Idempotency and retries
Retries will happen, so make them safe. Learn what makes an action safe to repeat, and how one key per intent turns three attempts into exactly one charge.
The lesson in text
Click a paragraph to hear it.01Charged twice in a tunnel
Saturday, 18:40. Maya, StayHub's product manager, forwards a screenshot of a guest's bank statement. Two lines, a few seconds apart. €360. €360.
That guest is not alone. Since Thursday's app release, 212 guests have been charged twice for one booking. One tap on Pay, two charges.
Omar, the engineer on call, finds the change. The new app, version 5.2, retries a payment by itself when it gets no answer within 10 seconds. Up to three times. Exactly as it was designed to.
So should you just switch the retries off? In this lesson, you'll learn why retries can't be avoided, what makes an action safe to repeat, and how one small reference number turns several attempts into exactly one charge.
02Why the app retries
Picture the guest. She's on a train, she taps Pay, and her phone sends the request. StayHub's server charges her card with the payment provider, and the answer starts back towards her phone.
Then the train enters a tunnel. The answer never arrives. After ten seconds, the app stops waiting. From where the phone sits, there's no way to tell whether the payment worked.
That's the key fact about networks: a timeout means you stopped waiting, not that it failed. The other side may have finished the job. You met this unknown outcome when we looked at partial failures.
So the app retries, and here's the catch. The retry is a brand-new request. Nothing in it says: this is the same payment as before. The server sees a new payment, and charges again.
Switching retries off doesn't help. Every tunnel becomes a lost booking, and guests simply tap Pay again by hand: the same retry, with no protection. Retries come from people, phones, proxies, queues and webhooks. You can't make them rare. You make them safe.
03The cheque number
Think of paying your rent by cheque. You post it, and hear nothing for a week. Did it arrive? You can't tell. So you send a copy.
If the copy carries the same cheque number, the bank checks its book of numbers it has already cashed, finds number 1042, and ignores the copy. You pay once.
But if you write a new cheque, with a new number, the bank has no way to know it's the same rent. It cashes both. That's exactly what StayHub's server did on Thursday.
The word for the safe case is idempotent: an action is idempotent when doing it twice has the same effect as doing it once. Cashing cheque 1042 is idempotent, because the bank remembers. Cashing any cheque that arrives is not.
04Set, or add?
Some actions are safe to repeat all by themselves. Reading a hotel page is: read it ten times, and nothing changes. So is a set, like: set my check-out date to the sixteenth of November. Do it twice, and the date is still the sixteenth.
Other actions add something every time. Charge three hundred and sixty euros. Add one night. Send a confirmation email. Each repeat adds again: a second charge, an extra night, a second email.
So the first question for any action is: can it be written as a set? Where it can, retries are already harmless. Where it can't, like charging a card, it needs what the cheque has: a number the other side can recognise.
| Action | Safe to repeat? | How to make retries safe |
|---|---|---|
| Read a hotel page | Yes | Retry freely |
| Set check-out to 16 November | Yes: it describes the end state | Retry freely |
| Cancel booking 8812 (set status) | Yes | Retry freely; a second try may answer "already cancelled" |
| Charge €360 | No: each call moves money | One idempotency key per intent |
| Add one night | No: each call adds again | Rewrite as a set ("check-out = 17 Nov"), or use a key |
| Send a confirmation email | No: each call sends again | Remember which emails were sent, by booking |
05One key per checkout
That number is called an idempotency key: a unique id for one intent, like "pay for this cart". It's created once, and sent with every attempt.
Where it's born matters most. StayHub's server already sent the payment provider a reference. But it made a new one for every request it received, so the retry got a new reference too. A new cheque, with a new number.
The intent is born on the phone, when the guest taps Pay. So the app creates the key right there, and saves it with the cart. If she closes the app, opens it again and taps Pay, the same key goes with her.
On the server, a dedupe table keeps every key it has handled, with the answer it gave. It's the bank's book of cashed cheque numbers.
Now every request gets a clear answer. A new key: do the work. A key that's already done: send back the stored answer, and charge nothing. A key that's still running: 409, try again in a moment. The same key with a different amount: 422, refused, because that's a bug in the app.
201201 (replayed)409422Two more rules. The server passes the key down to the payment provider, as "pay-" followed by the key, so the provider recognises a repeat too. And it saves the payment and the stored answer together, in one transaction, so a crash can't leave one without the other.
StayHub keeps keys for 24 hours, then deletes them. Stripe, a large payment provider, documents the same design: the client sends an idempotency key, a repeat gets the first answer back, and keys can be removed once they're a day old.
Put it together, and you get the deal that makes networks bearable. The app sends at least once. The server handles repeats safely. The guest pays exactly once.
06Check, then act
The fix ships on Monday. By Wednesday, Omar still counts about three double charges a day. Every one is a double tap: the same key, two requests forty milliseconds apart.
Here's how the first version worked. Look up the key. If it isn't there, charge the card. Then save the key. Read it again, slowly, with two requests in mind.
The charge takes 800 milliseconds, and the key is only saved after it. So for 800 milliseconds, the table says: never seen. Both requests look, both find nothing, and both charge.
Back at the bank. Two clerks get the same cheque at the same moment. Both check the book, both see no 1042, and both cash it. The fix: write the number in the book first, and only the clerk who wrote it gets to cash it.
In the database, that's one rule: each key can be stored only once. Every request starts by trying to insert its key. The database lets exactly one insert succeed. The winner charges the card. The loser gets the stored answer, or a 409.
- A looks up 7c1e…: not found
- B looks up 7c1e…, 40 ms later: not found
- A charges €360 (800 ms)
- B charges €360
- A and B save the key
- A inserts 7c1e…: accepted
- B inserts 7c1e…: refused, the key exists
- A charges €360 with pay-7c1e…
- B gets 409, then the stored answer
- A saves payment + answer together
Check, then act, is a race whenever two requests can arrive together. Claim first. Act only if you won.
07Tonight's decision
Back to Saturday night, in the war room. Karim, the CTO, wants the double charges stopped tonight. But keys need a new app release, and the app stores take days to approve one.
His idea: refuse two bookings with the same guest, the same hotel and the same dates. One rule in the database, live in an hour.
Lina, the senior engineer, points at the cost. About 300 times a day, a guest books a second room for the same nights, for parents or for kids. Karim's rule would block every one. It guesses the intent from the data, instead of naming it.
Her plan: keys on the server tonight, for the website, and the app release as fast as the stores allow. The team keeps Karim's rule only as a stopgap, with a removal date written down. The real fix is the key.
08Your job as lead
Now you ask Claude Code to make payments safe to retry. It writes a handler that looks up the key, charges the card, then saves the key, and replays the stored answer for repeats. It looks right.
It's Wednesday's race. Reject it, and ask for three things. Claim the key first, with a unique key in the database. Pass the key down to the provider. Save the answer in the same transaction as the payment.
Then ask your questions. Where is the key born, and does it survive an app restart? What's the first database call in the handler? And what does a repeat get back: the stored answer, a 409, or a 422?
And ask for the test that would have caught it: two identical requests, forty milliseconds apart, and exactly one charge in the provider's test dashboard.
Let's recap. A timeout means you stopped waiting, not that it failed, so retries will happen. An action is idempotent when doing it twice equals doing it once. Prefer a set over an add. Where you can't, give each intent one key, born where the intent is born, and let the database pick one winner. Next: what happens when a service doesn't fail, but just gets slow.
Check yourself
0/10 answered1What does it mean for an action to be idempotent?
2The app sent Pay, waited 10 seconds and got no answer. What does it actually know?
3Which action is safe to repeat on its own, with no key?
4Where should the idempotency key for "pay for this cart" be created?
5A retry arrives with a key the server has already completed. What should the guest's app get back?
6Claude Code's handler looks up the key, charges the card if the key isn't there, then saves the key. Two taps arrive 40 ms apart. What do you do?
7A request arrives with a key the server already knows, but for a different amount. What should happen?
8Karim wants to refuse any two bookings with the same guest, hotel and dates, live in an hour. What is the main cost?
9The server charged the card, then crashed before saving anything. The app retries with the same key. What stops a second charge?
10Claude Code proposes switching off the app's automatic retries to stop the double charges. Why say no?
Save your progress — create a free account
Free. No card. Your finished lessons follow you to any device, and you can ask questions in the community.
Create my free accountEvery lesson is free while we build. Lock in €9/month for later.
The first 100 members keep the founding price for as long as they stay. Reserving is free: no card, nothing is charged.
See the founding offer