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

You can start building tomorrow, but first add four short rules to the doc. The overall approach is sound: stock is reserved in one transaction, the payment call happens outside any transaction with the order id as the provider's idempotency key, there is a reconciliation job, and email can never fail an order. The gaps are in edge cases the doc doesn't define yet. Each one is a few sentences to add, not a redesign. Two of them could corrupt stock counts or leave orders stuck in production.

## Must fix before building

**1. Status changes aren't guarded, so stock can be restored twice. (High)**
Steps 5 and 6 say "mark `FAILED` and restore stock". Nothing says this only happens if the order is still `PENDING`, and nothing says the job runs on only one of the two instances.
- **Example:** order X is `PENDING` and the provider says it was declined. The reconciliation job runs on both instances at the same time. Both mark X `FAILED` and both add the quantity back to `available`.
- **Result:** the stock count goes up by 2× the quantity. It should go up by 1×.
- The same thing can happen if a slow request thread and the job both settle the same order.
- **Fix:** make every status change conditional, e.g. `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. Also say how the job runs only once at a time, for example with a Postgres advisory lock or `SELECT … FOR UPDATE SKIP LOCKED`.

```mermaid
stateDiagram-v2
    [*] --> PENDING: stock reserved, order inserted
    PENDING --> PAID: only if still PENDING
    PENDING --> FAILED: only if still PENDING (stock restored once)
    PAID --> [*]
    FAILED --> [*]
```

**2. Reconciliation has no rule for "the provider has no record of this charge". (High)**
Step 6 assumes the provider always answers "paid" or "declined". But an order can be `PENDING` without any charge ever reaching the provider.
- **Example:** an instance crashes right after step 2 commits and before step 3 sends the charge. The provider reports "not found".
- **Result:** the job can't settle the order, so it stays `PENDING` forever and its stock stays reserved. It should end up `FAILED` with the stock restored.
- **Fix:** add the rule "not found and older than N minutes → `FAILED`, restore stock". Because no more retries happen at that point, a late duplicate charge can't arrive afterwards. Also check how long the provider honours idempotency keys (some expire after about 24 h) and make sure reconciliation always runs well inside that window.

**3. After a 202, the client has no way to learn the final result. (Medium)**
Step 6 returns `202`, but the doc doesn't define a `GET /orders/{id}` endpoint or any other way for the client to see the order become `PAID` or `FAILED`. Add the endpoint, or say which existing one the client should poll.

**4. Duplicate requests that arrive at the same time aren't handled. (Medium)**
"A repeated key returns the existing order" works when the second request arrives after the first has committed. If two requests with the same key arrive together, both run step 2, and the second hits the unique-constraint error. The doc should say: catch that error, roll back (which also undoes the second request's stock decrement), and return the existing order. The doc should also say:
- what happens when the same key arrives with a *different* cart (usual answer: return `422`)
- whether the key is unique per customer or across all customers. If it's unique across all customers, a reused key could hand customer A customer B's order.

## Should fix (can be settled during the build)

- **The confirmation email can be lost. (Medium)** Step 4 commits `PAID` and only then queues the email. If the process crashes between those two steps, the email never goes out. Fix: write an outbox row in the same transaction as the `PAID` update. Also say whether orders that reconciliation marks `PAID` get the email; right now the doc doesn't say.
- **Multi-item orders can deadlock. (Low–Medium)** Two concurrent orders that update the same SKUs in different orders (A then B, versus B then A) can deadlock. Fix: update SKUs in sorted order, and treat a deadlock error as retryable.
- **The doc doesn't say how one transaction spans two modules. (Low)** Step 2 touches both `stock` (inventory module) and `orders` (orders module) in one transaction, while the module rule says no module reads another's tables. That works, but write down the mechanism, e.g. each module's repository accepts a transaction passed in by `OrderCheckout`. Otherwise someone will break the boundary to make the transaction work.
- **The retry policy only covers timeouts. (Low)** Say explicitly that declines and other 4xx responses are never retried, and decide what happens on 5xx responses.
- **The data model is missing constraints. (Low)** No primary keys are listed: `orders.id`, `stock.sku`, and `order_items (order_id, sku)` need them, and `order_items.order_id` needs a foreign key. Add `CHECK (available >= 0)` and `CHECK (quantity > 0)`. Declare the unique index on `idempotency_key` in the table itself, not only in the flow text.
- **Some tests are missing. (Medium)** Add tests for:
  - reconciliation settling `PAID`, `FAILED` and "not found"
  - the reconciliation job and the request thread racing on the same order (issue 1)
  - concurrent duplicate `POST`s (issue 4)
  - two buyers racing for the last unit, not just one buyer taking it
  - a crash between step 2 and step 3

## A question, not a confirmed problem

- **Where do prices come from?** "The client sends the cart." If `unit_price` or `total` come from the client rather than a server-side lookup, a client could set its own price. The doc doesn't say either way. One sentence would settle it.

## Fine as written

At 200–2,000 orders a day, one Postgres database and two instances is plenty. A request can take up to about 25 s while it waits on payment retries, which is acceptable at this volume. The 30-minute `PENDING` alert and logging the order id on every line are good choices.

VERDICT: READY WITH CHANGES
