# Review of design.md: checkout flow for order-service (revision 3)

The overall design holds up and you can build from it tomorrow. Before you do, fix six gaps in the spec. Two of them would cause wrong stock counts or orders stuck in `PENDING` in production. Each fix is a few lines in the design and is cheap now, but expensive once code exists.

Several parts are already right and shouldn't change: the conditional stock decrement, calling the payment provider outside any transaction, reusing the order id as the provider's idempotency key, and the reconciliation job backed by an alert at 30 minutes.

## Must fix before building

**1. An order can be settled twice, which restores its stock twice.**
Nothing in the design stops two writers from settling the same order. Both service instances run the reconciliation job, and a slow request can also return late.
- *Case:* order A (2 × SKU-1) is `PENDING`. Both instances' reconciliation jobs ask the provider about it, both get "declined", and both run "mark `FAILED` and restore stock".
- *Result:* SKU-1 `available` goes up by 4.
- *Expected:* it goes up by 2.
- *Fix:* make every status change conditional: `UPDATE orders SET status = :new WHERE id = :id AND status = 'PENDING'`. Restore stock only if that update changed a row. Also make the job claim rows with `FOR UPDATE SKIP LOCKED` (or take an advisory lock) so the two instances don't both work the same order.

**2. If the service crashes between steps 2 and 3, the order stays `PENDING` forever.**
- *Case:* the order commits as `PENDING`, then the instance restarts before it calls the provider. Reconciliation asks the provider about this order id, and the provider answers "no such charge".
- *Result:* the design only handles `PAID` and `FAILED`, so the order sits there holding stock until a human acts on the 30-minute alert.
- *Expected:* the job either sends the charge (it is safe to repeat, because the idempotency key is the order id) or marks the order `FAILED` and restores stock. Pick one and write it down.

```mermaid
stateDiagram-v2
    [*] --> PENDING: stock reserved, order inserted
    PENDING --> PAID: charge succeeded (request or reconciliation)
    PENDING --> FAILED: declined, or provider has no charge (restore stock once)
    PAID --> [*]
    FAILED --> [*]
```
Every arrow above should be the conditional update from item 1. No other transitions are allowed.

**3. Two orders for the same SKUs can deadlock each other.**
- *Case:* order X reserves SKU-1 and then SKU-2, while order Y reserves SKU-2 and then SKU-1, at the same moment.
- *Result:* Postgres cancels one of the two transactions, and that customer gets a 500.
- *Expected:* both orders succeed, or one gets a clean `409`.
- *Fix:* update stock rows in sorted SKU order.

**4. Two requests with the same idempotency key at the same moment fail.**
- *Case:* the client double-submits. Both requests start their transactions, and the second one hits the unique-key violation on insert.
- *Result:* the second request gets a 500.
- *Expected:* it returns the existing order.
- *Fix:* catch the unique violation, then read the order and return it.

Two related rules are also missing:
- **Make the key unique per customer.** Use `(customer_id, idempotency_key)`, so two customers' clients can't generate the same key and collide.
- **Reject a reused key with a different cart.** Return `422` when a key comes back with a different cart, instead of silently returning the old order.

**5. The module rule contradicts the flow.**
"No module reads another module's tables" doesn't fit step 2, which writes `orders` and `stock` in one transaction (step 5 does the same). State how this works. For example, the inventory module exposes `reserve(tx, items)` and `release(tx, items)`, which `OrderCheckout` calls inside a transaction it owns. Without that, the rule gets broken on day one with no agreed shape.

**6. The design doesn't say where prices come from.**
`unit_price` and `total` are stored on the order, but nothing says whether they come from the client's cart or a price lookup. If they come from the client, a client can set its own price. Name the source.

## Should fix (smaller)
- **Retry only when the outcome is unknown.** Retry on timeouts and provider errors in the 5xx range, never on a decline.
- **Check the load balancer timeout.** Four attempts at 5 s each plus backoff means a request can take about 25–30 s. Confirm the load balancer's idle timeout is longer than that.
- **Define how a client follows up on a `202`.** Either add `GET /orders/{id}` or document that the client re-sends the same `POST`.
- **Close the email gap.**
  - If the instance crashes after committing `PAID` but before queuing the email, the email is lost. A small outbox table written in the same transaction fixes this.
  - Also state that orders settled as `PAID` by reconciliation get the email too.
- **Add constraints and indexes to the data model.**
  - A primary key on `stock.sku` and a `CHECK (available >= 0)`.
  - A primary key on `order_items` (`order_id`, `sku`).
  - An index on `orders (status, created_at)` for the reconciliation query.

## Missing tests
Add these to the integration list:
- Two buyers racing for the last unit. The current test has a single buyer.
- A concurrent duplicate `POST /orders`.
- A decline restores stock exactly once.
- Reconciliation settles an order as `PAID`, settles one as `FAILED`, and handles a provider answer of "no such charge".
- Both reconciliation instances running at the same time.
- A multi-SKU cart sent in reverse order alongside another cart (the deadlock case).

VERDICT: READY WITH CHANGES
