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

**The overall structure is sound and you can start building tomorrow, but first fix three gaps in the design.** Each one is a few lines in the doc. Each one, left alone, causes wrong stock counts, stuck orders, or one customer seeing another customer's order.

## What's already solid
- The stock reservation is a conditional `UPDATE … WHERE available >= :qty` inside the order transaction, so stock can't oversell.
- The payment call happens outside any transaction, so database locks aren't held during network calls.
- The order id is sent as the provider's idempotency key, so retries can't double-charge.
- There's a reconciliation job and a 30-minute alert for stuck `PENDING` orders.
- The email is decoupled from the order, so a failed email can't fail the order.
- The scale assumption (2,000 orders a day) is easy for one Postgres and two instances.

## Must fix before building

**1. Two instances can settle the same order twice, which corrupts stock.**
The reconciliation job runs on both instances. Nothing in the design stops two settlements of one order.
- *Case:* order X is `PENDING` with 1 unit of SKU A, and the provider says "declined". Both instances run step 5 at the same time, and each adds 1 back to stock. **Actual:** `available` goes up by 2. **Expected:** up by 1.
- The same race exists between the request path and the job, for example on a slow request.
- *Fix:* every status change must be guarded: `UPDATE orders SET status = :new WHERE id = :id AND status = 'PENDING'`. Restore stock only if that update changed exactly one row, in the same transaction. Optionally, also have the job claim orders with `FOR UPDATE SKIP LOCKED` so the two instances don't duplicate work.

**2. Reconciliation has no plan for "the provider has no record of this charge".**
This happens when the process crashes after step 2 commits but before step 3. It also happens when every attempt timed out before reaching the provider.
- *Case:* the order commits as `PENDING`, then the instance restarts. The job asks the provider, and the provider returns "not found". **Actual:** the design only defines `PAID` and `FAILED`, so the order stays `PENDING` forever and its stock stays reserved. **Expected:** a defined outcome.
- *Fix:* pick one and write it down.
  - Option A: re-issue the charge with the same order-id key. Because the key is the same, this is safe.
  - Option B: mark the order `FAILED` and restore stock. This is only safe if the provider is guaranteed to reject a late-arriving request with that key.
  - I recommend option A, with a maximum age after which the job falls back to B.

**3. Idempotency keys are globally unique and only the key is compared.**
- *Case:* two customers' clients happen to send the same key. Customer B gets back customer A's order. That is a data leak.
- *Fix:* make the unique constraint `(customer_id, idempotency_key)`. If the same key arrives with a different cart, return `422`.

## Should fix (small)
- **Deadlock on multi-item carts.** Order 1 locks SKU A then B, while order 2 locks B then A. Postgres aborts one of them. *Fix:* sort SKUs before the updates, and merge duplicate SKU lines first.
- **The email can be silently lost.** If the process dies between "commit `PAID`" and "queue email", no email is sent, and reconciliation won't catch it because the order is already `PAID`. *Fix:* insert the email job in the same transaction as the `PAID` update (an outbox row).
- **A client that gets `202` has no way to learn the outcome.** Add `GET /orders/{id}`, or document how the client finds out.
- **Two modules write in one transaction.** Step 2 writes both inventory and orders, which is allowed under "no module reads another's tables" only if the inventory module takes the caller's transaction. State that explicitly so nobody "fixes" it into two transactions later.
- **Missing keys in the data model.** Declare primary keys (`stock.sku`, `order_items(order_id, sku)`) and a `CHECK` constraint on `status`.
- **Worst-case request time is about 25 s or more** (4 attempts × 5 s, plus backoff). Confirm the load balancer's timeout is longer than that.

## Order lifecycle with the fixes
```mermaid
stateDiagram-v2
    [*] --> PENDING: stock reserved + order inserted (one transaction)
    PENDING --> PAID: charge succeeded (only if still PENDING) + email job row
    PENDING --> FAILED: declined (only if still PENDING) + stock restored once
    PENDING --> PENDING: result unknown, reply 202
    PENDING --> PAID: reconciliation, provider says paid
    PENDING --> FAILED: reconciliation, provider says declined
    PENDING --> PENDING: reconciliation, provider has no record, re-charge with same key (NEW)
```

## Tests to add to the plan
The current list covers the single-request happy and failure paths. It doesn't cover the cases above. Add:
- reconciliation settling to `PAID`
- reconciliation settling to `FAILED`
- reconciliation finding no charge at the provider
- two reconciliation runs at once restoring stock exactly once
- two concurrent `POST /orders` calls with the same key
- two concurrent buyers for the last unit
- two carts with overlapping SKUs in opposite order (no deadlock)
- the same key from different customers
- the same key with a different cart (`422`)
- a crash between step 2 and step 3

Next step: update the doc for items 1–3 (about 15 minutes), add those tests to the plan, then start building.

VERDICT: READY WITH CHANGES
