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

You can start building tomorrow. The core of the design holds up: the conditional stock update, committing before the charge, using the order id as the payment key, and reconciling unknown results are the right choices for 200 to 2,000 orders a day. But there are a few gaps to close before you write the code they affect. The biggest is that the design never says where item prices come from. Most of the gaps take a sentence or a paragraph to fix, and none of them change the overall structure.

## Must fix before building the affected step

**1. Where prices come from is never defined (High).** The data model has no price table, and `stock` has no price column. Step 1 says the client "sends the cart". If `unit_price` and `total` come from that request, a customer can send `unit_price: 0.01` for a $200 item and get charged a cent. Say that the server looks up prices from a named source (a table or another service) and calculates `total` itself.

**2. Quantity is never checked (High).** Take a cart line `{sku: "A", quantity: -5}`. Step 2 runs `available = available - (-5) WHERE available >= -5`, which matches every row, so stock goes **up** by 5 and the order goes through. It should be rejected with `400`. Add a rule that quantity must be greater than 0, both in request validation and as a `CHECK` constraint on `order_items`.

**3. Reconciliation doesn't cover a charge the provider never received (High).** If an instance crashes or is redeployed after the step 2 commit but before step 3, the order is `PENDING` and the provider has no charge for it. Reconciliation can only settle orders as `PAID` or `FAILED`, so this order stays `PENDING` forever, its stock stays reserved, and the 30-minute alert keeps firing. This will happen on ordinary deploys, not just rare crashes. Decide what reconciliation does when the provider says "not found": either retry the charge with the same key, or mark the order `FAILED` and restore the stock.

**4. Two code paths can settle the same order (Medium).** Steps 4 and 5 (the live request) and the reconciliation job can both act on one order. Both instances also run the job every 5 minutes. For example, if both instances' jobs see a declined order, each one restores its stock, so 2 units go back for 1 ordered. Two fixes:
- Make every status change conditional: `UPDATE orders SET status = … WHERE id = :id AND status = 'PENDING'`, and only restore stock if that update changed a row.
- Stop the two instances' jobs from settling the same order at once, for example with `SELECT … FOR UPDATE SKIP LOCKED` or a Postgres advisory lock.

```mermaid
stateDiagram-v2
    [*] --> PENDING: step 2 commit
    PENDING --> PAID: charge succeeded (request or reconciliation)
    PENDING --> FAILED: declined (request or reconciliation)
    PENDING --> PENDING: provider has no charge (not defined, stuck)
```

Every arrow out of `PENDING` should be the guarded update from item 4.

## Should fix (Medium)

**5. Idempotency key scope and mismatched repeats.** If the unique constraint covers `idempotency_key` alone, two customers whose clients generate the same key get each other's order back. Make it unique on `(customer_id, idempotency_key)`. Also decide what happens when a repeated key arrives with a different cart. The usual answer is to store a hash of the request and return `422` when it doesn't match. And say what a repeat returns while the first request is still charging: the current order with `202`, and no second charge.

**6. A `202` client has no way to learn the result.** Step 6 returns `202`, but the design defines no `GET /orders/{id}` endpoint and no callback. Add the endpoint for clients to poll.

**7. The confirmation email can be lost.** Step 4 commits and *then* puts the email on the queue. If the process crashes between the two, the order is `PAID` and no email is ever sent. Write an outbox row in the same transaction as the status change, and have a worker send from that table. Also say whether the queue keeps messages through a restart.

**8. Transactions cross module boundaries without saying how.** Steps 2 and 5 change `stock` (inventory module) and `orders` (orders module) in one transaction, while the code-structure section says no module touches another module's tables. Both can be true, but only if `OrderCheckout` owns the transaction and passes it into each module's own methods. Write that down so nobody "fixes" it later by splitting it into two transactions.

**9. The test list is missing the riskiest paths.** Add tests for:
- reconciliation settling as paid, declined, and "not found";
- a crash between the step 2 commit and the charge;
- a decline restoring stock exactly once;
- two concurrent buyers of the last unit (a real concurrency test, not just a sequential one);
- a failed email not affecting the order;
- items 2 and 5 above.

## Minor (Low)

**10. Possible deadlocks.** Cart X reserves SKUs A then B, while cart Y reserves B then A, and Postgres aborts one of them. Reserving SKUs in sorted order prevents this.

**11. Keys and constraints aren't declared.** The data model has no primary key on `stock.sku` or `order_items`, and no foreign key from `order_items.order_id`. Add them, and add `CHECK (available >= 0)` on `stock` as a backstop.

**12. Slow `POST /orders`.** With a 5 s timeout and 3 retries plus backoff, one request can hang for about 25 to 30 seconds. Check that the load balancer and client timeouts are longer than that. If they're shorter, the client gives up and retries while the first attempt is still running. Item 5 makes that safe, but it's wasted work.

## Possible concerns, not yet supported by the design
- **How long the provider honours idempotency keys.** If it forgets them after a set period (some providers use 24 hours), a very late retry could charge twice. This doesn't matter with the current timings, but confirm the period.
- **Currency.** `order_items` has no currency column, so the design assumes every item in an order has the same currency. That's fine if there's only one currency per store.

## Suggested order of work
Fix items 1 and 2 in the doc tonight, since they affect step 1 and step 2, which you'll build first. Fix items 3, 4 and 7 before you start on the payment and reconciliation code. The rest can be done as you go.

VERDICT: READY WITH CHANGES
