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

**The design is close, and you can start building tomorrow once you add about six short clarifications to the doc.** The main structure holds up: stock is reserved in one transaction, payment happens outside any transaction, the order id is sent to the provider as its idempotency key, and orders with an unknown result go to a reconciliation job. Nothing needs redesigning. What's missing are rules for a few cases that the code will hit. Two of them change stock counts, so write them down before anyone codes the payment and reconciliation paths.

## Must fix before building

**1. Status changes aren't guarded, so stock can be restored twice. (High)**
Steps 4, 5 and 6 say the service "marks" the order but never require it to still be `PENDING`. With two instances, the reconciliation job can run on both at once.
- Case: order X is `PENDING` with 2 units of SKU A. Both instances run reconciliation, both see a decline, and both mark X `FAILED` and add 2 back to stock.
- Wrong result: `available` goes up by 4. Expected: up by 2.
- Fix: every change of status runs `UPDATE orders SET status = :new WHERE id = :id AND status = 'PENDING'`. Restore stock (or queue the email) only if that update changed exactly one row. It's also worth letting only one instance run the job at a time, using a Postgres advisory lock.

**2. Reconciliation doesn't say what it does after it settles an order. (High)**
- Step 5 restores stock on a decline, but step 6 doesn't say reconciliation does the same when it settles an order as `FAILED`. Without that, those units never come back.
- Step 4 queues the confirmation email, but nothing says reconciliation does when it settles an order as `PAID`, so those customers get no email.
- Step 6 doesn't cover the provider answering "no such charge." For example, the instance crashed after step 2 committed and before it called the provider. The design should say whether that order becomes `FAILED` (and stock is restored) or the charge is retried.

**3. The design doesn't say where unit prices come from. (High)**
`order_items.unit_price` and `orders.total` exist, but the schema has no price or product table, and the design doesn't say the server looks prices up. If they come from the client's cart, the client sets its own price. State that the server looks up prices and computes the total.

**4. Cart input isn't validated. (High)**
- Case: the cart has `quantity: -5` for SKU A. The check `available >= -5` passes, and `available - (-5)` adds 5 units.
- Wrong result: the order goes through with a negative total and stock goes up. Expected: `400`.
- Fix: require `quantity > 0`, and add `CHECK (quantity > 0)` on `order_items` and `CHECK (available >= 0)` on `stock`. Merge duplicate SKU lines into one, or reject the cart.

## Should fix (cheap, and better done now)

**5. Two carts can deadlock each other. (Medium)** Cart 1 reserves SKU A then B while cart 2 reserves B then A. Postgres aborts one of them, and the design has no response defined for that, so it would probably surface as a `500`. Fix: always reserve SKUs in sorted order.

**6. A client that gets `202` has no way to find out what happened. (Medium)** The doc has no `GET /orders/{id}` and no notification. Add one of them.

**7. Duplicate requests that arrive at the same time aren't specified. (Medium)** If two requests with the same key overlap, the second one blocks on the unique constraint and then fails. Its stock reservation rolls back, which is fine. The code then has to catch that unique-violation error, return the existing order, and not return a `500` or `409`. Also decide:
- Is the key unique on its own, or per customer? If it's unique on its own, customer B could get customer A's order back.
- What happens if the same key comes with a different cart, or no key is sent?

**8. One transaction covers two modules' tables. (Medium)** Step 2 changes `stock` (owned by inventory) and `orders` in one transaction, but the code-structure section says no module reads another module's tables. Both rules can hold if `OrderCheckout` opens the transaction and passes it to the inventory and orders modules. Write that down so nobody "fixes" it by reaching into another module's tables.

**9. The tests skip the riskiest part. (Medium)** Add integration tests for:
- reconciliation settling as `PAID`, as `FAILED`, and as "not found"
- two reconciliation runs at once (the double-restore case in item 1)
- two duplicate `POST /orders` requests at the same time
- two buyers going for the last unit at the same time (the current test is a single buyer)
- negative quantity, and two carts with opposite SKU order (the deadlock in item 5)

## Minor

**10. The confirmation email can be lost. (Low)** The order commits as `PAID` and only then queues the email. A crash between those two steps loses it. A table of pending messages written in the same transaction as the status change (an "outbox") closes this gap. Or accept the risk and note it in the doc.

**11. Retry scope isn't stated. (Low)** Say which errors trigger a retry: timeouts and 5xx only, never declines.

## Not confirmed, worth checking

- **Load-balancer timeout.** Four attempts of 5 seconds each plus backoff can hold a request open for about 30 seconds. Check that this is shorter than the load balancer's timeout.
- **Provider key expiry.** Check how long the provider remembers idempotency keys. Reconciliation works within minutes, so this probably isn't a problem.

## Order status rules once fixes 1 and 2 are in

```mermaid
stateDiagram-v2
    [*] --> PENDING: stock reserved, order inserted
    PENDING --> PAID: charge succeeded (request or reconciliation)<br/>then queue email
    PENDING --> FAILED: declined (request or reconciliation)<br/>then restore stock
```

Each arrow should apply only if the order is still `PENDING` (fix 1). The follow-up action on each arrow runs the same way whether the request or the reconciliation job made the change (fix 2).

Your time is best spent on items 1–4. Each one is a few sentences in the doc and will save debugging later. Items 5–9 can be settled while you write the first tests.

VERDICT: READY WITH CHANGES
