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

You can start tomorrow, but fix the design first. The overall structure is sound. Two gaps would cause real bugs in production: stock can be restored twice for one order, and some orders can stay `PENDING` forever. Both fixes are small and fit in the current structure. You can write them into the doc in an hour.

## What's already solid
- The stock decrement is conditional (`available >= :qty`), so stock can't go negative under concurrent requests.
- The payment call happens outside any database transaction, and the order id is sent as the provider's idempotency key on every attempt.
- Unknown payment results go to a reconciliation job instead of being guessed. There's also an alert for orders stuck in `PENDING`.
- Module boundaries are clear, routes are thin, and the test list already covers the main payment outcomes.

## Must fix before building

**1. Two writers can settle the same order, so stock gets restored twice.** Nothing stops the reconciliation job from settling an order that something else has already settled. With two instances, the job probably runs on both. Example: stock for SKU `A` is 5. An order for 2 leaves it at 3. The charge result comes back unknown. Both instances' reconciliation jobs see the order as `PENDING`, both learn it was declined, and both run "mark `FAILED` and add 2 back". Stock ends at 7 instead of 5, and you can now sell two units you don't have. The same thing happens if a slow request thread and the job both settle one order.
*Fix:* every status change is a guarded update, `UPDATE orders SET status = :new WHERE id = :id AND status = 'PENDING'`. Restore stock only if that update changed one row, and do it in the same transaction. The job should also use `FOR UPDATE SKIP LOCKED`, or a single scheduled runner, so the two instances don't pick up the same orders.

```mermaid
stateDiagram-v2
    [*] --> PENDING: stock reserved, order inserted
    PENDING --> PAID: charge succeeded (only if still PENDING)
    PENDING --> FAILED: charge declined, stock restored (only if still PENDING)
    PAID --> [*]
    FAILED --> [*]
```

**2. The design doesn't say what happens when the provider has no record of the charge.** Example: an instance commits the `PENDING` order in step 2, then crashes or gets redeployed before step 3 sends the charge. Two minutes later the job asks the provider and gets "not found". The design only defines `PAID` and `FAILED`. The order sits in `PENDING` and holds its stock until someone acts on the 30-minute alert by hand.
*Fix:* decide the rule. My recommendation: if the order is older than about 10 minutes and the provider has no record, mark it `FAILED` and restore the stock (guarded as in item 1). Also confirm that the provider lets you look up a charge by your idempotency key or by metadata. Some providers don't, and step 6 depends on it.

## Should fix (small, cheap now)

3. **Deadlock risk in step 2.** Example: cart X holds SKUs `[A, B]` and cart Y holds `[B, A]`. If they check out at the same moment, each one locks its first row and waits on the other. Postgres then aborts one of them, and the customer sees an error. *Fix:* update stock rows in sorted SKU order.
4. **Scope the idempotency key per customer.** Use a unique constraint on `(customer_id, idempotency_key)`. With a global constraint, a key collision returns another customer's order. Also define what happens when the same key arrives with a different cart: I suggest returning `422`.
5. **The client has no way to learn the final result after a `202`.** Add `GET /orders/{id}` so the client can poll.
6. **The email can be lost.** Step 4 commits `PAID` and only then queues the email, so a crash between the two drops it. *Fix:* insert the email job in the same transaction as the `PAID` update (an outbox table).
7. **Data model gaps:**
   - No primary or foreign keys are stated. They should be: `stock.sku` primary key, `order_items (order_id, sku)` primary key with a foreign key to `orders`.
   - Add `CHECK (available >= 0)` and `CHECK (quantity > 0)`.
   - Add a `provider_charge_id` column on `orders`; you'll need it for refunds and support lookups.
   - State that `unit_price` and `total` come from the server's catalog, not from the client's cart.

## Missing tests
Add these to the test plan, writing them before the code:
- Two reconciliation runs on one order: stock is restored once.
- Request path and reconciliation job settle the same order at once: one of them wins.
- Crash after step 2, before the charge: the provider has no record and the order resolves.
- Two carts with the same SKUs in opposite order: no deadlock.
- Same idempotency key with a different cart: rejected.
- The reconciliation job's own unit tests: no record, still unknown, paid, declined.

The core design is good. Items 1 and 2 must go into the doc before coding starts; items 3–7 are about a line each.

VERDICT: READY WITH CHANGES
