# Review of design.md (checkout flow, revision 2)

The overall design holds up and fits the scale. Taking the payment call out of the database transaction, keeping orders whose payment result is unknown as `PENDING` and settling them later, and alerting on stuck orders are all the right calls for 2,000 orders a day. But three parts of the flow will lose money or stock as written: a customer can be charged twice, the last unit of stock can be sold twice, and the same order can be created twice. Each one needs a small fix to the doc before you write that step. None of them changes the architecture.

## Must fix before building

**1. Retries can charge the customer twice (step 3).**
The idempotency key is `<order id>-<attempt number>`, so every retry looks like a new charge to the provider.
- Case: attempt 1 succeeds at the provider, but the response is lost and the call times out after 5 s. Attempt 2 is sent with key `abc-2`, and the provider charges the card again.
- Expected: one charge. Actual: two.

```mermaid
sequenceDiagram
    participant S as order-service
    participant P as Payment provider
    S->>P: charge, key abc-1
    P-->>P: card charged
    P--xS: response lost (timeout)
    S->>P: retry, key abc-2
    P-->>P: card charged again
    P->>S: success
```

Fix: use the same key on every attempt, ideally the order id. To trace attempts in the provider's dashboard, put the attempt number in the charge metadata, not in the key. A stable key also lets the reconciliation job look up the charge with a single query.

**2. The last unit of stock can be sold twice (step 2).**
"Read `available`, then write `available - quantity`" is a lost update under Postgres's default isolation level (READ COMMITTED). Wrapping it in a transaction doesn't prevent this.
- Case: `available = 1`. Two checkouts each read 1, each write 0, and both commit.
- Expected: one order and one `409`. Actual: two orders for one unit.

Fix: decrement in one statement, `UPDATE stock SET available = available - $q WHERE sku = $sku AND available >= $q`, and treat 0 rows updated as "short" (roll back and return 409). Update the items in a fixed order (sorted by sku) so that two multi-item carts can't deadlock each other. Add `CHECK (available >= 0)` as a safety net.

**3. Duplicate requests create duplicate orders (step 1).**
Each instance keeps the idempotency keys in its own memory, but there are two instances behind the load balancer, and every restart or deploy empties the map.
- Case: the client retries `POST /orders` after a network blip, and the load balancer sends the retry to the other instance.
- Expected: the existing order comes back. Actual: a second order, a second stock decrement and a second charge.

Fix: add an `idempotency_key` column on `orders` with a unique constraint (scoped by `customer_id` if keys are only unique per client), inserted in the step 2 transaction. On a unique violation, return the existing order.

**4. Status changes need to be conditional, and reconciliation needs more rules (step 6).**
- When reconciliation settles an order as `FAILED`, the doc doesn't say it restores stock. Step 5 does this; reconciliation must too, or declined orders keep their stock reserved forever.
- Both instances will run the job every 5 minutes, so both can process the same order. If both settle it as `FAILED`, the stock is restored twice. Fix: write every transition as `UPDATE orders SET status = ... WHERE id = $id AND status = 'PENDING'`, and only restore stock when that update hits a row. Optionally, also take a Postgres advisory lock or use `FOR UPDATE SKIP LOCKED` so only one job instance works at a time.
- If the service crashes after step 2 commits but before the charge is sent, the provider has no record of the order. Define what happens: the provider reports "not found", the order goes to `FAILED`, and stock is restored.

**5. Store money as an exact type.**
`total` and `unit_price` are `double precision`, so binary rounding errors creep in (for example, 0.1 + 0.2 ≠ 0.3), and totals won't always match the provider's amounts. Use `numeric(12,2)` or integer minor units (cents).

## Should fix (small, do while building)

- **Module boundaries conflict with step 2.** The doc says "no module reads another module's tables", but step 2 writes to `stock` (inventory) and `orders` (orders) in one transaction. Decide how that works, e.g. `OrderCheckout` opens the transaction and passes it to both modules' repositories. Otherwise someone will put stock SQL directly into the orders code.
- **Confirmation emails can be lost.** If the process dies between committing `PAID` and queueing the email, no email is sent. If the queue lives in Postgres, insert the email job in the same transaction as the `PAID` update (the outbox pattern).
- **Clients have no way to see the outcome of a 202.** After a `202`, the client needs some way to learn the result, e.g. `GET /orders/{id}`. Add it to the doc.
- **The schema has gaps.** Add primary keys on `stock(sku)` and `order_items(order_id, sku)`, and a `CHECK` constraint on `status` for the three allowed values.

## Tests to add

The current list doesn't cover any of the fixes above. Add:
- Two concurrent checkouts for the last unit: one succeeds and one gets 409. This needs real concurrency against real Postgres; the current single-threaded "last unit" test can't catch the oversell.
- The same idempotency key sent to two different service instances, or to one instance after a restart.
- A timeout where the fake provider *did* charge, followed by a retry. Assert there is exactly one charge.
- Reconciliation: settles a pending order as `PAID`; settles it as `FAILED` with stock restored; handles "provider has no record"; two job runs on the same order restore stock only once.
- The email-queue failure path.

## Bottom line

The architecture is sound. Fixes 1 to 5 above take roughly an hour of edits to the doc and schema. Make them before you build steps 1–3 and 6, and write the matching tests first. You can start the module layout and the routes tomorrow as planned.

VERDICT: READY WITH CHANGES
