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

You can start building tomorrow, but fix six things in the doc first. Each is a sentence or two of spec, not a redesign. The main choices are sound and you should keep them: the conditional stock `UPDATE`, the charge call made outside any transaction, the order id reused as the provider's idempotency key, a reconciliation job for charges whose outcome is unknown, and the email sent after commit and never allowed to fail the order.

## Fix before building

**1. Stock can be restored twice when an order fails.** You run two instances, and the doc doesn't say the reconciliation job runs on only one of them. Both instances can pick up the same `PENDING` order in the same 5-minute cycle.
- Case: order O reserved 2 units of SKU A, and the provider later reports the charge declined. Instance 1 marks O `FAILED` and adds 2 back. Instance 2 does the same. `available` ends 2 higher than it should, so you sell stock you don't have.
- The same race can happen between the request handling a live checkout (steps 4–5) and the job, though that is rarer.
- Fix: make every status change conditional, e.g. `UPDATE orders SET status = 'FAILED' WHERE id = :id AND status = 'PENDING'`. Only restore stock or queue the email if that update changed exactly one row. Optionally also make the job single-runner, using `FOR UPDATE SKIP LOCKED` or a Postgres advisory lock.

**2. A negative quantity increases stock.** Nothing in the doc validates `quantity`.
- Case: the cart has `quantity = -5`. `available >= -5` is always true, so the reservation succeeds and `available` goes up by 5. The order total comes out negative.
- Fix: validate `quantity > 0` at the API, and add `CHECK (quantity > 0)` on `order_items` and `CHECK (available >= 0)` on `stock`.

**3. The doc doesn't say where prices come from.** It says "the service sends the cart" and stores `unit_price`, but no table holds prices.
- Case: if `unit_price` is taken from the client, a client sending `unit_price: 0.01` gets charged 0.01.
- Fix: state that prices are looked up on the server (which table or service), and that the total charged is computed from those prices.

**4. Reconciliation doesn't cover a charge that was never made.** If an instance crashes after step 2 but before step 3, the provider has no record of the charge. The doc only lists the outcomes `PAID` and `FAILED`.
- Fix: say what "not found" means. Most likely it should mark the order `FAILED` and restore stock, since after 2 minutes no live request can still be charging it.
- Also say what happens when the provider keeps reporting "processing". Today the order just sits until the 30-minute alert fires.
- Also state that when reconciliation settles an order as `PAID`, it queues the confirmation email too. Step 4 currently covers only the live path.

**5. Two orders can deadlock on overlapping SKUs.**
- Case: order A reserves `[X, Y]` while order B reserves `[Y, X]` at the same moment. Postgres aborts one of them, and that client gets a 500.
- Fix: sort SKUs before running the updates. Merge duplicate SKU lines in a cart at the same time.

**6. Reconciliation has no tests.** It is the only path that settles unknown outcomes, and the test list doesn't mention it. Add tests for:
- the job settling an order as `PAID` (including the email being queued) and as `FAILED` (stock restored exactly once)
- the provider reporting "no such charge"
- two job runs overlapping on the same order
- two concurrent buyers going for the last unit. The current "last unit" test reads as a single buyer, which doesn't exercise the race.

## Worth stating, but not blocking

- **Idempotency key details:**
  - Scope the unique constraint to `(customer_id, idempotency_key)`, so two customers can't collide on the same key.
  - Say what happens when a request reuses a key with a different cart. Usually that returns `422`.
  - Say what happens when two requests with the same key arrive at the same time: catch the unique-constraint violation and return the existing order.
- **Email could be lost.** "Commit, then queue" loses the email if the process dies between those two steps. An outbox table written in the same transaction as the `PAID` update closes that gap. This is lower priority, because the customer is charged correctly either way.
- **Response time.** In the worst case a request takes about 20 s plus backoff (4 attempts × 5 s). The load balancer's timeout needs to be longer than that.
- **Missing columns and constraints.** The data model has no column for the provider's charge id, which you'll want for support and refunds. It also doesn't show primary or foreign keys on `order_items` and `stock`.
- **Shared transaction across modules.** Step 2 writes to both the inventory and orders tables in one transaction, while the module rule says no module touches another's tables. State that inventory exposes a `reserve(tx, items)` function that takes the caller's transaction, so the module boundary still holds.

## Order lifecycle with the guarded transitions

```mermaid
stateDiagram-v2
    [*] --> PENDING: stock reserved, order inserted
    PENDING --> PAID: charge succeeded (only if still PENDING) → queue email
    PENDING --> FAILED: declined or no charge found (only if still PENDING) → restore stock once
    PENDING --> PENDING: outcome unknown → reconciliation retries every 5 min
    PAID --> [*]
    FAILED --> [*]
```

Items 1 and 2 are the ones that would corrupt stock in production. Item 3 is an open question only you can answer.

VERDICT: READY WITH CHANGES
