Skip to content
Lesson 51

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.

A timeout is an unknown outcome
Guest's phone
StayHub server
Payment provider
Pay €360
charge the card
charged ✓
paid ✓ (lost in the tunnel)
10 s later: retry Pay €360
charge the card again
The card was charged; only the answer was lost in the tunnel. After 10 seconds the app knows one thing: it stopped waiting. It doesn't know whether the payment worked.

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.

Set or add: is it safe to repeat?
ActionSafe to repeat?How to make retries safe
Read a hotel pageYesRetry freely
Set check-out to 16 NovemberYes: it describes the end stateRetry freely
Cancel booking 8812 (set status)YesRetry freely; a second try may answer "already cancelled"
Charge €360No: each call moves moneyOne idempotency key per intent
Add one nightNo: each call adds againRewrite as a set ("check-out = 17 Nov"), or use a key
Send a confirmation emailNo: each call sends againRemember which emails were sent, by booking
Prefer a set over an add where you can: retries are then harmless with no extra machinery. Where you can't, like a charge, give each intent a key.

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.

What the server answers, by key
A key the server has never seen
Do the work, then store the answer
201
A key already done
Send back the stored answer; charge nothing
201 (replayed)
A key still running
Ask the app to try again in a moment
409
The same key with a different amount
Refuse it: the app reused a key, which is a bug
422
The dedupe table stores each key with a fingerprint of the request and the answer it gave. Every repeat gets a clear answer, and money moves only for the first.

Two 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.

One checkout, one key
App
StayHub server
Dedupe table
Provider
Pay · key 7c1e…
claim 7c1e… ✓
charge · key pay-7c1e…
save payment + answer (one transaction)
retry · same key 7c1e…
already done → stored answer
paid ✓ (no new charge)
The app creates the key when the guest taps Pay and saves it with the cart. Every attempt carries it. The server claims it once, passes it down to the provider, and answers every repeat from its table: four attempts, one charge.

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.

Two taps, 40 ms apart
Check, then act (the first version)
  1. A looks up 7c1e…: not found
  2. B looks up 7c1e…, 40 ms later: not found
  3. A charges €360 (800 ms)
  4. B charges €360
  5. A and B save the key
Two charges
Claim first (the fix)
  1. A inserts 7c1e…: accepted
  2. B inserts 7c1e…: refused, the key exists
  3. A charges €360 with pay-7c1e…
  4. B gets 409, then the stored answer
  5. A saves payment + answer together
One charge
A lookup takes no lock, so both requests can see "never seen". A unique key in the database lets exactly one insert succeed; only the winner touches the card.

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 answered
  1. 1What does it mean for an action to be idempotent?

  2. 2The app sent Pay, waited 10 seconds and got no answer. What does it actually know?

  3. 3Which action is safe to repeat on its own, with no key?

  4. 4Where should the idempotency key for "pay for this cart" be created?

  5. 5A retry arrives with a key the server has already completed. What should the guest's app get back?

  6. 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?

  7. 7A request arrives with a key the server already knows, but for a different amount. What should happen?

  8. 8Karim wants to refuse any two bookings with the same guest, hotel and dates, live in an hour. What is the main cost?

  9. 9The server charged the card, then crashed before saving anything. The app retries with the same key. What stops a second charge?

  10. 10Claude Code proposes switching off the app's automatic retries to stop the double charges. Why say no?

Free account

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 account
Founding members

Every 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

Questions from the community

All questions →