# How PayRail code maps to the interview

**Read this on the portal.** You do not have to unzip first to understand the design.

**In one sentence:** The same `Idempotency-Key` must return the same `order_id`. A new UUID after a timeout is a second charge.

PayRail assumptions used in the sprint: **8M charges/day ≈ 93/s**, Black Friday **1,200/s**, **2% retries ≈ 24 duplicate attempts/s** without a key.

## The four answers you must be able to point at

| Interview sentence | Function / file | What happens |
|--------------------|-----------------|--------------|
| “I claim the key before I call the gateway.” | `claim_key` in `lab_store.py` / `dynamo_store.py` | First writer inserts `status=processing`. Everyone else sees the existing row. |
| “Same key + same body = replay.” | `charge()` in `charge.py` | If `completed`, return the cached 201 and `x-idempotent-replay: true`. |
| “Same key + different body = 409.” | `charge()` after the hash check | `request_hash` is SHA-256 of `{amount_cents, currency}`. |
| “Store down → fail closed.” | `StoreDown` → 503 | Do not charge if you cannot record the attempt. |

## Happy path (first POST)

1. Client sends `Idempotency-Key` + `X-Tenant-Id` + `{ amount_cents, currency }`.
2. `charge()` hashes the body.
3. `claim_key` creates a `processing` row (or returns the existing one).
4. Mock Stripe writes one PaymentIntent keyed by `tenant#key` — not a new intent per retry.
5. An `order_id` is minted **once**, stored, and cached on the key row.
6. A webhook event is enqueued. The worker dedupes on `event_id`.

## Timeout path (the interview trap)

`X-Lab-Crash-After-Claim: 1` returns 504 and **leaves the row `processing`**.

- A retry with the **same** key sees `processing` → **409 in flight** (client should wait / retry the same key).
- The **sweeper** (`sweeper.py`) looks for a gateway intent:
  - Intent exists → complete the key (the money already moved).
  - No intent → mark `failed`. Do not invent a second charge.

> **COMMON MISTAKE:** Minting a new `Idempotency-Key` because the first call timed out. That is a second `claim_key` and a second order.

## Why DynamoDB in the student lab

Production mapping you say out loud: **ALB + ECS + Aurora**. The lab uses **HTTP API + Lambda + DynamoDB** so a same-day destroy stays under **$2**. The *state machine* is what you are learning, not the SKU names.

## Files to open in the source browser on Build PayRail

1. `charge.py` — claim / replay / 409 / 503
2. `lab_store.py` — in-memory version of the same API (pytest + local server)
3. `dynamo_store.py` — the AWS version (`attribute_not_exists` claim)
4. `sweeper.py` — heal stuck `processing`
5. `worker.py` — `event_id` dedupe
6. `terraform/main.tf` — what `apply` builds
