# Review of design.md (checkout flow for order-service)

**Not ready to build tomorrow.** As written, the flow can charge a customer twice, and it can take their money without saving an order. Both problems are in steps 3–6, the core of the design, so fixing them changes the shape of the flow rather than adding a line here and there. The code-structure section is mostly fine. The fixes are well known and should take a few hours of design work, not a rethink.

## Blockers (fix before writing code)

**1. Retrying the charge can bill the customer up to four times.**
Step 4 retries the charge on a 5 s timeout, but a timeout doesn't mean the charge failed. Example: the provider charges the card but its reply takes 6 s. The service gives up at 5 s and retries. That second charge succeeds, so the customer has paid twice for one order. With 3 retries, the worst case is 4 charges.
*Fix:* send an idempotency key (the order id works) on every charge call, so the provider handles a retry as the same charge. Check that your provider supports this. Most do (Stripe, Adyen, Braintree).

**2. The service can take money and have no order to show for it.**
Steps 3–6 keep a database transaction open while calling the payment provider, which can last more than 20 s. Two ways this goes wrong:
- The charge succeeds, then the process crashes or the commit fails. The transaction rolls back, the `PENDING` row disappears, and the customer has been charged for an order that doesn't exist.
- The `PENDING` row is never visible outside the transaction, so it records nothing. Nothing can find or reconcile it.

*Fix:* commit `PENDING` first, call the provider outside any transaction, then update the order in a second short transaction.

**3. An unclear payment result is reported as a failure.**
If all retries time out, nobody knows whether the customer paid. Step 6 rolls back and returns an error anyway, so the customer may try again and pay twice. Also, step 4 only covers timeouts. A card decline must not be retried at all.
*Fix:* add a `PAYMENT_UNKNOWN` state. Resolve it through the provider's webhook, or a job that queries the provider by idempotency key. Tell the client "processing", not "failed".

**4. A client retrying `POST /orders` creates duplicate orders.**
A request that takes 20 s will hit client or load-balancer timeouts, and the client will resubmit. Each resubmission creates a new order.
*Fix:* require an `Idempotency-Key` header on `POST /orders` and return the existing order when a key repeats.

**5. The design never decides what happens when stock runs out.**
Step 2 checks stock against a cache that can be 5 minutes old, and no step reserves or decrements stock. Example: one unit is left, two customers check out within the 5 minutes, and both are charged. That may be acceptable at 2,000 orders a day, but the design has to say so and say what happens next (refund? backorder?). Otherwise the payments module will have to make that call ad hoc. The inventory module also needs to be told about the sale, and right now nothing tells it.

## Proposed flow

```mermaid
sequenceDiagram
    participant C as Client
    participant S as OrderCheckout
    participant DB as Postgres
    participant P as Payment provider
    C->>S: POST /orders (Idempotency-Key)
    S->>S: stock check (cache)
    S->>DB: insert PENDING, commit
    S->>P: charge (idempotency key = order id)
    alt success
        S->>DB: mark PAID, commit
        S->>DB: write "send email" to outbox
    else declined
        S->>DB: mark FAILED, commit
    else timed out after retries
        S->>DB: mark PAYMENT_UNKNOWN, commit
        Note over S,P: reconciled later by webhook or polling job
    end
    S-->>C: order + status
```

## Should fix (lower risk, still before launch)

- **Confirmation email:** sending it inline after commit means a failed or slow email can produce an error even though the order succeeded. Use an outbox table plus a worker, as shown in the diagram.
- **Tests:** one happy-path integration test isn't enough for this flow. You need tests for:
  - timeout then success, where a mock provider confirms it received a single charge
  - decline, which must not be retried
  - all retries timing out, ending in `PAYMENT_UNKNOWN`
  - a crash between the charge and the update
  - the same client idempotency key sent twice

  These are the bugs above, so write them first.
- **Backups:** nightly backups mean losing up to 24 hours of orders. The provider would still hold those payments while you had no record of them. Continuous point-in-time recovery (WAL archiving, or managed Postgres PITR) is cheap. Turn it on, or record the 24-hour loss window as an accepted risk.
- **Alerting:** add a metric and an alert on orders stuck in `PENDING` or `PAYMENT_UNKNOWN`. Logs alone won't show you a stuck order.

## What's fine

- The module boundaries (no module reads another module's tables), thin routes, and an `OrderCheckout` service that coordinates the modules are a sound layout.
- Scale isn't a concern: 2,000 orders a day is about 1.4 a minute. A single Postgres instance is the right choice. Don't add queues or replicas for throughput.

## Next step

Revise steps 3–6 to match the diagram. Add the order state list (`PENDING`, `PAID`, `FAILED`, `PAYMENT_UNKNOWN`), the two idempotency keys and the stock-out decision. Then start with the failure-path tests. If that revision is done today, building tomorrow is realistic.

VERDICT: NOT READY
