# Review of design.md (revision 3)

You can start tomorrow. The overall shape is sound, but six specific gaps should be written into the doc first. Two of them would cause wrong stock counts or stuck orders in production. Each fix is a sentence or two in the doc and doesn't change the architecture.

## What's already solid

- Stock is reserved with a conditional `UPDATE ... WHERE available >= :qty`, so stock can't go negative and no explicit locks are needed.
- The payment call happens outside any transaction, so a slow provider doesn't hold database locks.
- The order id is the provider idempotency key, so retries can't double-charge.
- Unknown payment results get an honest `202`, a reconciliation job, and an alert as a backstop.
- The email is queued after commit and never fails an order.
- The test list covers the main failure paths.

## Must fix before building

**1. Two code paths can settle the same order, and stock gets restored twice.**
The request handler (steps 4–5) and the reconciliation job (step 6) can both settle an order. Both service instances also run the 5-minute job. Concrete case: order X holds 1 unit of `SKU-A` and the provider says "declined". Instance 1's job and instance 2's job both see X as `PENDING` and both run "mark FAILED and restore stock".
- **What happens:** `SKU-A.available` goes up by 2.
- **Expected:** it goes up by 1.

**Fix:** every status change must be `UPDATE orders SET status = :new WHERE id = :id AND status = 'PENDING'`, and stock is restored only if that update changed exactly one row. Also say how the job avoids running on both instances at once, for example with a Postgres advisory lock or `FOR UPDATE SKIP LOCKED`.

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

Every arrow out of `PENDING` can be taken by more than one caller. The conditional update makes sure only the first caller wins.

**2. The case where the provider has no record of the charge is undefined.**
Suppose an instance crashes or redeploys after step 2 commits but before step 3 reaches the provider. The order is `PENDING`, its stock is reserved, and the provider has never heard of it. The job asks for the charge status and gets "not found". The doc only describes settling as `PAID` or `FAILED`, so this order stays `PENDING` forever and keeps its stock. The 30-minute alert fires, but someone has to fix it by hand every time.

**Fix:** decide on a rule. For example: "not found and older than N minutes" means `FAILED` plus stock restored. This is safe because nothing will retry the charge after the original request has ended. Add an integration test for it.

## Should fix (cheap, and better done now)

**3. Deadlock on multi-item carts.** Order A updates `SKU-1` then `SKU-2`. At the same time, order B updates `SKU-2` then `SKU-1`. Postgres aborts one of them with a deadlock error, and that user gets a `500`. **Fix:** sort SKUs before running the stock updates.

**4. A confirmation email can be lost.** If the process dies between "commit PAID" and "queue email", that email is never sent. Orders settled by the reconciliation job aren't mentioned as sending email at all. **Fix:** write the email job to an outbox table in the same transaction as the `PAID` update, and send it from both code paths.

**5. Module boundaries vs. shared transactions.** The doc says "No module reads another module's tables". But steps 2 and 5 change `stock` and `orders` in one transaction. That's fine, but state how: for example, the inventory module exposes `reserve(tx, items)` and `release(tx, items)`, and the orders module passes in its transaction. Otherwise the first implementation will query `stock` directly from orders code.

**6. Small API and data-model gaps:**
- A client that gets `202` has no documented way to learn the outcome. Add `GET /orders/:id`.
- Scope the idempotency key per customer, as a unique constraint on `(customer_id, idempotency_key)`. Also define what happens when the same key arrives with a different cart; returning `422` is a common choice.
- State that `unit_price` and `total` come from the server's catalog, not from the client's cart.
- Add primary keys: `order_items (order_id, sku)` and `stock (sku)`.
- In the worst case the charge takes about 20 seconds plus backoff (4 attempts × 5 s). Check that this fits within the load balancer's request timeout.

## Tests to add to the plan

- Two concurrent `POST /orders` with the same key: one order, stock reserved once.
- Two concurrent buyers for the last unit: one `201`, one `409`.
- The reconciliation job settling `PAID`, `FAILED`, and provider "not found".
- The job running twice at once: stock is restored only once (covers fix 1).
- Multi-item carts in opposite SKU order running concurrently (covers fix 3).

At 2,000 orders a day, nothing here is a scaling concern. The current infrastructure (two instances, one Postgres) is right-sized.

VERDICT: READY WITH CHANGES
