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

**Yes, you can start tomorrow, but fix three things in the doc first.** Each is a few sentences, not a redesign. The core is sound: stock is reserved in a single atomic update, the payment call stays outside the database transaction, retries reuse the order id as the provider's idempotency key, a reconciliation job settles unknown results, and there's an alert for orders stuck in `PENDING`. At 2,000 orders a day, load isn't a concern.

The problems are all in the lifecycle below: how an order leaves `PENDING`, and what happens to its stock when it does.

```mermaid
stateDiagram-v2
    [*] --> PENDING: POST /orders (stock reserved)
    PENDING --> PAID: charge succeeds (request or reconciliation)
    PENDING --> FAILED: charge declined (request or reconciliation)
    PENDING --> PENDING: result unknown, 202 returned
    FAILED --> [*]: stock restored
    PAID --> [*]: email queued
```

## Fix before building

**1. Two writers can settle the same order, and stock gets restored twice. (High)**
The reconciliation job runs every 5 minutes, and you have two instances. Unless only one of them runs the job, both can pick up the same order. Example: an order for 3 units of SKU-A is stuck in `PENDING`, and the provider reports the charge as declined. Both instances mark it `FAILED` and both add 3 back. Stock goes up by 6 when it should go up by 3. The same thing can happen if the request thread and the job ever overlap.
*Fix:* make each status change conditional, e.g. `UPDATE orders SET status='FAILED' WHERE id=:id AND status='PENDING'`. Only restore stock or queue the email when that update changes exactly one row. Also say whether the job runs on one instance or both (an advisory lock or `FOR UPDATE SKIP LOCKED` works).

**2. Reconciliation is only half specified. (Medium)**
Step 6 says the job settles orders as `PAID` or `FAILED`, but it doesn't say:
- whether a `FAILED` result restores stock (step 5 does; step 6 is silent, so stock could leak), or whether a `PAID` result queues the confirmation email;
- what to do when the provider has **no charge** for the order. Example: an instance crashes right after step 2 commits. The order is `PENDING`, nobody was charged, and the provider answers "not found". Nothing in the doc covers that answer.
*Fix:* say that "not found" after the 2-minute window counts as `FAILED`, and route the job through the same settle functions as steps 4 and 5.

**3. Input validation isn't stated, and the reservation SQL depends on it. (Medium)**
If `quantity = -5`, the check `available >= -5` passes and `available - (-5)` adds 5 units to stock, which also makes the total negative. The doc also doesn't say where `unit_price` comes from. If it comes from the client's cart, the client sets its own price.
*Fix:* require `quantity > 0` (validate it and add a `CHECK` constraint), and state that prices are looked up on the server.

## Should fix (small)

- **Email can be lost on a crash (Low–Medium).** Step 4 commits `PAID` and only then queues the email. A crash in between means the email is never sent. Write an outbox row in the same transaction instead.
- **Idempotency key is unique across all customers (Low–Medium).** One customer reusing another customer's key would get back that customer's order. Make the constraint `(customer_id, idempotency_key)`. It would also help to reject a reused key that comes with a different cart.
- **Concurrent duplicate requests (Low).** Two simultaneous requests with the same key will make the second one fail with a unique-constraint violation. Say that this error is caught and the existing order returned.
- **Deadlocks on multi-item carts (Low).** Two carts that lock the same SKUs in opposite order can deadlock. Run the reservation updates in a fixed order, sorted by SKU.
- **Module boundaries need one sentence (Low).** Steps 2 and 5 write to orders and stock in a single transaction, which is fine. State how that works without breaking the "no module reads another module's tables" rule, e.g. the inventory module's functions accept the caller's transaction.
- **Client has no way to follow up (Low).** After a `202`, how does the client learn the result? There's no `GET /orders/{id}` or webhook in the doc.
- **Schema gaps (Low):**
  - `stock.sku` and `order_items` have no primary keys or foreign keys.
  - No `CHECK` constraint on `status`.
  - No column for the provider's charge id, which refunds and support will need.
  - No index on `orders(status, created_at)` for the reconciliation query.

## Tests to add

The reconciliation job, the riskiest part of the design, has no tests in the plan. Add these:
- reconciliation settles an order as `PAID`, as `FAILED` (with stock restored), and on a "not found" answer;
- two settles of the same order restore stock only once;
- two concurrent POSTs with the same key;
- two buyers racing for the last unit;
- a two-item cart where the second item is out of stock (the first item's stock must be rolled back);
- the confirmation email fails and the order still ends up `PAID`;
- a negative or zero quantity is rejected.

## Things to check, not confirmed problems

- The whole retry design assumes the provider deduplicates charges by idempotency key. Check in their docs or sandbox how long they keep keys, and whether they reject a reused key with a different amount. A test against the fake provider can't tell you this.
- The worst-case retry time (4 attempts × 5 s plus backoff) is under the 2-minute reconciliation window, so the job and the request thread shouldn't overlap. A stalled process could still exceed it, and fix #1 covers that case.

VERDICT: READY WITH CHANGES
