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

**It is not ready to build yet.** The parts that protect against double charges, overselling and duplicate orders each have a hole that will happen under normal traffic. Most fixes are a line or two in the doc, so you can probably close them tonight. The structure, the module split and the plan to reconcile unknown payments are sound.

## Must fix before building

**1. Charging the same customer twice (step 3).** The payment idempotency key is `<order id>-<attempt number>`, so the provider sees every retry as a new charge.
- *Case:* attempt 1 charges the card, but the response is lost when the 5 s timeout fires. Attempt 2 uses `…-2`, and the provider charges again.
- *Expected:* one charge. *Actual:* two.
- *Fix:* use one stable key per order, such as the order id. To trace attempts, log the attempt number on your side instead of putting it in the key. This also fixes reconciliation, which right now has no single charge to look up.

**2. Overselling the last unit (step 2).** The design reads `available` and then writes `available - quantity`. Postgres defaults to READ COMMITTED isolation, and at that level two transactions can both read the same value.
- *Case:* `available = 1`, and two customers check out at the same moment. Both read 1, both write 0, and both orders succeed.
- *Expected:* one order succeeds and one gets `409`. *Actual:* two units sold, only one exists.
- *Fix:* `UPDATE stock SET available = available - $q WHERE sku = $s AND available >= $q`. If that touches 0 rows, roll back and return `409`. Also add `CHECK (available >= 0)` as a backstop.

**3. Duplicate orders from a repeated request (step 1).** Idempotency keys live in a per-instance map, but there are two instances behind the load balancer, and the map is lost on every restart or deploy.
- *Case:* the client times out and retries. The step 3 retries alone can hold the request for about 20–30 s. The load balancer sends the retry to the other instance, which has never seen the key.
- *Expected:* the existing order is returned. *Actual:* a second order, a second stock reservation and a second charge.
- *Fix:* add an `idempotency_key` column on `orders` with a `UNIQUE` constraint (or a separate keys table), and insert it in the same transaction as the order. Store the response too, so a repeated `409` gives back the same answer.

**4. Money stored as `double precision`.** Floating point can't represent most decimal amounts exactly.
- *Case:* three items at 0.10 add up to `0.30000000000000004`, and totals stop matching the provider and your accounting.
- *Fix:* use `numeric(12,2)`, or integer minor units (cents) with `bigint`.

**5. Two writers can settle the same order, and stock can be restored twice.** The request path (steps 4–5) and the reconciliation job can both settle an order. The job will also run on both instances unless you prevent it.
- *Case:* both instances' jobs pick up the same order, and both mark it `FAILED` and restore stock. `available` goes up by 2× the quantity.
- *Fix:* every status change should be `UPDATE orders SET status = $new WHERE id = $id AND status = 'PENDING'`. Only restore stock if that update changed a row, and do it in the same transaction. Use `SELECT … FOR UPDATE SKIP LOCKED` or an advisory lock so the job's runs don't overlap.

**6. Reconciliation leaves out two outcomes.**
- *Provider says "no such charge":* this happens if the process crashes after step 2 commits but before step 3 runs. The design only lists PAID or FAILED as outcomes. If the charge isn't found, the job should mark the order `FAILED` and restore stock. If it doesn't, those units stay reserved forever and your 30-minute alert fires on every crash.
- *Settling as `FAILED`:* the doc doesn't say whether this restores stock. It should, through the same code path as step 5.

```mermaid
stateDiagram-v2
    [*] --> PENDING: stock reserved + order inserted (one tx)
    PENDING --> PAID: charge succeeded (request or reconciliation)
    PENDING --> FAILED: declined / not found at provider + stock restored (one tx)
    PAID --> [*]
    FAILED --> [*]
```
Every arrow above should be a conditional update from `PENDING`, so whichever writer gets there second does nothing.

## Should fix (smaller)

- **Lost confirmation emails (step 4).** If the process dies between committing `PAID` and queueing the email, the email is never sent. Write an outbox row in the same transaction, or have the job also scan for `PAID` orders with no email sent. At 2,000 orders a day this will happen occasionally.
- **The design contradicts its own module rule.** "No module reads another module's tables," yet step 2 writes `stock` and `orders` in one transaction. Choose and write down how this works, for example: the inventory module exposes `reserve(tx, items)`, takes the caller's transaction, and owns the SQL. Otherwise someone will end up writing raw stock SQL inside `OrderCheckout`.
- **The `202` response leaves the client nowhere to go.** Specify `GET /orders/{id}` so the client can poll for the result.
- **Missing keys in the schema.** There's no primary key on `stock.sku` or `order_items`, and no foreign key from `order_items.order_id`.
- **Request time is too long.** 4 attempts × 5 s plus backoff holds the HTTP request open for 20–30 s, which invites the client retries from item 3. Consider fewer retries in the request path, and let reconciliation handle the slow cases.

## Tests to add (your test list misses every bug above)

- Two checkouts racing for the last unit, run genuinely in parallel against real Postgres. Exactly one should succeed.
- The same `Idempotency-Key` sent to two different service instances (or after a restart), giving one order.
- A fake provider that charges the card but times out on the response, then a retry: assert only one charge. Your current "timeout then success" test passes even with the double-charge bug, unless the fake actually records a charge on the timed-out attempt.
- Reconciliation tests: charge found as paid, as declined, and as not found. Also two job runs at once, asserting stock is restored only once.
- A crash between step 2 and step 3, which reconciliation should settle as `FAILED` with stock restored.
- Money totals using amounts like 0.10 × 3.

If you fix items 1–6 and add the race and crash tests, I'd expect the next revision to be ready to build.

VERDICT: NOT READY
