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

**Don't start building tomorrow from this version.** Two parts of the payment flow can take a customer's money with no order to show for it. Both come from how steps 3 to 6 are put together, so fixing them means rewriting the Flow section, not adding a line. That rewrite is roughly half a day of design work. The context, the module layout and the scale assumptions are fine.

## Blockers (fix in the doc before writing code)

**1. Retrying a charge after a timeout can charge the customer twice.**
A timeout does not mean the charge failed. It means you don't know what happened.
- Case: the first charge call reaches the provider and succeeds, but the response takes longer than 5 s. The service retries and the provider sees a second, separate charge.
- Wrong result: the customer is charged twice, for example $50 + $50.
- Expected: one charge of $50.
- Fix: send an idempotency key with every charge attempt (the order id works). Most providers support this, so retries return the original result instead of charging again. Check that yours does before you commit to the retry policy.

**2. The payment call happens inside an open database transaction, so a rollback can erase an order that was paid for.**
- Case: the charge succeeds, then the commit fails (connection dropped, deadlock, deploy restart). Or all 4 attempts time out even though one of them actually went through.
- Wrong result: the transaction rolls back, the `PENDING` row disappears, and the client gets an error. The customer has paid and there is no record of the order on your side.
- Expected: an order row that says the charge happened, or at least that its outcome is unknown.
- Also: the `PENDING` state does nothing in this design. No one outside the transaction can ever see it, because it is never committed on its own.
- Side effect: each checkout holds a database connection for up to about 20 s (4 attempts × 5 s). At 2,000 orders a day that is survivable, but a slow provider would use up your connection pool.

**3. There's no defined outcome when a payment ends in an unknown state.**
After the last retry times out, step 6 rolls back and returns an error, but the charge may have succeeded. The design needs:
- a status such as `PAYMENT_UNKNOWN`
- a reconciliation job that asks the provider what happened to orders stuck in `PENDING` or `PAYMENT_UNKNOWN`, then marks each one `PAID` or `FAILED`
- a response to the client that doesn't say "failed" when the honest answer is "we're checking"

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: Check stock (inventory cache)
    S->>DB: Tx 1: insert order PENDING, commit
    S->>P: charge(idempotency key = order id), retries reuse the same key
    alt success
        S->>DB: Tx 2: mark PAID
        S-->>C: 201 PAID
        S->>S: queue confirmation email
    else declined
        S->>DB: Tx 2: mark FAILED
        S-->>C: 402 declined
    else still timing out after retries
        S->>DB: Tx 2: mark PAYMENT_UNKNOWN
        S-->>C: 202 processing
        Note over S,P: Reconciliation job asks the provider later and settles the order
    end
```

## Should fix (decide before or during the first sprint)

**4. A client retry creates a duplicate order.** Mobile clients and browsers resend `POST /orders` when a request is slow. Without a client-supplied `Idempotency-Key` header, a double tap produces two orders and, with blocker 1 fixed, two separate charges, because each order has its own key.

**5. Overselling is possible and the design doesn't say what happens next.** The stock check reads a cache that can be up to 5 minutes old, and nothing reserves or decrements stock.
- Case: one unit is left, and two customers check out within the same 5-minute window. Both pass the check, both are charged, and one order can't be fulfilled.
- Accepting the cache to avoid the 800 ms warehouse call is a reasonable tradeoff, but the design has to state the consequence. Either (a) reserve stock with the warehouse after payment and refund automatically if the reservation fails, or (b) accept overselling and name who handles the refund and how.

**6. The confirmation email shouldn't be able to fail the checkout.** Step 5 sends it inline. If the email provider is slow or down, it shouldn't affect a paid order. Write an "email pending" record in the same transaction that marks the order `PAID` (the transactional outbox pattern) and send from a worker, or at least send in the background and log failures.

**7. The test plan only covers the case where everything works.** One happy-path integration test isn't enough for a payment flow. Add tests, written first, for:
- a timeout followed by success on retry, checking that the same idempotency key is sent each time
- a timeout on every attempt, ending in `PAYMENT_UNKNOWN`
- a declined payment
- the charge succeeding but the database update failing
- a duplicate `POST /orders` with the same idempotency key
- reconciliation settling a stuck order

A fake payment provider that can be scripted to time out, decline or succeed will make all of these cheap to write.

## Worth noting (not blocking)

- **Nightly backups mean up to 24 hours of lost orders.** If Postgres fails at 11 pm, the day's orders are gone from your side while the provider still holds the charges. Turn on point-in-time recovery (continuous WAL archiving). Most managed Postgres services offer it as a setting.
- **Timeout budget:** 4 attempts × 5 s plus the 800 ms fallback path is well past what a client will wait. Set a total deadline, around 10 s, after which the order goes to `PAYMENT_UNKNOWN`.
- **Scale is not a concern.** 2,000 orders a day averages under 2 a minute, so a single Postgres instance and a team of four are fine.
- **The code structure section is good:** separate modules, no module reading another's tables, thin routes, structured logs keyed by order id. Keep it. Payment state changes should be logged with the provider's charge id as well as the order id so reconciliation can be traced.

## What to do before building
1. Rewrite the Flow section to match the diagram: commit `PENDING` before charging, use idempotency keys for both the client and the provider, and add the `PAYMENT_UNKNOWN` status plus reconciliation.
2. Write down the oversell policy, option (a) or (b) from point 5.
3. Expand the test plan with the failure cases in point 7.

Once those three are in the doc, the design is ready to build.

VERDICT: NOT READY
