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

**The design is close. You can start building tomorrow if you first settle four items. Each one is a sentence or two in the doc, not a redesign.** The core is right: stock is reserved with a guarded `UPDATE`, the payment call happens outside the database transaction, the provider idempotency key is the order id, there's a reconciliation job for unknown results, and email failures can't fail the order.

## Fix before building

**1. Stock can be restored twice when two runs settle the same order.** Both instances run the reconciliation job every 5 minutes, and nothing in the doc stops two runs from settling the same order.
- Case: order X has been `PENDING` for 3 minutes. The provider reports it declined. Instance A and instance B both mark it `FAILED` and both run `available = available + qty`.
- Wrong result: stock for that SKU goes up by 2 × qty.
- Expected: it goes up by qty, once.
- 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. This also covers a late response on the request path racing the job. Optionally add `FOR UPDATE SKIP LOCKED` or a Postgres advisory lock so only one instance runs the job at a time.

**2. Reconciliation has no rule for "the provider has no record of this charge."** This happens when the process crashes after step 2 commits but before step 3 sends anything. The order stays `PENDING` forever, and the stock stays reserved until the 30-minute alert pages a person.
- Decide the rule: treat "not found" after 2 minutes as `FAILED` and restore stock, or retry the charge with the same order id as the key. Write it down.
- Also say outright that settling an order as `FAILED` in reconciliation restores stock, the same as step 5.

**3. Orders that reconciliation settles as `PAID` get no confirmation email.** Only step 4 queues the email. The customers whose payment timed out are the ones who most need that email. The email also has a crash gap:
- Case: the service commits `PAID`, then crashes before it queues the email.
- Wrong result: the customer was charged and gets no email.
- Expected: the email is sent.
- Fix: write an outbox row (a pending-email record in Postgres) in the same transaction that sets `PAID`, on both the request path and the reconciliation path. A worker sends emails from the outbox.

**4. Where do `unit_price` and `total` come from?** The flow says the client "sends the cart," and there's no price or catalog source in the data model. If prices come from the client, anyone can buy at £0.01. State that the server looks up prices, and from which module.

## Small changes, add while building

- **Deadlock on multi-item orders.** Order 1 reserves SKU A then B while order 2 reserves B then A. Postgres aborts one of them, and the client gets a 500 instead of an order or a `409`. Fix: reserve SKUs in sorted order.
- **Duplicate key with a different cart.** As written, a reused `Idempotency-Key` with a different cart silently returns the old order. Store a hash of the request body and return `422` if it doesn't match. Also decide whether the key is unique globally or per `customer_id`.
- **A `202` needs a way to check back.** Add `GET /orders/{id}` so the client can poll for the final status.
- **Data model gaps.**
  - Primary keys: `stock.sku`, and `order_items (order_id, sku)`.
  - `CHECK (available >= 0)` on `stock`.
  - A foreign key from `order_items` to `orders`.
  - A `provider_charge_id` column, for support and refunds.
  - An index on `(status, created_at)` for the reconciliation query.
- **Module boundary.** Step 2 writes `stock` and `orders` in one transaction, which looks like it breaks "no module reads another module's tables." Decide how they share the transaction. I suggest the inventory module exposes `reserve(tx, items)` and `release(tx, items)`, and `OrderCheckout` owns the transaction.

## Tests to add to the plan

The current list covers only the request path. Add:
- Reconciliation tests: provider says paid, provider says declined, provider says not found.
- Two reconciliation runs on the same order: stock is restored exactly once.
- Two concurrent `POST /orders` with the same key: one order is created and stock is reserved once.
- A crash after step 2 (order is `PENDING`, no charge was sent), recovered by reconciliation.
- Two multi-SKU orders in opposite SKU order at the same time: no deadlock.
- An email is sent for orders settled by reconciliation.

## Order status lifecycle, with the gaps marked

```mermaid
stateDiagram-v2
    [*] --> PENDING: POST /orders (stock reserved)
    PENDING --> PAID: charge succeeds (sends email)
    PENDING --> FAILED: charge declined (restores stock)
    PENDING --> PAID: reconciliation says paid (GAP: no email)
    PENDING --> FAILED: reconciliation says declined (GAP: stock restore not stated, can run twice)
    PENDING --> PENDING: provider has no record (GAP: no rule)
```

Volume isn't a concern: 2,000 orders a day is light for this setup.

VERDICT: READY WITH CHANGES
