Idempotency keys: how to make retries safe
A client sends POST /charges. The server charges the card. The response is lost on the way back, so the client sees a timeout. What should it do?
If it doesn’t retry, the customer may have paid for nothing. If it does retry, the customer may pay twice. Both are bad, and you can’t tell which situation you’re in from the client side. That is the core problem of every network call that changes something.
The fix is not “make the network reliable”. It’s making the retry safe.
The bug
Here is a naive handler, and a client that retries once after a timeout:
type Charge = { id: string; amount: number };
const charges: Charge[] = [];
let nextId = 1;
function createCharge(amount: number): Charge {
const charge = { id: `ch_${nextId++}`, amount };
charges.push(charge);
return charge;
}
createCharge(500); // first attempt: succeeded, but the response was lost
createCharge(500); // retry
charges.reduce((sum, c) => sum + c.amount, 0); // 1000
The customer asked to pay 500 and was charged 1000. The server did exactly what it was told, twice.
The pattern
The client generates a unique idempotency key (a random UUID is fine) for each intended operation and sends it with every attempt, including retries:
POST /charges
Idempotency-Key: 7b1e2c9a-3f44-4d0b-9a55-1c3a7e0d92aa
Content-Type: application/json
{"amount": 500}
The server remembers the key and the result. If it sees the same key again, it returns the stored result instead of doing the work again. One intention, one effect, however many attempts.
“Idempotent” means that doing something many times has the same effect as doing it once. PUT /users/7 with the same body is naturally idempotent. POST /charges is not, so we add the key to make it so.
A working version
type Entry =
| { state: "running"; fingerprint: string; promise: Promise<Charge> }
| { state: "done"; fingerprint: string; result: Charge };
const store = new Map<string, Entry>();
async function createCharge(key: string, body: { amount: number }): Promise<Charge> {
const fingerprint = JSON.stringify(body);
const seen = store.get(key);
if (seen) {
if (seen.fingerprint !== fingerprint) {
throw new Error("409: key reused with a different request");
}
return seen.state === "done" ? seen.result : seen.promise;
}
const promise = doCharge(body.amount); // the real work
store.set(key, { state: "running", fingerprint, promise });
try {
const result = await promise;
store.set(key, { state: "done", fingerprint, result });
return result;
} catch (error) {
store.delete(key); // failed: allow a clean retry
throw error;
}
}
Run three identical requests at the same moment and you get one charge and three identical answers (ch_1, ch_1, ch_1). Send the same key again later, same answer, no new charge.
Three details in that code are the difference between a demo and something you can trust.
Edge case 1: two requests at once
A retry can arrive while the first attempt is still running. If you only store results after the work finishes, both requests find an empty store and both do the work. That’s why the entry has a running state: the second request waits on the first one’s promise instead of starting its own.
In a real system the store is a database, not a Map. Then the guard is a unique constraint on the key: insert the row first, and whichever request fails to insert knows it is the duplicate. The database does the locking for you.
Edge case 2: same key, different request
If a client reuses a key with a different body (amount: 900 instead of 500), something is wrong with the client. Don’t silently return the old result and don’t run the new request. Compare a fingerprint of the request and return an error (409 or 422). It turns a quiet bug into a loud one.
Edge case 3: failures
If the work fails, should the key be remembered? It depends on the kind of failure.
- The request was rejected before any effect (validation error, card declined): safe to store the failure and replay it, or to forget it. Pick one and document it.
- It crashed halfway: you don’t know what happened. Forgetting the key and redoing the work is only safe if the work itself can be retried, for example by passing the same key down to the payment provider.
That last point is the quiet rule of this pattern: idempotency has to hold all the way down. If your handler calls another service that charges money, give it a key derived from yours.
How long to keep keys
Long enough to cover every realistic retry, short enough to bound storage. 24 hours is a common choice. Say it in your docs so clients know the guarantee has an end.
When you don’t need it
- Reads.
GETis already safe to repeat. - Naturally idempotent writes. “Set the status to shipped” gives the same state however many times it runs. “Add one to the counter” doesn’t.
- Work you can check afterwards. Sometimes it is simpler to let the client look up whether the thing exists before retrying.
The checklist
- Client creates one key per intended operation, and reuses it on every retry.
- Server inserts the key before doing the work, guarded by a unique constraint.
- Concurrent duplicates wait for the first and share its result.
- A different body under the same key is rejected.
- Keys expire after a documented window.
- Downstream calls get derived keys.
Get those six right and retries stop being scary. You can then retry aggressively, which is what makes the rest of a distributed system resilient.
Build this instead of just reading it
Paren's How Services Talk course lets you predict what happens when a response is lost on a simulated network, then write the fix. API Design has a lesson on idempotency keys too.
Start free