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

You can start building tomorrow once you fix six specific gaps in the document. The core of the design is sound and doesn't need rethinking. Each fix is a few lines in the doc plus a test, but two of them cause real money or stock errors if they're missing.

## What's already right
- **Duplicate orders.** The client's idempotency key has a unique constraint, so a repeated `POST /orders` returns the existing order.
- **Overselling.** The stock update only succeeds if `available >= :qty`, so two buyers can't both take the last unit.
- **Payment outside the transaction.** The provider is called after the database transaction commits, and the order id goes to the provider as its idempotency key, so retries can't double-charge.
- **Unknown payment results.** Orders whose outcome is unknown get a reconciliation job, and an alert fires when an order is stuck `PENDING` for 30 minutes.
- **Email.** A failed confirmation email never fails the order.
- **Capacity.** The setup is the right size for 200 to 2,000 orders a day.

## Must fix before building

**1. Status changes aren't guarded, so stock can be restored twice.** The doc says "marks the order `FAILED` and restores the stock" but doesn't say this only happens if the order is still `PENDING`.
- *Failing case:* an order for the last unit of SKU-1 has an unknown payment result. Both instances' reconciliation jobs run and both see the order as `PENDING`. Each marks it `FAILED` and adds 1 back.
- *What happens:* stock goes from 0 to 2. *Expected:* 1. You then sell a unit you don't have.
- *Fix:* every status change is `UPDATE orders SET status = :new WHERE id = :id AND status = 'PENDING'`. Restore stock only if that update changed one row. Do the same for `PAID`, so the request thread and the reconciliation job can't both settle the same order.

**2. The reconciliation job runs on both instances.** You have two instances and the doc doesn't say where the job runs. Fix 1 makes duplicate runs safe, but you should still run it on one instance only. A Postgres advisory lock (`pg_try_advisory_lock`) at the start of each run is enough.

**3. Reconciliation assumes the provider always answers "paid" or "declined."** It can also say "still processing" or "no such charge."
- "Still processing" should leave the order `PENDING`. The 30-minute alert covers orders that stay stuck.
- "No such charge" should become `FAILED`, but only for orders old enough that no retry can still be in flight. The 2-minute threshold works, since 4 attempts × 5 s plus backoff is about 30 s.
- Write all three outcomes into step 6.

**4. Orders settled as `PAID` by reconciliation never send a confirmation email.** Step 4 queues the email only when the request thread itself sees success.
- *Failing case:* the charge times out on every attempt, the client gets `202`, and five minutes later the job marks the order `PAID`. The customer is charged and gets no email.
- *Fix:* put "mark paid and queue the email" in one function that both paths call.
- Also say what the queue is. If it isn't in Postgres, a crash between the commit and the enqueue loses the email. A transactional outbox (an `outbox` table written in the same transaction as `PAID`) closes that gap.

**5. The doc never says where prices come from.** `order_items.unit_price` and `orders.total` exist, but no table holds prices and the flow says the client sends "the cart." If the cart includes prices, a client can send `unit_price: 0.01`. State that prices and totals are computed on the server from a price source (which table or service?) and never taken from the request.

**6. A client that gets `202` has no way to learn the outcome.** Add `GET /orders/{id}` (or a webhook) and say how the client should poll it.

## Should fix (cheap, do them while building)
- **Idempotency key details.** Decide whether the key is unique per customer (`(customer_id, idempotency_key)`) or globally. Decide what happens when the same key arrives with a different cart; the usual answer is `422`.
- **Deadlocks.** Two carts with the same SKUs in opposite order can deadlock each other. Sort cart lines by SKU before updating stock, and merge duplicate SKU lines first.
- **Missing constraints.** Add `CHECK (available >= 0)` on `stock`, primary keys (`order_items (order_id, sku)`), and a foreign key from `order_items` to `orders`.
- **Module boundary.** "No module reads another module's tables" doesn't match steps 2 and 5, where orders and inventory change in one transaction. Name the mechanism: `OrderCheckout` opens the transaction and passes it to the orders and inventory repositories. That keeps each module's table access inside the module.
- **Non-retryable errors.** Say how errors like a provider `400` or invalid card are handled. They should become `FAILED` right away, not go through retries.

## Order lifecycle with the guards from fix 1
```mermaid
stateDiagram-v2
    [*] --> PENDING: stock reserved + order inserted (one transaction)
    PENDING --> PAID: charge succeeded (request or reconciliation), only if still PENDING; queue email
    PENDING --> FAILED: declined, or provider has no charge after 2 min, only if still PENDING; restore stock
    PENDING --> PENDING: result unknown / provider still processing; alert after 30 min
    PAID --> [*]
    FAILED --> [*]
```

## Tests to add
The current list has no tests for reconciliation and none that run anything concurrently. Add tests for:
- decline restores stock
- reconciliation settling `PAID`, `FAILED`, and leaving "still processing" alone
- two reconciliation runs on the same order (stock restored exactly once)
- an order settled by reconciliation still sends its email
- a real concurrent race for the last unit, two parallel requests rather than one after the other
- two concurrent requests with the same idempotency key
- a crash after a successful charge but before `PAID` (reconciliation recovers it)
- the email failing without failing the order
- the price in the request being ignored

None of these needs a redesign. They're edits to steps 4–6 and the data model, and you can write them in an hour before you start.

VERDICT: READY WITH CHANGES
