Skip to content

Design a payment that charges exactly once — through retries and crashes

AdvancedAsked very oftenSystem designDesignArchitecture
Asked atStripeRazorpayPayPal
#payments#idempotency#outbox-pattern#queues#consistency

Company tags are compiled from public interview reports and are signals, not guarantees.

What interviewers are testing

Payment idempotency is the senior-interview litmus test: it compresses concurrency, distributed failure, and data modeling into one problem with a rupee amount attached. Candidates earn the offer by naming the crash window between an external side effect and a local write, putting the invariant in the database instead of a lock, closing dual writes with a transactional outbox, and treating retries and webhook replays as the default weather rather than the exception.

Mental model

Exactly-once delivery does not exist over unreliable networks — exactly-once effects do. Every step is rebuilt as at-least-once plus idempotent: requests carry a key the database can enforce once, state changes and events commit in the same transaction, consumers deduplicate by event id, and a reconciliation job compares your ledger against the provider’s settlement when all else fails. The question is never "will it retry?" but "is it safe when it does?"

Step-by-step solution

  1. Step 1: The double charge: a crash inside the window

    Replay the incident slowly. Request A reaches the provider and the card is charged — a real, external, irreversible side effect. Before the API can write "paid" to PostgreSQL, the process dies. No row exists, so the state is indistinguishable from "nothing happened" — and when the user retries, request B sees an empty database and charges the card again. The deep point is that no database transaction spans the provider: the charge happens in the outside world, your record happens inside yours, and the gap between them is the bug. Watch the animation — the two charges are not caused by a race in your SQL; they are caused by a lost write around an external effect. Any system where a retry can re-trigger the external call without proof of prior execution will double-charge under exactly this sequence.

  2. Step 2: Idempotency keys: the database enforces "once"

    The fix starts with a client-generated key — one per checkout attempt, not per HTTP retry — sent in a header like Idempotency-Key. Retries of the same attempt reuse the same key; a genuinely new attempt gets a new one. The crucial implementation detail: the key becomes a row with a UNIQUE constraint before the provider is called, so only one request in the entire fleet can own the attempt. A concurrent duplicate does not race into a second charge — it loses an INSERT and is answered deterministically: "in progress, try later", or the stored result once the winner finishes. When the charge succeeds, the receipt is stored against the key; every replay returns that receipt without touching the provider. Watch the animation: the app never needs to be clever about "checking" — the database simply refuses the second owner. This is the invariant behavior interviewers want: charge-once is not a promise the code makes, it is a constraint the storage keeps.

  3. Step 3: Redis locks vs database constraints

    The tempting first design is a Redis lock: SET key NX EX 30, first request wins, others wait. It is fast and it demos well — and it is not correctness. A TTL can expire while the holder is paused in a GC cycle or a slow network call, and then two requests hold "the" lock at the exact moment that matters. A failed Redis node forgets the lock entirely; a failover can drop it. Locks are leases with an expiry date, and money cannot be protected by something that expires. The durable version puts the invariant in PostgreSQL: UNIQUE (idempotency_key) survives crashes, restarts, and failovers, and the loser of the race gets a deterministic duplicate-key error your tests can reproduce. The mature answer keeps both: Redis as the fast single-flight optimization to reduce pileups, Postgres as the source of truth that makes one charge unavoidable. Compare the panels — the difference is not speed, it is what happens at the worst possible moment.

  4. Step 4: The transactional outbox: closing the dual-write window

    Even with idempotency keys, the original crash window still exists between the charge and your database write — and a second one opens between the database write and publishing "payment.captured" to the queue. Two systems, one business fact, and no transaction spans both: that is the dual-write problem. The transactional outbox closes it by refusing to do two writes. One PostgreSQL transaction records the payment row and an outbox event together; they commit or roll back as a unit, so the event exists exactly when the state exists. A relay then reads unpublished events, publishes to the queue, and retries until the broker acknowledges — at-least-once delivery, by design. If the API crashes before commit, nothing happened at all; if it crashes after, the committed event still ships. Watch the animation: the payment and its event are born in the same transaction, and the relay only ever moves durable facts. Consumers deduplicate by event id, which upgrades at-least-once delivery into exactly-once effects.

  5. Step 5: Webhooks, reconciliation, and proving it under fire

    The system is not done when the charge path is safe — it is done when the recovery path is boring. Provider webhooks will replay, arrive twice, or land during a deploy, so the endpoint does three things in order: verify the signature, persist the raw event durably, acknowledge, and only then process — idempotently, keyed by event id. Webhooks are also the authority on money movement: your API marks intent, but only the provider's events confirm capture, and a reconciliation job compares your ledger against the provider's settlement report to catch anything that slipped. Then you prove all of it: fire N concurrent identical requests and assert exactly one charge with N identical responses; kill the process between charge and DB write and assert recovery leaves a single charge; run controlled two-transaction interleavings and assert one wins while the other replays. The animation pairs the failure scenarios with the tests that pin each one — the senior signal is not knowing the patterns, it is being able to show they hold when the server dies.

Edge cases & traps

  • Idempotency keys must be scoped to the request payload: reuse of the same key with a different amount or cart is an attack or a bug — store a request hash and reject mismatches with 409.
  • In-flight duplicates need a state machine, not a lock: a second request hitting an in_progress key must get a deterministic "retry later" (or wait on the same row), never a second provider call.
  • The provider webhook is the authority on money: never mark "captured" from your own request path alone — capture, refund, and settlement all reconcile against provider events and reports.
  • Idempotency records cannot live forever or expire too soon: keys must outlive the provider’s retry schedule (typically days), so sweep with a retention window and archive receipts instead of deleting them.
  • Redis locks expire mid-flight under GC pauses, network stalls, or failovers — two holders at the worst moment; any design where correctness depends on the lease surviving is a double charge waiting for load.

Follow-up questions

Go deeper: Explore the System Design visualizer