# Review of design.md (checkout flow, order-service rev 3)

Yes, you can start building tomorrow. The core of the design is sound: stock is reserved with a guarded update in one transaction, the payment call happens outside any transaction, retries reuse the same payment idempotency key, and orders with an unknown payment result are left `PENDING` for a reconciliation job and an alert. None of what I found needs a redesign. Two items can lose stock or count it twice, though, and one is a possible pricing hole. Settle those three in the doc before you write the reconciliation job and the order-creation code.

## Order lifecycle and where the gaps are

```mermaid
stateDiagram-v2
    [*] --> PENDING: POST /orders (stock reserved)
    PENDING --> PAID: charge succeeds (request or reconciliation)
    PENDING --> FAILED: declined (request) - stock restored
    PENDING --> FAILED: reconciliation - stock restore NOT specified
    PENDING --> PENDING: provider has no record of charge - NOT specified
```

## Fix before building (high)

**1. Orders failed by the reconciliation job never get their stock back.** Step 5 restores stock when a charge is declined during the request. Step 6 only says reconciliation "settles them as PAID or FAILED" and doesn't mention stock.
- Example: an order for 2 × SKU-A times out and stays `PENDING`. Reconciliation later learns it was declined and marks it `FAILED`. SKU-A stays 2 units short for good, when it should be back to full.
- Fix: put "mark FAILED and restore stock" in one shared function that both paths call.

**2. The reconciliation job can run on both instances at once, which settles the same order twice.** You run two instances (line 6). If the job runs inside each one, both pick up the same `PENDING` orders.
- Example: both instances see order X declined. Both mark it `FAILED` and both restore 2 units. Stock ends up 2 too high, so you oversell.
- Fix: make every status change conditional (`UPDATE orders SET status = 'FAILED' WHERE id = :id AND status = 'PENDING'`) and restore stock only if that update changed a row. Also run the job on one instance only, or have it claim rows with `FOR UPDATE SKIP LOCKED`. The conditional update also protects you if a slow request and the job ever overlap.

**3. The design doesn't say where `unit_price` and `total` come from.** No table in the data model holds prices, and the client "sends the cart". If prices are taken from the request, a customer can send `unit_price: 0.01`. The likely fix is one sentence: prices are looked up on the server (from which source?), and client-sent prices are ignored. I'm flagging this as a gap in the doc, not a confirmed bug.

## Fix soon (medium)

**4. Deadlock between two orders that share SKUs.** Step 2 updates stock rows in cart order. Order A updates SKU-1 then SKU-2 while order B updates SKU-2 then SKU-1, and Postgres kills one of them with a deadlock error. Fix: sort SKUs before updating, and merge duplicate SKU lines in the cart into one.

**5. Reconciliation has no rule for a charge the provider has never seen.** This happens when an instance crashes after step 2 commits but before step 3 sends the charge. The provider has no record, and the order is neither `PAID` nor `FAILED`, so it stays `PENDING` until the 30-minute alert fires and someone handles it by hand. Fix: decide the rule, probably "not found after N minutes → FAILED and restore stock".

**6. Orders paid via reconciliation may never send a confirmation email.** Step 4 queues the email only on the request path. Also, "commit, then queue" loses the email if the process dies between those two steps. Fix: write the email job to an outbox table in the same transaction that marks the order `PAID`, and do this on both paths.

**7. The module boundary and the single transaction conflict.** Line 41 says no module reads another module's tables, but step 2 writes `stock` (inventory) and `orders` in one transaction. Pick one approach and write it down. I recommend that `InventoryService.reserve(tx, items)` takes the caller's transaction, so the inventory module still owns its SQL.

**8. A client that gets `202` has no way to learn the final result.** The doc has no `GET /orders/{id}` endpoint and no webhook. Add the endpoint.

## Minor (low)

- **9. The idempotency key is unique across all customers.** If two customers ever send the same key, the second one gets the first customer's order back. Make the constraint `UNIQUE (customer_id, idempotency_key)`.
- **10. Two idempotency edge cases have no defined response:**
  - The same key arrives with a different cart. Suggest `422`.
  - Two requests with the same key arrive at the same time. The second one hits a unique-constraint error and should be caught and answered with the existing order.
- **11. Keys and constraints are missing from the data model.**
  - No primary or foreign keys are listed, for example `stock.sku` as primary key and `order_items.order_id` referencing `orders.id`.
  - There is no `CHECK (available >= 0)` and no check on `status`.
  - Nothing stores the provider's charge id or the payment attempts, which you'll want for support and refunds.
- **12. Worst-case request time is about 27 seconds.** That's 4 attempts × 5 s plus backoff. Check that the load balancer and client timeouts are longer. Also only retry on timeouts and 5xx errors, never on a decline.

## Tests to add to the plan

Your list covers the request path well. It's missing:
- the reconciliation job itself: paid, declined (with stock restored), and provider has no record
- the job running on both instances at once (stock restored once)
- two concurrent `POST /orders` with the same key
- two concurrent buyers for the last unit
- a multi-item cart where one SKU is short (the whole order rolls back)
- the deadlock case from #4

## Possible concerns (not supported by the doc, just worth a thought)

- At 2,000 orders a day, load is not a concern. The index on `(status, created_at)` for the reconciliation query is optional, though cheap.
- If you ever add partial refunds or multiple currencies per cart, the data model will need a payments table. That isn't needed now.

**What to do next:** add a few sentences to the doc for #1, #2, #3 and #5, add the missing tests to the plan, then build. Items #4 and #6–#12 can be handled as you write the code.

VERDICT: READY WITH CHANGES
