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

You can start building tomorrow if you first add five short clarifications to the doc. The core design is sound: the stock update can't oversell, the payment call is retry-safe, the email can't fail an order, and stuck orders are reconciled and alerted on. The problems are gaps in what the doc specifies, not things that need redesigning. Two of them can lose or corrupt stock, so fix those before you write code.

## Must fix before coding

**1. The reconciliation job can restore stock twice. (High)**
You run two instances, and as written each one runs the job every 5 minutes. The "mark `FAILED` and restore stock" step also doesn't check the order's current status.
- **Example:** an order holds the last unit of SKU X, so `available` is 0. The charge times out and the order stays `PENDING`. At 12:05 both instances ask the provider, both hear "declined", and both run the step. `available` becomes 2 when you only have 1 unit, so you oversell on the next order.
- **Expected:** stock is restored once and `available` ends at 1.
- **Fix:**
  - Make every status change conditional, for example `UPDATE orders SET status='FAILED' WHERE id=:id AND status='PENDING'`. Only restore stock if that update changed a row.
  - Make sure only one instance runs the job at a time, for example with a Postgres advisory lock or `FOR UPDATE SKIP LOCKED`.
  - Use the same conditional update in steps 4 and 5.

**2. The doc doesn't say what reconciliation does when the provider has no record of the charge. (High)**
If an instance crashes after step 2 commits but before step 3 calls the provider, the provider never saw the charge. Step 6 only covers settling as `PAID` or `FAILED`, so this order stays `PENDING` forever and keeps its stock reserved. The 30-minute alert fires, but nothing fixes it.
- **Fix:**
  - State that "charge not found" (after the 2-minute grace period) means `FAILED` plus stock restore.
  - State that a reconciliation `FAILED` also restores stock (only step 5 says so today).
  - State that a reconciliation `PAID` also queues the confirmation email.

**3. The doc doesn't say where prices come from. (High, security)**
`POST /orders` "sends the cart". If `unit_price` or `total` comes from the request, a client can set its own price. The doc should say the server looks up prices from the catalog and ignores any prices the client sends.

**4. The module rule contradicts the flow. (Medium, architecture)**
The doc says "no module reads another module's tables". But steps 2 and 5 write to `stock` and `orders` in one transaction. Pick one option and write it down:
- **Recommended:** the inventory module exposes `reserve(tx, items)` and `release(tx, items)`, and `OrderCheckout` passes in the open transaction. That keeps the atomicity and the module boundary.
- **Alternative:** accept that orders and inventory share a transaction, and say so.

**5. Two concurrent orders can deadlock. (Medium)**
- **Example:** two carts contain SKUs {A, B} and {B, A}. One transaction locks A and waits for B; the other locks B and waits for A. Postgres aborts one with a deadlock error, which the design doesn't handle.
- **Fix:** sort the cart items by SKU before the updates, and merge duplicate SKUs in a cart into one line with the total quantity.

## Should fix (you can do these during the build)

- **Two requests with the same key at the same moment (Medium):** both can get past a "does this key exist?" check. The second insert then hits the unique constraint. Catch that error and return the existing order instead of a 500.
- **Idempotency key scope (Medium):**
  - Make the unique constraint `(customer_id, idempotency_key)`. With a global constraint, two customers who happen to send the same key collide.
  - Return `422` when a key is reused with a different cart.
- **Confirmation email can be lost (Medium):** a crash between "commit `PAID`" and "queue email" loses the email. Insert the email job into an outbox table in the same transaction as the status change.
- **Clients have no way to poll after a `202` (Medium):** add `GET /orders/{id}` so a client can poll for the final status.
- **Retry rules (Low):** retry only on timeouts and 5xx errors, never on a decline. The worst case is roughly 4 × 5 s plus backoff, about 27 s. Check that this fits inside the load balancer and client timeouts.
- **Data model gaps (Low):**
  - The table lacks primary and foreign keys: PK on `stock.sku`, PK and FK on `order_items`.
  - Add `CHECK (available >= 0)`, a check constraint on `status`, and a `provider_charge_id` column on `orders` for refunds and support.

## Test gaps (Medium)

The test list covers the main paths but misses these:
- a decline restores stock;
- reconciliation settling `PENDING` as `PAID`, as `FAILED`, and as "charge not found";
- two overlapping reconciliation runs restore stock only once;
- two buyers racing for the last unit;
- two concurrent requests with the same idempotency key;
- a crash after step 2 commits;
- email failure leaves the order `PAID`.

## Order lifecycle after fixes 1 and 2

```mermaid
stateDiagram-v2
    [*] --> PENDING: stock reserved, order inserted
    PENDING --> PAID: charge succeeded (request or reconciliation)
    PENDING --> FAILED: declined, or provider has no record of the charge
    PAID --> [*]: confirmation email queued
    FAILED --> [*]: stock restored once
```

Each arrow is a conditional update (`WHERE status='PENDING'`), so only the first writer moves the order and does the follow-up work.

Fixes 1–5 are a few sentences each in the doc plus matching tests. None of them changes the overall flow.

VERDICT: READY WITH CHANGES
