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

**You can start building tomorrow, but fix two gaps in the doc first. Each fix is a sentence or two.** The core of the design is sound. Stock is reserved with a conditional update, the payment call happens outside any open transaction, the provider gets a stable idempotency key, and a reconciliation job settles orders whose result is unknown. Most of what's below is small, but the first two items would cause real bugs in production.

## Must fix before building

**1. Stock can be restored twice. (High)**
- **Where:** Step 5 (`design.md:33-34`) restores stock when an order becomes `FAILED`. Step 6 (`design.md:36-38`) runs the reconciliation job, and Context (`design.md:6`) says there are two service instances. The doc doesn't say the job runs on only one instance, and it doesn't say a status change only happens if the order is still `PENDING`.
- **Failing case:** Order X (2 × SKU-A) times out on every attempt. Both instances run reconciliation at the same moment, and both learn the charge was declined. Both mark X `FAILED` and both add 2 back to SKU-A.
  - Wrong result: stock goes up by 4.
  - Expected: stock goes up by 2.
  - Result: you oversell later.
- **Fix:** Make every status change conditional: `UPDATE orders SET status = ... WHERE id = :id AND status = 'PENDING'`. Restore stock only when that update changed exactly one row. This also protects steps 4 and 5. Optionally, also make the job run on one instance only, for example with a Postgres advisory lock.

**2. Reconciliation has no rule for "the provider has no record of this charge." (Medium)**
- **Where:** Step 6 settles orders "as `PAID` or `FAILED`" only.
- **Failing case:** All 4 attempts time out before reaching the provider (5 s each, plus backoff). Reconciliation asks for the status and gets "not found."
  - Wrong result: as written, the order stays `PENDING` forever, holds its stock, and fires the 30-minute alert (`design.md:45`).
  - Expected: the order is settled.
- **Fix:** Decide the rule and write it down. Either re-send the charge with the same order-id key, or mark the order `FAILED` and restore stock. After 2 minutes no retry from the original request can still be in flight, so either choice is safe.

## Should fix (small, but cheaper now than later)

**3. Where do prices come from? (Medium, needs an answer)**
`order_items.unit_price` and `orders.total` exist, but no table holds prices (`design.md:12-14`), and step 1 only mentions "the cart." If prices come from the client's cart, a client can send a price of 0.01. State that the server looks up prices from a source you trust.

**4. Possible deadlock on stock updates. (Low to medium)**
Step 2 updates stock rows in cart order.
- **Failing case:** Order 1 has [A, B] and order 2 has [B, A], both at the same time. Postgres aborts one of them with a deadlock error, which becomes a 500. Neither a 409 nor a retry happens.
- **Fix:** Sort SKUs before updating, and merge duplicate SKU lines in the cart first.

**5. Two requests with the same `Idempotency-Key` at the same time. (Low)**
`design.md:20-21` says a repeated key "returns the existing order." That holds once the first order is committed. If two requests are in flight at once, the second one hits a unique-constraint error at insert time. Its transaction rolls back, including its stock changes, so the data stays correct. But the code must catch that error and return the existing order rather than a 500. Also decide what happens when the same key arrives with a different cart. A 422 is a common choice.

**6. Orders settled by reconciliation get no confirmation email. (Low to medium)**
Only step 4 queues the email. An order that times out, was actually charged, and is later marked `PAID` by reconciliation never gets one. Also, the email is queued *after* the commit. If the process crashes between those two steps, the email is lost. Inserting a row into an outbox table inside the same `PAID` transaction fixes both problems.

**7. After a 202, how does the client find out the result? (Low)**
No `GET /orders/{id}` endpoint, polling rule, or webhook is described.

**8. Missing constraints in the data model. (Low)**
- No primary key on `order_items`.
- `stock.sku` isn't declared as the primary key.
- `idempotency_key` is unique across all customers rather than per `customer_id`. This is fine if clients use UUIDs; just make it a deliberate choice.

**9. Client wait on the worst path. (Low)**
4 attempts × 5 s plus backoff is roughly 25 s or more. Check that this fits under the load balancer's timeout and the client's timeout.

## Test plan gaps

These are worth adding given the TDD-first approach (`design.md:47-51`):
- Reconciliation: charge found as paid, found as declined, not found, and two runs at once (this would catch item 1).
- Two buyers racing for the last unit, as opposed to one buyer taking it.
- 409 when quantity is greater than available, with no partial reservation left behind.
- Same idempotency key sent at the same time; same key with a different cart.
- A decline restores stock exactly once.
- Opposite SKU orders running at the same time (item 4).

## Order lifecycle with the fixes applied

```mermaid
stateDiagram-v2
    [*] --> PENDING: stock reserved + order inserted (one txn)
    PENDING --> PAID: charge succeeded (only if still PENDING)
    PENDING --> FAILED: declined, or provider has no record (only if still PENDING)<br/>stock restored in same txn
    PAID --> [*]: confirmation email via outbox
    FAILED --> [*]
```

Not a concern: at 2,000 orders a day, one Postgres database and two instances are plenty, and the module split and thin-route structure are fine as written.

VERDICT: READY WITH CHANGES
