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

You can start building tomorrow, but fix four things in the doc first. Each is a short edit. The overall design is sound. The order is reserved and committed before the charge. Every charge attempt reuses the order id as the payment provider's idempotency key. Unknown payment results are settled by a reconciliation job. Two of the four gaps would cause wrong stock counts or wrong charges in production.

## Must change before building

**1. Two code paths can restore the same order's stock twice.** Steps 5 and 6 both "mark FAILED and restore stock". Neither says the change only applies if the order is still `PENDING`. You run two instances. If each one runs the reconciliation job, both jobs pick up the same stale order.
- **Case:** SKU X has `available = 0`. A `PENDING` order holds the last unit, and the provider reports it declined. Both instances' jobs mark it `FAILED` and add the unit back.
- **Wrong result:** `available = 2`, so you sell a unit that doesn't exist. **Expected:** `available = 1`.
- **Fix:** Make every status change a conditional update: `UPDATE orders SET status = 'FAILED' WHERE id = :id AND status = 'PENDING'`. Restore stock only if that statement changed one row. Do it in the same transaction. Have the job claim orders with `FOR UPDATE SKIP LOCKED`, or run it on one instance only. All three exits from `PENDING` (request path, decline, reconciliation) should share this one guarded function.

```mermaid
stateDiagram-v2
    [*] --> PENDING: stock reserved + order inserted (one transaction)
    PENDING --> PAID: charge succeeded (request path or reconciliation)
    PENDING --> FAILED: declined or charge not found (stock restored in same transaction)
    PAID --> [*]
    FAILED --> [*]
```
Each arrow out of `PENDING` should happen at most once. Today nothing in the design enforces that.

**2. The design never says where prices come from.** `order_items.unit_price` and `orders.total` exist, but no table holds prices. The request sends "the cart". If the cart includes prices, a client can send `unit_price: 0.01` and get charged that. The doc should say that prices are looked up on the server (from which module or table), and that the client only sends SKUs and quantities.

**3. Reconciliation doesn't cover a charge the provider has never seen.** Suppose an instance crashes after step 2 commits but before step 3 sends the charge. The provider then says "no such charge", and step 6 only handles `PAID` and `FAILED`. Decide what happens. Either mark the order `FAILED` and restore stock, or re-send the charge with the same idempotency key, which is safe to repeat. Also state two more things about the job: when it settles an order as `PAID` it queues the confirmation email, and when it settles one as `FAILED` it restores stock through the same function as step 5.

**4. A client that gets `202` has no way to find the outcome.** Add `GET /orders/{id}`, or document how the client gets the final status.

## Should change (small, do while building)

- **Reserve SKUs in a fixed order.** Order 1 reserves A then B while order 2 reserves B then A. Postgres hits a deadlock and aborts one of them, and that customer gets a `500`. Fix: sort the SKUs before running the updates.
- **Scope the idempotency key to the customer:** make it `UNIQUE (customer_id, idempotency_key)`. Then one customer's key can never return another customer's order. Also say what happens when a repeated key arrives with a different cart: I'd return `422` rather than silently returning the old order.
- **Say how the transaction crosses modules.** Step 2 writes both `stock` (inventory module) and `orders` (orders module) in one transaction. That's fine if each module runs its own SQL against a transaction that `OrderCheckout` passes in. Name that mechanism so nobody "fixes" the boundary by splitting the transaction.
- **Retry only on timeouts and 5xx errors**, never on a decline. The doc probably means this already; say it.
- **Email after commit can be lost.** If the process dies between the `PAID` commit and queuing the email, the customer never gets it. If the queue lives in Postgres, insert the email job in the same transaction (an outbox table).
- **Add schema details:** primary keys on `stock(sku)` and `order_items(order_id, sku)`, foreign keys, and `CHECK (available >= 0)`.

## Tests to add to the plan

The current list covers the request path well. Add:
- Two buyers racing for the last unit at the same time; exactly one succeeds. The current test only covers one buyer.
- A declined charge restores stock.
- Reconciliation settles `PAID`, settles `FAILED` (stock restored, once), and handles "charge not found".
- Two reconciliation runs at once on the same order: stock is restored exactly once (the test for item 1).
- A duplicate `POST /orders` sent while the first request is still in flight.
- A duplicate key sent with a different cart.
- A client-supplied price is ignored.

VERDICT: READY WITH CHANGES
