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

**You can start tomorrow, but resolve four gaps first. Each needs about one sentence in the doc and a test.** The core of the design is sound. Stock is reserved with a conditional `UPDATE`. The payment call happens outside any transaction and reuses one idempotency key across retries. Unknown payment results go to a reconciliation job instead of being guessed. The gaps all sit on the paths where an order leaves `PENDING` some way other than the normal one.

## Fix before building

**1. When reconciliation marks an order FAILED, nothing says the stock comes back.**
Step 5 restores stock when a charge is declined. Step 6 says the reconciliation job "settles them as PAID or FAILED" but says nothing about stock.
- Case: someone orders 1 unit of SKU `A` (stock 5 → 4). The charge times out on every attempt, so the order stays `PENDING`. Reconciliation later finds the charge was declined and marks the order `FAILED`. Stock stays at 4, but it should be 5. One unit is lost each time this happens.
- Fix: every move to `FAILED` restores stock in the same transaction, whichever code path does it. Put that in one function in `OrderCheckout` that both paths call.

**2. Reconciliation doesn't handle "the provider has no record of this charge".**
- Case: an instance crashes after step 2 commits but before step 3 sends the charge. The order is `PENDING` with stock reserved. Reconciliation asks the provider about it and gets "not found", which is neither PAID nor FAILED. The order sits in `PENDING` and fires the 30-minute alert every time.
- Fix: decide what happens. I recommend having reconciliation send the charge again with the same idempotency key (the order id) rather than only asking for status. That returns a definite answer in every case and can't double-charge. The other option is to mark "not found" as `FAILED` and restore stock.

**3. Status changes need a guard, because two instances can settle the same order.**
Both instances will run the reconciliation job unless something stops that. The request path can also still be finishing while the job runs.
- Case: both instances' jobs pick up order X, both learn it was declined, and both run "mark FAILED and restore stock". Stock goes up by 2 for a 1-unit order.
- Fix: write every status change as `UPDATE orders SET status = :new WHERE id = :id AND status = 'PENDING'`. Only restore stock or queue the email if that update changed a row. This also makes it harmless that the job runs on both instances.

**4. The idempotency key rules leave out two cases.**
- Two identical `POST`s that arrive at the same moment. Both get past the "does this key exist?" check, and one then hits the unique constraint. The design needs to say that this request rolls back its stock reservation and returns the existing order, not a `500`.
- The same key sent with a *different* cart. Right now the client silently gets back the old order. Store a hash of the request body and return `422` when it doesn't match.
- Also say what the key is unique within: unique per `(customer_id, idempotency_key)` is safer than globally unique.

## Fix during the build (small, but write them down)

- **Where prices come from.** `unit_price` and `total` are stored, but the design doesn't say where they come from. If they come from the client's cart, a client can set its own price. State that the server looks prices up, and name the module or table that owns them.
- **Deadlocks with more than one item.** If two orders lock the same SKUs in opposite order (`A,B` and `B,A`), Postgres will kill one of them with a deadlock error. Sorting SKUs before the `UPDATE`s prevents it.
- **Lost confirmation emails.** If the process dies between the `PAID` commit and queuing the email, the customer never gets one. Writing the email job into the same transaction (an outbox table) closes this. If you'd rather not, write it down as a known gap.
- **Module boundary.** Step 2 puts `stock` and `orders` in one transaction, but the modules may not touch each other's tables. That's fine if inventory exposes something like `reserve(tx, items)` that runs inside the caller's transaction. Say so explicitly so nobody "fixes" it by splitting the transaction.
- **Database constraints.** Add a primary key on `stock.sku`, `CHECK (available >= 0)` and `CHECK (quantity > 0)`, a foreign key from `order_items` to `orders`, and a check constraint on `status`.
- **Response codes.** Steps 4 and 5 don't say what the client gets on success or on decline (e.g. `201` and `402`).

## Tests to add to the plan

- Reconciliation: a `PENDING` order settles as `PAID`; settles as `FAILED` with stock restored; "not found" at the provider; two job runs on the same order restore stock only once.
- Two concurrent `POST`s with the same key, and the same key with a different body.
- Two *concurrent* buyers of the last unit. The current test, "buying the last unit of stock", reads like a single buyer.
- A crash after step 2 (stock reserved, no charge sent) that reconciliation recovers.
- Multi-item orders with overlapping SKUs in opposite order (the deadlock case).

## Order lifecycle with the fixes applied

```mermaid
stateDiagram-v2
    [*] --> PENDING: stock reserved + order inserted (one transaction)
    PENDING --> PAID: charge succeeds (request or reconciliation)
    PENDING --> FAILED: declined or not found (request or reconciliation), stock restored
    PAID --> [*]: email queued
    FAILED --> [*]
```

Every arrow out of `PENDING` uses the guarded `WHERE status = 'PENDING'` update. Leaving `PENDING` for `FAILED` always includes restoring stock.

VERDICT: READY WITH CHANGES
