Why can you press a lift button five times, but not the "Order" button in a slow food app? Press "5" five times because you're impatient and the lift still goes to floor 5, not floor 25. Press "Order" five times and five plates may turn up.
The lift button is idempotent: its effect is the same whether you run it once or many times. In a distributed system retries are certain, so every important action has to be designed like the lift button.
Why retries can't be avoided
In the Why Distributed Systems Are Hard lesson, order asks payment to charge Budi's card $150 for order #1001, then times out after 2 seconds. A timeout means "unknown": the request may be lost, the response may be lost, or payment may just be slow. A caller that wants the payment to go through has to retry, and as soon as there are retries, the server can receive the same action twice. The design job: make sure the second action adds no effect.
Naturally idempotent or not
Some operations are idempotent by nature:
| Operation | Idempotent? | Why |
|---|---|---|
GET /api/events/42 |
yes | it only reads |
PUT /api/users/7 with the whole profile |
yes | replaces the state with the same value |
DELETE /api/orders/1001 |
yes | deleted twice, still deleted |
UPDATE balance SET amount = 50 |
yes | sets a fixed value |
POST /api/orders |
no | every call creates a new order |
UPDATE balance SET amount = amount + 10 |
no | run twice, it adds 20 |
The HTTP rule: GET, PUT and DELETE are idempotent by the spec; POST and PATCH are not. So retrying a PUT with the same body is safe with nothing extra. What needs protecting is actions like "charge the card", "create the order", "send the e-ticket".
Idempotency key: one action, one key
How: the client creates a unique Idempotency-Key (usually a UUID) once per action, then sends the same key on every attempt. The server stores the key with its result in a dedupe store (Redis or a database table). When the same key arrives again, the server checks its record:
| State of the key in the store | payment answers |
Card charged? |
|---|---|---|
| not there | charge the card, store the result, 201 Created |
yes, once |
| there, finished | send the stored result again (replay) | no |
| there, still processing | 409 Conflict: try again later |
no |
| there, but a different body | 422: the key belongs to another action |
no |
// payment: a dedupe store per Idempotency-Key (example model)
const TTL_HOURS = 24; // a key is remembered for 24 hours
const store = new Map(); // key -> { status, body, response, untilHour }
let charged = 0;
const chargeCard = () => new Promise((ok) => setTimeout(() => ok("ch_" + ++charged), 120));
async function charge(req, hour) {
const body = JSON.stringify(req.body);
const existing = store.get(req.key);
if (existing && hour < existing.untilHour) {
if (existing.body !== body) return { status: 422 }; // the same key for another action
if (existing.status === "processing") return { status: 409 }; // the first attempt is still running
return existing.response; // replay: the card is not charged again
}
const entry = { status: "processing", body, untilHour: hour + TTL_HOURS };
store.set(req.key, entry); // claim the key BEFORE charging the card
entry.response = { status: 201, charge: await chargeCard() };
entry.status = "done";
return entry.response;
}
async function main() {
const req = { key: "ord-1001", body: { orderId: 1001, amount: 150 } };
const [a, b] = await Promise.all([charge(req, 0), charge(req, 0)]); // a double click
console.log(a.status, a.charge, "|", b.status); // 201 ch_1 | 409
const c = await charge(req, 1); // a retry one hour later
console.log(c.status, c.charge); // 201 ch_1 (replay)
const d = await charge(req, 26); // a retry 26 hours later
console.log(d.status, d.charge, "| charged:", charged); // 201 ch_2 | charged: 2
}
main();
store.get(req.key)is checked before charging the card. Swap the order and the card is already charged by the time you learn it's a duplicate.store.set(req.key, entry)with status"processing"claims the key before the work starts. That's why a second click arriving while the card is being charged gets409, not a second charge.return existing.responsereturns the very same result object (ch_1). The client can't tell a replay from the original answer, and doesn't need to.untilHouris the key's age limit. Past it, the key counts as new.chargedcounts the charges.
In real Redis, claiming the key must be atomic (one command that checks and stores at once), for example SET idem:ord-1001 processing NX EX 86400. NX means "store only if it isn't there yet", so two servers claiming at the same moment can't both win. The details of the HTTP header are in the Idempotency lesson (API track).
At-least-once: a message that arrives twice
The message queue in the Message Queue lesson guarantees at-least-once delivery: every message arrives, but maybe more than once. The e-ticket worker sends the e-ticket for order #1001, then dies before it can ack (tell the queue "done"). After the 10-second visibility timeout, the queue sends that message again to another worker, and Budi gets two e-tickets.
Three delivery guarantees worth knowing:
- At-most-once: delivered at most once. Never doubled, but it can be lost.
- At-least-once: never lost, but it can be doubled. This is what most queues use (SQS, RabbitMQ).
- Exactly-once: in practice reached with at-least-once plus an idempotent consumer.
An idempotent consumer stores the IDs of messages it has processed: SET processed:msg-1001 1 NX EX 86400 in Redis (in older versions, the SETNX command plus a TTL). An OK reply means a new message, do the work; an empty reply means it's been seen, skip it and just ack. This is safer than "check the database first, then insert": two workers can both see "not there" between the check and the insert. One catch: if the worker dies after the SET but before the work is done, the next delivery is skipped too, so for expensive work store a processing and done status like payment's dedupe store.
TTL: how long a key is remembered
Keys aren't kept forever. The TTL (time to live) is a key's lifetime in the store. Stripe, for example, keeps keys for at least 24 hours. At TicketTune: 50,000 orders a day × about 1 KB per record = 50 MB for 24 hours, cheap.
Take the last line of the code's output. Key ord-1001 is stored at hour 0 and forgotten at hour 24. Budi's phone is offline overnight, and its retry arrives at hour 26, when the key is gone, so payment treats it as a new payment. Budi's card is charged 2 times.
- TTL too short: a legitimate retry arrives after the key is forgotten, and the action happens twice.
- TTL too long: the store fills with old keys that will never be retried.
Pick a TTL longer than your client's longest retry gap.
Polite retries: backoff and jitter
Retry only errors that may heal on their own: network errors, 408, 429, 500, 502, 503, 504. Don't retry 400, 401, 403, 404 or 422: send them as often as you like, the answer stays the same. Use growing pauses (exponential backoff: 1, 2, 4 seconds) with randomness inside them (jitter: a random pause between 0 and the limit), so thousands of clients that failed together don't storm the server in the very same second it recovers.
Redesign so it's naturally idempotent
Sometimes it's cleaner to change the shape of the action than to bolt on a key. The "like" button on the concert page: POST /api/events/42/likes/increment isn't idempotent, two clicks = two likes. Change it to record who likes it: POST /api/events/42/likes with { userId: 7 }, stored as a unique (concert, user) pair, and let the server count the total. However many times it's clicked, Budi is recorded once. Same for a cart: PUT /cart/items/7 { quantity: 3 } is safer than "add 1".
⚠️ Why does the card still get charged twice?
- A new key on every retry. The key must be created once per action and reused. A fresh UUID per attempt is the same as no key.
- The key is created on the server. The client doesn't know it, so it can't send the same key when it retries.
- Check then work, with no atomic claim. Two requests arriving together both see "not there", then both charge the card.
- Only disabling the button in the frontend. It helps, but automatic retries, a second tab and manual requests still get through. The protection must be on the server.
- Forgetting external services. If
paymentcalls a payment gateway, pass the key on to it too, or one retry insidepaymentcan charge the card twice.
TL;DR: Idempotent means running it many times has the same effect as once. GET, PUT and DELETE are idempotent by the spec; POST and PATCH aren't, so actions like paying and ordering need an Idempotency-Key: created by the client once per action (a UUID), sent unchanged on every retry. The server keeps the key and its result in a dedupe store: a new key is processed, a finished key is answered with the stored result (replay), a key still being processed gets 409. Claiming the key must be atomic (SET ... NX). Queues give at-least-once delivery, so consumers must be idempotent too: store the message ID with SET NX plus a TTL, and skip what has been seen. The TTL is a trade-off: too short and a legitimate retry is processed twice (a 24-hour key, a retry at hour 26, the card charged twice), too long and the store fills up. Retry only errors that can heal, with backoff and jitter. When you can, redesign the action so it's naturally idempotent.
⚡ Idempotent: the effect stays the same
Guess first: which one is safe to run twice, UPDATE balance SET amount = 50 or UPDATE balance SET amount = amount + 10?
The first. It sets a fixed value. The second, run twice, adds 20.
Meaning: GET, PUT and DELETE are idempotent by the HTTP spec; POST and PATCH are not. So PUT /api/users/7 with the whole profile is safe to retry with nothing extra.
⚡ One action, one key
Meaning: The client creates an Idempotency-Key once per action, then sends the same key on every attempt. The server stores the key with its result: a new key is processed, a finished key is answered with the stored result (replay), a key still being processed gets 409.
⚡ Claim the key before charging the card
Write:
const entry = { status: "processing", body, untilHour: hour + TTL_HOURS };
store.set(req.key, entry); // claim the key BEFORE charging the card
Meaning: A second click arriving while the card is being charged gets 409, not a second charge. In Redis, the claim must be atomic: SET idem:ord-1001 processing NX EX 86400.
⚡ A TTL longer than the longest retry
Meaning: Key ord-1001 is remembered for 24 hours. The retry from Budi's phone, offline overnight, arrives at hour 26, when the key is forgotten, so his card is charged 2 times. Pick a TTL longer than your client's longest retry gap.