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

You can start building tomorrow if you make a few small changes to the design first. The overall shape is right. Stock is reserved in one transaction and the charge happens outside it. The order id is the payment idempotency key, so retries can't double-charge. There's a reconciliation job and an alert for stuck orders. None of what I found needs a redesign. Two issues can corrupt stock counts, though, and should be fixed in the doc before any code exists. Together the changes are maybe an hour of editing.

## Must fix before building

**1. High: stock can be restored twice for one failed order.**
The service runs on two instances. As written, each instance would run the reconciliation job every 5 minutes. Nothing says a status change only happens if the order is still `PENDING`.
- **Case:** order X for 2 units of SKU A is stuck `PENDING`. Both instances' jobs pick it up and the provider says "declined" to both. Each marks it `FAILED` and adds 2 back to stock.
- **Actual:** `available` goes up by 4. **Expected:** it goes up by 2.

The same race can happen between the request path and the job, or between two jobs. **Fix:** make every transition conditional, e.g. `UPDATE orders SET status='FAILED' WHERE id=:id AND status='PENDING'`, and restore stock only if that update changed a row. Also run the job on one instance at a time, using a Postgres advisory lock or `FOR UPDATE SKIP LOCKED`.

**2. High: a negative or zero quantity increases stock.**
- **Case:** a cart line has `quantity = -5`. The update `available - (-5) WHERE available >= -5` always matches.
- **Actual:** stock goes up by 5 and an order is created. **Expected:** the request is rejected with `400`.

**Fix:** validate `quantity > 0` at the API, and add `CHECK (quantity > 0)` on `order_items` and `CHECK (available >= 0)` on `stock`.

**3. Medium: the design doesn't say where `unit_price` and `total` come from.**
No table holds prices, and the client sends "the cart". If the prices come from the client, a buyer can set their own price. **Fix:** state that prices are looked up on the server (from which module or table) and that `total` is computed on the server.

**4. Medium: reconciliation has no rule for "the provider has no record of this charge".**
- **Case:** an instance crashes after step 2 commits but before step 3 sends the charge. The provider has never seen the order.
- **Actual:** the job can only settle `PAID` or `FAILED`, so the order stays `PENDING`, the stock stays reserved, and the 30-minute alert fires every time.
- **Expected:** after N minutes with no record, the order becomes `FAILED` and its stock is released.

**Fix:** define what happens on "not found". Also say that the job reuses the same paths as steps 4 and 5: `PAID` queues the email, `FAILED` restores stock. Right now a customer whose charge timed out and later succeeded never gets a confirmation email.

## Should fix (small spec additions)

5. **Medium: concurrent duplicate requests.** When two `POST /orders` with the same key arrive together, the second insert hits the unique constraint and its transaction rolls back. Say that the service then looks up and returns the existing order. Also say what status code a repeat gets while the order is still `PENDING` (presumably `202`).
6. **Medium: the tests don't cover the riskiest paths.** Add tests for:
   - reconciliation settling to `PAID`, to `FAILED`, and to "not found"
   - two reconcilers racing on one order (catches issue 1)
   - concurrent duplicate `POST`
   - two buyers racing for the last unit
   - a decline restoring stock
   - a crash between step 2 and step 3
   - rejection of a zero or negative quantity
7. **Low: database deadlock on multi-item carts.** Cart A is [x, y] and cart B is [y, x] at the same moment, and Postgres aborts one of them. **Fix:** update SKUs in sorted order, merge duplicate SKU lines, and say that a deadlock is retried or returns `409`, not `500`.
8. **Low: a crash after commit can lose the confirmation email.** In step 4, if the instance dies between committing `PAID` and queuing the email, the email is lost. If the queue lives in Postgres, insert the email job in the same transaction (an outbox table).
9. **Low: the idempotency key is unique across all customers.** Make it `UNIQUE (customer_id, idempotency_key)` so one customer's key can never return another customer's order. Also make the header required (`400` if missing). Decide what happens when a repeated key arrives with a different cart.
10. **Low: some keys and limits are unstated.**
    - `stock.sku` should be the primary key, and `order_items` needs one, e.g. `(order_id, sku)`.
    - Retry only on timeouts and provider 5xx errors, never on declines.
    - Check that the worst-case request time fits under the load balancer timeout. With 4 attempts of 5 s each plus backoff, that is about 25–30 s.
11. **Low: transactions cross module boundaries.** Steps 2 and 5 touch both `orders` and `stock` in one transaction, which looks like it conflicts with "no module reads another module's tables". Say that the inventory module exposes `reserve()` and `release()` functions that join a transaction passed in by the caller.

## Speculative (not blocking)
- At 2,000 orders a day, a single Postgres instance and a 5-minute reconciliation interval are both fine. Nothing here needs to change for that growth.

Here are the order states once issues 1 and 4 are fixed. Each transition only happens if the order is still `PENDING`:

```mermaid
stateDiagram-v2
    [*] --> PENDING: stock reserved
    PENDING --> PAID: charge succeeded (request or reconciliation) / queue email
    PENDING --> FAILED: declined, or provider has no record after N min / restore stock
    PAID --> [*]
    FAILED --> [*]
```

**Next step:** add issues 1–4 to the doc, plus the extra tests from item 6. Items 5 and 7–11 are a sentence each and can go in at the same time or as you build.

VERDICT: READY WITH CHANGES
