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

**No, it isn't ready to build yet.** Three parts of the checkout flow would lose money or sell stock you don't have, even at today's 200 orders a day. Each fix is small and well known, so you can revise the doc tonight and still start tomorrow. The overall approach is sound: reserve stock, charge outside the transaction, then reconcile orders still in `PENDING`. The 2,000 orders a day you expect next year is not a scaling problem for this setup.

## Must fix before building

**1. Duplicate requests create duplicate orders (step 1).** Each instance keeps the idempotency keys it has seen in its own memory, and you run two instances behind a load balancer.
- *Case:* the client sends `POST /orders` with key `K` and instance A takes it. The client times out and retries with `K`, and the load balancer sends the retry to instance B. B has never seen `K`.
- *Result:* two orders, stock taken twice, two charges. *Expected:* B returns A's order.
- The same thing happens after any restart or deploy, because the map is wiped.
- *Fix:* add an `idempotency_keys` table (`key` primary key, `request_hash`, `order_id`, `created_at`) and insert into it in the same transaction as the order. If the key already exists, return the existing order. If the key matches but the request body is different, return `422`.

**2. A retry after a timeout can charge the customer twice (step 3).** The payment idempotency key is `<order id>-<attempt number>`, so every retry looks like a new charge to the provider.
- *Case:* attempt 1 (`O1-1`) succeeds at the provider, but the response arrives after your 5-second timeout. Attempt 2 is sent as `O1-2`.
- *Result:* two charges. *Expected:* one charge.
- Your test "timeout then success" won't catch this unless the fake provider records the timed-out charge as successful.
- *Fix:* use the order id alone as the provider key on every attempt. To trace each attempt, log the attempt number or send it as metadata, not in the key.
- Also say which failures are retried: timeouts and 5xx responses yes, declines never.

**3. Two buyers can both get the last unit (step 2).** The flow reads `available` and then writes `available - quantity`. Under Postgres's default isolation level (READ COMMITTED), two transactions running at the same time can both read the same value.
- *Case:* `available = 1`, and two checkouts run at once. Both read 1, both write 0, and both commit.
- *Result:* two orders for one unit. *Expected:* one order and one `409`.
- *Fix:* do the check and the decrement in one statement: `UPDATE stock SET available = available - $q WHERE sku = $s AND available >= $q`. If it updates zero rows, the item is short, so roll back and return `409`.
- Update items in `sku` order, so that two carts containing the same SKUs can't deadlock each other.

**4. Money is stored as `double precision`.** Floating-point numbers can't hold most decimal amounts exactly. For example, `0.1 + 0.2` gives `0.30000000000000004`, so order totals drift away from what the provider actually charged. Use `numeric(12,2)`, or store `bigint` minor units (cents). Fix this before the first migration; changing the type later is painful.

## The reconciliation job needs these rules written down

Right now step 6 only covers the happy path. These are the transitions that need to be explicit:

```mermaid
stateDiagram-v2
    [*] --> PENDING: stock reserved, order inserted
    PENDING --> PAID: charge succeeded (request or reconciliation)
    PENDING --> FAILED: declined, or provider has no charge (stock restored)
    PAID --> [*]
    FAILED --> [*]
```

- **What if the charge was never sent?** If an instance crashes between committing the order (step 2) and calling the provider (step 3), the order sits in `PENDING` and the provider has no record of it. The job needs a rule for this. I suggest: if the provider says "not found" and the order is old enough, mark it `FAILED` and restore the stock. Otherwise that stock stays locked up for good.
- **Restore stock on every route to `FAILED`.** Step 5 restores stock when the request path sees a decline, but step 6 says nothing about stock when the job settles an order as `FAILED`.
- **Make every status change conditional:** `UPDATE orders SET status = $new WHERE id = $id AND status = 'PENDING'`. Otherwise a slow request and the job can overwrite each other. For example, the request marks the order `PAID` while the job marks it `FAILED` and also restores the stock.
- **Add a status endpoint.** A client that gets `202` has no way to learn the result; the doc doesn't define `GET /orders/{id}`.

## Should fix (not blockers)

- **One transaction across two modules.** "No module reads another module's tables" conflicts with step 2, which writes `stock` (inventory module) and `orders` (orders module) in one transaction. Say how this works, for example: `OrderCheckout` opens the transaction and passes it to `inventory.reserve(tx, items)` and `orders.create(tx, …)`. Otherwise someone will break the boundary just to make it work.
- **Emails can be lost.** In step 4, the order is committed and then the email is queued. A crash between those two steps loses the email. Write an `outbox` row in the same transaction as the `PAID` update and have a worker send from it.
- **Missing tests:**
  - two buyers taking the last unit at the same time (a single-threaded test can't catch bug 3)
  - the same idempotency key sent to two instances
  - a provider that charges but times out (bug 2)
  - reconciliation: paid, declined, not found, and the job racing the request path
  - a crash between committing the order and charging
  - the same key sent with a different request body

## What's already good

The charge happens outside the database transaction. Email failures can't fail an order. Routes stay thin. Every log line carries the order id. The 30-minute alert on stuck `PENDING` orders gives the reconciliation job a backstop. Items 1–4 are edits to the doc, not a redesign, but building before you make them would mean building the double-charge and oversell bugs into the code.

VERDICT: NOT READY
