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

**Short answer: you can start building tomorrow once you fix four gaps in the doc.** The overall approach is sound. Each item below is a short paragraph you can add to design.md, not a redesign. Without these fixes, specific cases will either leave stock reserved forever or put too much stock back.

## What's already solid
- The stock reservation is atomic: the conditional `UPDATE ... WHERE available >= :qty` runs in the same transaction as the order insert.
- The payment call happens outside any transaction, and the order id is the provider's idempotency key, so retries can't charge twice.
- An unknown payment result leaves the order `PENDING`, and the reconciliation job (the 5-minute job that checks stuck orders with the provider) settles it later. The 30-minute alert is the backstop.
- A failed email never fails the order.

## Must fix before building

**1. Two status updates can both run, and stock gets restored twice.**
Both instances may run the reconciliation job. A web request and the job can also finish the same order at the same moment.
- *Case:* a 2-unit order is declined. Two runs of the job each mark it `FAILED` and each add 2 back.
- *Result:* `available` goes up by 4. It should go up by 2.

*Fix:* every status change must be conditional: `UPDATE orders SET status = 'FAILED' WHERE id = :id AND status = 'PENDING'`. Only restore stock if that update changed one row. Also say whether the job runs on one instance only (an advisory lock or `FOR UPDATE SKIP LOCKED`) or on both.

**2. The doc doesn't say what happens when the provider has no record of the charge.**
- *Case:* an instance crashes after step 2 commits and before step 3 calls the provider. The order is `PENDING`, and the stock is reserved.
- *What happens:* the job asks the provider and gets "charge not found." The design only covers `PAID` and `FAILED`, so the order stays `PENDING` and the stock stays held until someone sees the alert.

*Fix:* add the rule. Either charge again with the same order id as the key (safe, because the provider dedupes on it), or mark the order `FAILED` and restore stock once it's older than N minutes.

```mermaid
stateDiagram-v2
    [*] --> PENDING: stock reserved
    PENDING --> PAID: charge succeeded (request or job)
    PENDING --> FAILED: declined (request or job), stock restored
    PENDING --> PENDING: result unknown, 202 to client
    PENDING --> ?: job finds no charge at provider (undefined today)
```

**3. A crash can lose the confirmation email.**
- *Case 1:* the instance crashes after the `PAID` commit and before the email is queued. The customer is charged and never gets a confirmation.
- *Case 2:* the doc never says whether the job sends an email when it settles an order as `PAID`.

*Fix:* write the email job as a row inside the same transaction that sets `PAID` (an outbox table that a worker reads). Use that same path for both the request and the job.

**4. Prices have no source.**
The client sends "the cart," and `order_items.unit_price` and `orders.total` are stored, but no table or service supplies prices. If prices come from the request, a client can set its own price. *Fix:* say where prices come from (a catalog service or a price table), and say that the server calculates `total`.

## Should fix (small)
- **Deadlock between multi-item orders.** Order A reserves {X, Y} while order B reserves {Y, X}. Postgres aborts one of them with a deadlock error, which surfaces as a 500. Fix: reserve SKUs in sorted order.
- **The module rule conflicts with step 2.** Step 2 updates `stock` (inventory) and `orders` (orders) in one transaction, but the doc says no module reads another module's tables. State the boundary you actually want, e.g. "inventory exposes `reserve(tx, items)`, and the orders module owns the transaction."
- **Missing keys and constraints.** `stock.sku` and `order_items` have no primary key. Add `CHECK (available >= 0)` on stock. Decide whether `idempotency_key` is unique on its own or per customer (`(customer_id, idempotency_key)`).
- **Unstated behavior:**
  - The status code for a declined charge (e.g. `402`).
  - What happens when a key is reused with a different cart (suggest `422`).
  - Which errors get retried (timeouts and 5xx only, never declines).
  - Whether about 25 s of in-request retries (four 5 s attempts plus backoff) fits under the load balancer's timeout.

## Test plan gaps
The listed integration tests are good. Add:
- the reconciliation job settling `PAID`, `FAILED`, and charge-not-found
- the job running twice at the same time on one order, with stock restored exactly once
- two concurrent requests with the same idempotency key
- two concurrent buyers racing for the last unit (make the existing "last unit" test concurrent)
- a crash after the `PENDING` commit and before the charge
- multi-item orders reserved in opposite SKU orders, with no deadlock

Next step: add items 1–4 and the extra tests to design.md, then start with `OrderCheckout` and the inventory reservation, writing tests first.

VERDICT: READY WITH CHANGES
