# Review of design.md (revision 3)

The overall design is sound and sized right for 2,000 orders a day. You can start building tomorrow, but first add about five decisions to the doc. Most are a sentence or two each. Two of them, stock being restored twice and orders that never reached the payment provider, would cause wrong data in production if built as currently written.

## What's already solid
- Stock is reserved with a conditional `UPDATE` in the same transaction as the order insert, so you can't oversell.
- No transaction is held open while calling the payment provider.
- The order id is sent as the provider's idempotency key, so retries can't double-charge.
- The email is sent after commit and can never fail the order.
- Unknown outcomes are handled by `202` plus a reconciliation job, with a 30-minute alert as a backstop.
- The test list already includes timeout-then-success and timeout-on-every-attempt.

## Fix before building

**1. Status changes must be guarded, or stock gets restored twice.** You run two instances, so the reconciliation job runs on both unless the doc says otherwise. Example: a `PENDING` order for 2 units of SKU `A` is settled as `FAILED` by both instances in the same run. Stock goes up by 4 when it should go up by 2. A late request thread and the job can collide the same way.
- **Fix:** every status change is `UPDATE orders SET status = :new WHERE id = :id AND status = 'PENDING'`. Restore stock only if that update changed a row.
- **Also:** have the job claim rows with `FOR UPDATE SKIP LOCKED`, or run it on only one instance.

```mermaid
stateDiagram-v2
    [*] --> PENDING: POST /orders (stock reserved)
    PENDING --> PAID: charge succeeded (request or reconciliation)
    PENDING --> FAILED: charge declined or not found (stock restored once)
    PAID --> [*]
    FAILED --> [*]
```
Only changes out of `PENDING` are allowed, and each happens at most once.

**2. Reconciliation has no rule for "the provider has never seen this charge."** Example: an instance crashes after step 2 commits but before step 3 calls the provider. The order stays `PENDING` and the stock stays reserved. When the job asks the provider, the answer is "not found", and the doc doesn't say what happens next.
- **Decide:** either mark it `FAILED` and restore stock, or retry the charge with the same order id.
- **Also say:** what the job does if the provider reports "still processing" (probably leave it `PENDING` and let the 30-minute alert catch it).

**3. Prices must come from the server, not the cart.** The data model has no price source, and step 1 says the client "sends the cart." If `unit_price` is taken from the request, a client can send `0.01`.
- **State:** where prices and currency are looked up. If that needs a products or pricing table or service, add it to the data model.

**4. The idempotency key needs a defined scope and payload check.** The key has a unique constraint on `idempotency_key` alone. If two customers happen to send the same key, customer B gets customer A's order back.
- **Fix:** make it unique on `(customer_id, idempotency_key)`.
- **Decide:** what happens when the same key arrives with a different cart. The usual answer is to store a hash of the request and return `422` when it doesn't match.
- **Concurrent duplicates:** when the second insert hits the unique violation, return the existing order, not a `500`.

**5. A client that gets `202` has no way to find out the result.** Add `GET /orders/{id}`, or a webhook or polling contract, to the flow.

## Smaller items (fine to settle while building)
- **Deadlocks:** two concurrent carts with SKUs `A,B` and `B,A` can deadlock in step 2. Lock stock rows in SKU order, and merge duplicate SKUs in a cart first.
- **Request duration vs. load balancer:** four 5-second attempts plus backoff can run past 25 seconds. Check this against your load balancer and client timeouts. A client that times out and retries with the same key will safely get the `PENDING` order back.
- **Retries:** say they happen only on timeouts and 5xx responses, never on a decline.
- **Lost email on crash:** an instance that crashes between the `PAID` commit and queueing the email loses the email. An outbox row written in the same transaction fixes this. It's fine to accept the risk for now, but write it down as known debt.
- **Module boundary:** "no module reads another module's tables" sits awkwardly with steps 2 and 5, which write orders and stock in one transaction. Say how this works, for example inventory functions that accept the caller's transaction.
- **Data model gaps:** add primary keys (`stock.sku`, and `(order_id, sku)` on `order_items`), an index on `orders(status, created_at)` for the reconciliation query, and a column for the provider's charge id.

## Tests to add
- Two buyers racing for the last unit, run concurrently, not one after the other.
- Decline restores stock exactly once.
- Two reconciliation runs settle the same order once.
- Crash between commit and charge, with the provider returning "not found".
- Reconciliation settling a timed-out order as `PAID` and as `FAILED`.
- Same idempotency key with a different cart, and the same key from a different customer.
- Deadlock: opposite SKU order.

VERDICT: READY WITH CHANGES
