IDEMPOTENCY & EXACTLY-ONCE
At-least-once delivery plus an idempotent handler is as good as it gets
The client sends an idempotency key, one id per checkout that it reuses on every retry. The server looks up the key, charges the card, then records the key. It crashes right after the charge. The client retries with the same key. What happens?
A timeout tells the client nothing. The request may never have arrived, or the server may have charged the card and the response got lost. The client has to retry, so delivery is at-least-once. Exactly-once delivery does not exist; exactly-once effect does.
You get it by making the handler idempotent. The client attaches one key per logical operation and reuses it on every retry. The server stores key → result and answers repeats from the store. The catch: the check and the record must not leave a window where a crash or a duplicate sees no key.
// handler
function charge(req) {
const result = card.charge(req.amount); // side effect
return result; // response lost -> client retries -> charged again
}// handler with an idempotency key
function charge(req) {
const r = store.reserve(req.id); // atomic insert-if-absent
if (r === 'pending') return 409; // another worker is on it
if (r !== 'claimed') return r; // replay: stored result, no side effect
return store.txn(() => {
const result = ledger.charge(req); // side effect ...
store.commit(req.id, result); // ... and the key, in one commit
return result;
});
} The invariant strip tracks each request id is applied at most once. NAIVE RETRY breaks it on the second charge. IDEMPOTENCY KEY holds for a lost response, then CRASH BETWEEN CHARGE AND RECORD breaks it again. RESERVE, THEN ONE TRANSACTION survives the same crash and the same retry.
Note the switch in that last scenario: the charge becomes a ledger row in your own database, so it can share a transaction with the key. A charge on a card network cannot sit inside your transaction. For that, pass the key downstream so the payment provider deduplicates too, or record the intent locally and send it from an outbox (see the last card). One more simplification: the sim lets a retry reclaim a pending key the moment its owner crashes. A real server cannot see that crash, so it puts a timeout or lease on the reservation, and a slow owner that outlives it is the leases-and-fencing problem again.
The key store is deployed and the retry is served from it. Inject a duplicate delivery of r1 (or a crash) at a point where it still charges the card twice.
GOAL: r1 is charged more than once
Make handle charge each request id exactly once. The grader replays a request after success, crashes the server at every point and retries, and delivers a duplicate to a second worker, trying every interleaving of the two. Each worker gets its own transaction; a reserve of a key that another open transaction has written waits for that transaction to finish, as a unique index would.
Payment APIs (an Idempotency-Key header), message consumers that dedupe by message id, Kafka's idempotent producer, webhook receivers, and any job queue with retries. The symptom: duplicate orders, double charges or double emails after a timeout or a redeploy.
“How do you make a payment endpoint safe to retry?” Say that the client generates the key, the server reserves it with insert-if-absent before the side effect, stores the result in the same transaction, returns the stored result on a repeat and a 409 while a first attempt is in flight, and that external side effects go through an outbox that passes the key downstream.
USED IN
Chapters that build on this lesson.
- Guardrails, injection and abuse casesAI Engineer
- Distributed transactions: 2PC, Percolator, and Spanner's clockDatabases
- Failover, split brain and fencingDatabases
- Hiring and interviewingEngineering Manager
- Technical decisions as a managerEngineering Manager
- Architecture governance and platform investmentHead of Engineering
- Contractors, outsourcing and vendorsHead of Engineering
- USSD and mobile money, seen from the networkHow Mobile Networks Work
- Leading a network outageNetwork Engineer
- AI in payments today: fraud scores, smart routing and support botsPayments
- Direct debit and mandatesPayments
- Idempotency and moving money exactly oncePayments
- Integrating a payment provider: charges, verification, webhooksPayments
- Payment states, failures, reversals and refundsPayments
- Project: a wallet with funding, transfers, refunds and daily reconciliationPayments
- Routing across providers to raise success ratesPayments
- Transfers and virtual accountsPayments
- When the money is wrong: payments incidentsPayments
- Design in the product trioProduct Designer
- Designing for low connectivity, cheap phones and USSDProduct Designer
- Platform, API and technical PMProduct Manager
- Product analytics: funnels, cohorts and instrumentationProduct Manager
- API, contract and integration testingQA and Quality Engineering
- Bug reports that get fixedQA and Quality Engineering
- Exploratory testing and chartersQA and Quality Engineering
- Mobile and accessibility testingQA and Quality Engineering
- Performance and load testingQA and Quality Engineering
- Release management and sign-offQA and Quality Engineering
- Test strategy and test plansQA and Quality Engineering
- Testing in production and observabilityQA and Quality Engineering
- Testing money and regulated systemsQA and Quality Engineering
- Testing philosophies: pyramid, trophy, exploratory, risk-basedQA and Quality Engineering
- Why quality engineering existsQA and Quality Engineering
- AI and agent securitySecurity
- Threat modellingSecurity
- A design doc for one featureSoftware Engineer
- Breaking down work and estimating it: pieces you can see, ranges you can defendSoftware Engineer
- Code review, giving and receivingSoftware Engineer
- Debugging a problem you have never seenSoftware Engineer
- Engineering philosophies: simple first, ship small, own what you runSoftware Engineer
- On call for what you builtSoftware Engineer
- Technical debt and the trade-offs you defendSoftware Engineer
- Testing your own workSoftware Engineer
- Testing data pipelines and migrationsSoftware Testing and Quality
- AI in operations: agents on call and what they may touchSRE, Platform and DevOps
- Chaos and resilience testingSRE, Platform and DevOps
- Toil and automationSRE, Platform and DevOps
- Architecture reviews and governanceStaff and Principal Engineer
- Cross-team projects and migrationsStaff and Principal Engineer
- The principal and the business: build vs buy, vendors, the frontierStaff and Principal Engineer
- Writing RFCs and design docsStaff and Principal Engineer
- How technical a TPM must beTechnical Program Manager
- Programmes across companies: partner banks, telcos, regulatorsTechnical Program Manager