Stripe Idempotency Ledger Lab (Interactive)
Drop the HTTP 200 after the charge lands and count double-bills with and without keys. Simulate the payment retry dilemma at merchant scale: blind retries re-execute succeeded charges, while the IN_FLIGHT to COMPLETED key state machine replays cached responses and holds exactly-once accounting.
Idempotency-Key Retry Ledger
Networks drop the HTTP 200 after the card is charged. Retries that blind duplicate — unless an idempotency state machine returns the cached response instead.
How It Works Under the Hood
Distributed networks deliver an unbearable ambiguity: Stripe charged the card through Visa, but the 200 OK vanished in transit, so the merchant must choose between retrying and leaving an order unpaid. Stripe's answer is the Idempotency-Key header backed by an atomic insert: concurrent twins get HTTP 409, completed keys replay the cached response body without touching the card network, and a 24-hour TTL bounds the key table. Behind the gateway, an immutable double-entry ledger records every movement as equal debits and credits, so balances are derived projections rather than overwritten columns.
Core Architectural Principles
- Retry arithmetic: dropped-response retries times the success-shadow rate equals the duplicate charges an unprotected API will bill.
- State machine: atomic INSERT ON CONFLICT DO NOTHING claims the key IN_FLIGHT; late twins are rejected 409 until COMPLETED caches the response.
- TTL boundary: retries arriving after 24-hour key expiry can re-execute unless idempotency derives from stable order IDs.
Any payment or mutating-API round demands idempotency: draw the IN_FLIGHT, authorized, COMPLETED sequence and say "HTTP 409 or a distributed lock on concurrent duplicates." Then reject UPDATE balance = balance + 100 in favor of append-only double-entry, and note multi-acquirer failover for availability. Interviewers hear production payments experience in exactly that ordering.
Idempotency storage and append-only ledgers guarantee exactly-once money movement at the cost of distributed-lock throughput and enormous write volume.