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

You can start building tomorrow, but fix three things in the doc first. Each fix is a sentence or two. The overall approach is sound:
- stock is reserved with a conditional update,
- the payment call runs outside any transaction,
- the order id is sent to the provider as the idempotency key,
- a reconciliation job settles payments whose result is unknown,
- the email is retried from the queue and never fails the order.

At 2,000 orders a day, scale is not a concern.

The gaps are mostly in the status changes and stock restores once more than one actor can touch the same order. Here is the lifecycle as it should end up:

```mermaid
stateDiagram-v2
    [*] --> PENDING: stock reserved, order inserted
    PENDING --> PAID: charge succeeds (request or reconciliation job)
    PENDING --> FAILED: declined, or provider has no charge → restore stock
    PAID --> [*]: queue confirmation email
    FAILED --> [*]
```

## Fix before you start coding

**1. High: the reconciliation job loses stock when it marks an order `FAILED`.** Step 5 restores stock on a decline. Step 6 only says the job "settles them as PAID or FAILED" and never restores stock.
- Case: an order for 2 × SKU-A times out on every attempt. Five minutes later the job learns the charge was declined and marks it `FAILED`.
- Expected: `available` goes back up by 2.
- As written: the 2 units stay reserved forever.
- Fix: put "mark FAILED and restore stock" in one shared function that both step 5 and step 6 call.

**2. High: two actors can settle the same order, so stock can be restored twice.** Both service instances may run the reconciliation job, and a slow request can still be finishing while the job runs.
- Case: both instances' jobs pick up the same `PENDING` order and both get "declined".
- Expected: one restore.
- As written: `available` goes up by 4 instead of 2.
- Fix: every status change is `UPDATE orders SET status = … WHERE id = :id AND status = 'PENDING'`, and stock is restored only when that update changed a row. State this in the design. It also covers the job and a late request racing each other.

**3. High: the job has no rule for "provider has no record of this charge".** This happens when an instance crashes after the step 2 commit but before the charge call.
- Case: the order is `PENDING` and the provider returns "not found".
- Expected: a defined outcome.
- As written: undefined. If the job just leaves it, the order stays `PENDING` forever and its stock stays reserved.
- Fix: treat "not found" after 2 minutes as `FAILED` plus a stock restore, or as a fresh charge attempt with the same idempotency key. Pick one and write it down.

## Fix this week, as you build those parts

**4. Medium: where do prices come from?** The client sends "the cart", and `order_items.unit_price` is stored. If the price comes from the client, they can set it.
- Case: a cart says `unit_price: 0.01` for a $50 item, and the order is charged $0.01.
- Fix: say that prices and `total` are computed on the server from the catalog. If there is no catalog yet, name where prices live.

**5. Medium: quantity is never validated.**
- Case: `quantity: -5` makes `available - (-5)` add 5 units of stock, and the `available >= :qty` check passes.
- Fix: require `quantity > 0`, merge duplicate SKU lines, and add `CHECK (available >= 0)` on `stock`.

**6. Medium: two carts can deadlock each other.**
- Case: cart 1 updates SKU A then B, while cart 2 updates B then A at the same moment. Postgres aborts one of them, and the client gets a 500 instead of a 409 or a success.
- Fix: update stock rows in sorted SKU order.

**7. Medium: the design contradicts its own module boundaries.** "No module reads another module's tables", yet one transaction writes both `orders` and `stock` (steps 2 and 5). Decide how this works. The simplest option: the inventory module exposes `reserve` and `release` functions that take the caller's transaction, and `OrderCheckout` owns the transaction.

**8. Medium: a client that gets `202` has no way to learn the outcome.** No `GET /orders/{id}` endpoint, polling contract, or webhook is specified. Add one.

**9. Medium: orders settled as `PAID` by the job may never get a confirmation email.** Step 4 queues the email only on the request path. The same shared settle function from fix 1 should queue the email for both paths.

**10. Medium: the test list misses the riskiest paths.** Add:
- the job settling `PAID`, `FAILED` and "not found" (and checking stock after each),
- both instances' jobs running at once,
- the job and a late request racing,
- two concurrent buyers for the last unit,
- two concurrent `POST /orders` with the same key,
- a multi-item cart where only the last item is short (everything rolls back),
- a crash between the order commit and the charge,
- negative or zero quantity.

## Low: tidy when convenient

- **11. Same key, different cart.** A repeated `Idempotency-Key` with a different cart silently returns the old order. Store a hash of the request and return `422` on a mismatch. Consider scoping the key's uniqueness to `(customer_id, idempotency_key)`.
- **12. Concurrent duplicate requests.** The loser of two simultaneous requests with the same key hits a unique-constraint violation. Catch it and return the existing order instead of a 500.
- **13. Email lost on crash.** If the queue lives outside Postgres, a crash between the `PAID` commit and the enqueue loses the email. An outbox row (a `pending_emails` table written in the same transaction) closes this.
- **14. Retry rules.** Retry only on timeouts and 5xx responses, never on a decline or other 4xx. Say so explicitly.
- **15. Schema details.** Primary keys (`stock.sku`, `order_items(order_id, sku)`), a foreign key from `order_items` to `orders`, a `CHECK` on `status`, and an index on `orders(status, created_at)` for the reconciliation job's query.

Items 1–3 are spec gaps that would become money or stock bugs in production. Write them into the design before you code the payment and reconciliation parts. You can start on the data model and inventory module tomorrow regardless.

VERDICT: READY WITH CHANGES
