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

The basic approach works. Stock is reserved inside one transaction, the charge happens outside any transaction, the order id is reused as the payment provider's idempotency key, and a job cleans up unknown results. Nothing needs redesigning. But three gaps will turn into bugs in the first week if you build it exactly as written. Each takes a few lines to fix in the doc, so fix them tonight and you can start tomorrow.

## Must fix before building

**1. Stock can be put back twice, so you sell items you don't have.**
Both instances run the reconciliation job every 5 minutes, and nothing stops them settling the same order. Steps 5 and 6 also don't say a status change only applies while the order is still `PENDING`.
- **Example:** SKU `A` has 1 unit. Order X reserves it, so `available = 0`, and the outcome is unknown. At the next run, both instances ask the provider, both hear "declined", and both run "mark `FAILED` and restore stock".
- **Result:** `available = 2`, with 1 unit on the shelf. **Expected:** `available = 1`.
- The same thing happens if the request thread and the job overlap (for example, a stalled instance).
- **Fix:** every status change is `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, in the same transaction. Have the job pick up orders with `FOR UPDATE SKIP LOCKED` so the two instances split the work instead of both doing it.

```mermaid
stateDiagram-v2
    [*] --> PENDING: stock reserved + order inserted (one transaction)
    PENDING --> PAID: charge succeeded (only if still PENDING) + queue email
    PENDING --> FAILED: declined or no charge found (only if still PENDING) + restore stock
    PAID --> [*]
    FAILED --> [*]
```

**2. The job has no rule for "the provider has no record of this charge".**
If an instance crashes after step 2 commits but before step 3 sends the charge, the order stays `PENDING` and the provider never hears about it. Step 6 only says "settle as `PAID` or `FAILED`". It doesn't say what happens when the provider answers "not found", or "still processing".
- Write both rules down. A reasonable choice: "not found" after 2 minutes means `FAILED` and restore stock, because a request finishes in about 25 s at most. "Processing" means leave it `PENDING`.
- Also check that your provider lets you look up a charge by your idempotency key or order id, and how long it keeps idempotency keys. Some providers don't support that lookup at all, and the whole job depends on it.

**3. The job has no tests.**
The test list covers the request path but not the code that settles unknown orders. Add tests for:
- the job settling an order as paid
- the job settling an order as declined
- "not found" at the provider
- two runs at once settling the same order (this proves fix #1)
- a crash between reserving stock and charging

## Should fix (cheap, and they affect the code you write first)

- **Moving the module rule, step 2 and the email in step 4 into one transaction:** the rule "no module reads another module's tables" clashes with step 2, which writes `stock` and `orders` in one transaction. Say how they share it, for example "inventory exposes `reserve(tx, items)` that runs inside the caller's transaction". Otherwise someone will split it into two transactions to honour the rule.
- **Deadlocks on multi-item carts:** two carts holding the same SKUs in a different order can deadlock each other in step 2. Sort the items by SKU before running the `UPDATE`s.
- **Emails that never send:** step 4 queues the email after the commit. A crash in between means no email, and nothing retries it. If the queue lives in Postgres, write the email job in the same transaction that sets `PAID`. Also state that orders the job marks `PAID` get an email too.
- **Duplicate requests at the same moment:** the two copies race. The loser's insert hits the unique constraint and rolls back, which also undoes its stock reservation. Say that it then returns the winner's order instead of a `500`, and add that case to the tests. The existing test "duplicate `POST /orders`" sounds like it covers only a repeat after the first one finished.
- **Idempotency key scope:** make the unique constraint `(customer_id, idempotency_key)` so one customer's key can never return another customer's order. Decide what a repeated key with a *different* cart does; returning `422` is safer than silently returning the old order.
- **How the client learns the result after `202`:** nothing says. Add `GET /orders/{id}` (or say how else the client finds out).
- **Schema guards:** add primary keys on `stock.sku` and `order_items`, plus `CHECK (available >= 0)`, so the database itself catches a bug like #1.
- **Missing tests:** stock comes back after a decline, and two buyers race for the last unit.

## Fine as is
- The volume (200 to 2,000 orders a day) is far below what two instances and one Postgres can handle.
- The 30-minute `PENDING` alert fits a job that runs every 5 minutes.
- Thin routes with the flow in `OrderCheckout`, and the order id on every log line, are good choices.

VERDICT: READY WITH CHANGES
