# Review of design.md (order-service checkout, revision 3)

You can start tomorrow, but fix four things in the doc first. Each one is a short edit, and each one would otherwise ship as a bug that loses money or stock. The rest of the design is sound: reserving stock with a conditional update, calling the payment provider outside the transaction, using the order id as the provider's idempotency key, and running a reconciliation job are all the right choices for 2,000 orders a day and a team of four.

## Fix before writing code

**1. The design never says where `unit_price` comes from.** No table holds prices, so the only source the doc implies is the client's cart. Example: a client posts `{sku: "A1", quantity: 1, unit_price: 0.01}` for a $50 item. The order total becomes $0.01 and the charge goes through. Expected: the server looks up the price from a catalog it trusts and ignores any price the client sends. Name that source and add a test that sends a tampered price.

**2. Both instances run the reconciliation job, and nothing stops two writers from settling the same order.** That can return stock twice. Example: instance A and instance B both pick up order X, both get "declined" from the provider, and both run "mark FAILED and restore stock." Stock for a 2-unit order goes up by 4. The same thing happens if the request path's decline handling and the reconciliation job race on one order. Expected: stock is restored exactly once. To get that:
- Make every status change conditional: `UPDATE orders SET status = 'FAILED' WHERE id = :id AND status = 'PENDING'`. Restore stock only if that update changed a row, and do both in the same transaction.
- Have the job claim its rows with `SELECT … FOR UPDATE SKIP LOCKED`, or take a Postgres advisory lock, so only one instance processes a given order.

```mermaid
stateDiagram-v2
    [*] --> PENDING: stock reserved, order inserted
    PENDING --> PAID: only if status is still PENDING
    PENDING --> FAILED: only if status is still PENDING, stock restored in same transaction
    PAID --> [*]
    FAILED --> [*]
```

**3. Two paths can lose the confirmation email.**
- Step 4 commits `PAID` and then puts the email on the queue. If the process crashes between those two steps, the customer is charged and never gets an email.
- Orders that reconciliation marks `PAID` (the timeout path) never queue an email at all; the doc doesn't mention it.

Fix: insert an outbox row (a record of the email to send) in the same transaction that sets `PAID`, on both paths, and have a worker send from that table. Also name the queue technology, because the doc currently doesn't.

**4. Reconciliation handles only two provider answers, but there are four.** The provider can say paid, declined, not found, or still processing. "Not found" is a normal result: the service committed `PENDING` and then crashed before it called the provider. Decide what each answer does. My suggestion: not found and older than the retry window → `FAILED`, restore stock. Still processing → leave it alone and let the 30-minute alert catch it.

## Should fix, small

- **Idempotency key scope.** The unique constraint covers `idempotency_key` alone, so if two customers' clients generate the same key, customer B gets customer A's order back. Make it unique on `(customer_id, idempotency_key)`. Also store a hash of the request body: if the same key arrives with a different cart, return `422` instead of the old order.
- **Two requests with the same key at the same moment.** The second insert fails on the unique constraint and its transaction rolls back, which correctly undoes its stock reservation. The code must catch that unique-violation error and return the existing order, not a `500`. Write that down and test it.
- **Deadlocks.** Two carts that hold the same SKUs in opposite order (`[A, B]` and `[B, A]`) can deadlock in step 2. Sort SKUs before running the updates, and merge duplicate SKUs within a cart first.
- **The `202` response has no follow-up.** The client has no way to learn the final result. Add `GET /orders/{id}`, or say that the client should poll by resending the same idempotency key.
- **Retry policy.**
  - Retry only on timeouts and provider 5xx errors, never on a decline.
  - Worst case is about 20 s of timeouts plus backoff, all inside one HTTP request. Check that this fits under the load balancer's timeout.
  - Check that it fits well inside the 2-minute threshold, so reconciliation never picks up an order that the request path is still retrying.
- **Module boundary contradiction.** The doc says no module reads another module's tables, yet steps 2 and 5 update `stock` and `orders` in one transaction. Say how: for example, inventory exposes `reserve(tx, items)` and `release(tx, items)`, and both take the caller's transaction.
- **Missing constraints in the schema.**
  - Primary keys on all three tables (`stock.sku`; `(order_id, sku)` for `order_items`).
  - A foreign key from `order_items` to `orders`.
  - `CHECK (available >= 0)` and `CHECK (quantity > 0)`.
  - A `CHECK` on `status`.
  - Define how `numeric` totals become the provider's minor units (cents).

## Tests to add to the plan

The current list is good but covers only the request path. Add:
- decline restores stock exactly once
- reconciliation for each of the four provider answers
- two reconciliation runs at the same time on one order
- reconciliation racing the request path
- a crash after commit and before the charge (ends as "not found")
- two buyers racing for the last unit
- the same idempotency key sent concurrently, and with a different body
- a tampered client price
- an email outbox row written on both `PAID` paths

None of these require rethinking the design. They are decisions to write down plus guards to add. Items 1–4 are the ones that would cost money or stock in production, so put them in revision 4 before the first commit.

VERDICT: READY WITH CHANGES
