Idempotency: the same payment, sent twice
Networks lose things, so clients retry. A retry that charges the card again is the bug. Watch one ฿990 payment meet four troubles and see which design charges exactly once.
What you'll take away
- Explain how a lost answer plus a retry charges twice, and why never retrying fails too
- Use one idempotency key per payment, so a retry gets the stored answer back
- Claim the key with one
INSERTinto a unique column, so two taps at once charge once - Make a worker skip a redelivered message by noting its id in the same transaction
The 1-minute version
Tap a point and the picture below plays that step.
Try every trouble with every design and find the one that charges once every time. PUT is off for the queue: a message isn't an HTTP request
The app sends POST /payments and times out. It can't tell whether the server charged already. How do you retry without a second charge?
The picture: a ฿990 payment travels from the phone (or a message on the queue) to the server and on to the ledger. Each light on a street is a message; one that stops half-way in red never arrived, and each street keeps the last message written beside it. Every ฿990 slab on the ledger's roof is a time the customer was charged.
Compare them all: Idempotency
One ฿990 payment meets four troubles in a row: a lost request, a lost response, a double tap and a redelivery. Count the charges for each design; right is ×1 in every row.
Use it when Work that may be lost, like usage stats
Skip it when Money, orders, anything a customer waits on
A model: the counts come from each tile's sequence diagram, not a real system. The designs themselves are really run in the code below. Press any tile to see it large above, with when it fits.
Delivery is at most once or at least once
| Design | Gives you | Goes wrong when |
|---|---|---|
| no retries | at most once | anything is lost: a sale, or a charge the app calls a failure |
| retries, no key | at least once | a response is lost, or two taps: charged twice |
| key, check then save | once, one at a time | two arrive together, or a crash between work and note |
| key claimed in one step | effectively once | keys are dropped while clients still retry |
Exactly-once is something you build
When an answer is lost, the sender can't know whether the other side got the message, so it either gives up (maybe lost) or sends again (maybe twice). What's sold as exactly-once is at-least-once delivery plus processing that does the same thing when it sees the same message again.
Set, don't add
PUT and DELETE are idempotent in HTTP: twice has the same effect as once. Where you can, make the work a set (status = paid) instead of an add (balance + 990). Where you can't, a key the client makes once per action, sent with every retry, does the job.
In real code
// A payment API that takes an Idempotency-Key, on a real node:http server. The client makes one key per payment and
// sends it with every retry; the server keeps the key with its answer. Here one response is dropped on purpose (the
// server closes the connection after the work, as a lost packet would), and the client retries.
// In one process, setting the key before the first await is the claim; with several servers it's a unique insert in
// the database (claim.sqlite.sql). Run: node server.ts (Node 23.6+; on Node 22: node --experimental-strip-types server.ts)
import assert from "node:assert/strict";
import { createHash, randomUUID } from "node:crypto";
import { createServer, request } from "node:http";
import type { AddressInfo } from "node:net";
type Kept = { hash: string } & ({ state: "running" } | { state: "done"; code: number; body: string });
const ledger: { payment: string; amount: number }[] = [];
const keys = new Map<string, Kept>();
let dropNext = false; // the test's stand-in for a network that loses one response
const sha = (s: string) => createHash("sha256").update(s).digest("hex");
const charge = async (amount: number) => { await new Promise((r) => setTimeout(r, 30)); const payment = `p_${ledger.length + 1}`; ledger.push({ payment, amount }); return payment; };
const server = createServer((req, res) => {
let raw = "";
req.on("data", (c) => (raw += c));
req.on("end", async () => {
const send = (code: number, body: string) => {
if (dropNext) { dropNext = false; req.socket.destroy(); return; } // the work is done, the answer never arrives
res.writeHead(code, { "content-type": "application/json" }).end(body);
};
const key = req.headers["idempotency-key"], hash = sha(raw);
if (typeof key === "string") {
const kept = keys.get(key);
if (kept && kept.hash !== hash) return send(422, `{"error":"this key was used for another request"}`);
if (kept?.state === "running") return send(409, `{"error":"the first request with this key is still running"}`);
if (kept?.state === "done") return send(kept.code, kept.body); // the stored answer, no second charge
keys.set(key, { hash, state: "running" }); // claimed before any await
}
const payment = await charge(JSON.parse(raw).amount);
const body = JSON.stringify({ payment });
if (typeof key === "string") keys.set(key, { hash, state: "done", code: 201, body });
send(201, body);
});
});
await new Promise<void>((r) => server.listen(0, "127.0.0.1", r));
const port = (server.address() as AddressInfo).port;
function post(amount: number, key?: string): Promise<{ code: number; body: string }> {
return new Promise((ok, fail) => {
const r = request({ host: "127.0.0.1", port, path: "/payments", method: "POST", headers: { "content-type": "application/json", ...(key ? { "idempotency-key": key } : {}) } }, (res) => {
let b = ""; res.on("data", (c) => (b += c)); res.on("end", () => ok({ code: res.statusCode ?? 0, body: b }));
});
r.on("error", fail);
r.end(JSON.stringify({ amount }));
});
}
/** Retry on a lost answer or a 409, a little later each time, with the SAME key. */
async function pay(amount: number, key?: string) {
for (let i = 0; ; i++) {
try { const r = await post(amount, key); if (r.code !== 409) return r; } catch { /* no answer: try again */ }
if (i === 4) throw new Error("gave up");
await new Promise((r) => setTimeout(r, 20 * 2 ** i));
}
}
dropNext = true;
await pay(990); // no key: the retry looks like a new payment
const withoutKey = ledger.length;
ledger.length = 0; dropNext = true;
const k1 = randomUUID();
const retried = await pay(990, k1);
const withKey = ledger.length;
ledger.length = 0;
const k2 = randomUUID();
const firstTry = await Promise.allSettled([post(990, k2), post(990, k2)]); // two taps, same key, same moment
const codes = firstTry.map((x) => (x.status === "fulfilled" ? x.value.code : 0)).sort();
const after = await pay(990, k2); // the 409 one comes back later
const twoAtOnce = ledger.length;
const otherAmount = await post(1990, k2);
server.close();
assert.equal(withoutKey, 2);
assert.equal(withKey, 1);
assert.equal(retried.code, 201);
assert.deepEqual(codes, [201, 409]);
assert.equal(twoAtOnce, 1);
assert.equal(JSON.parse(after.body).payment, "p_1");
assert.equal(otherAmount.code, 422);
console.log(`response lost, no key: charged ${withoutKey} · with a key: charged ${withKey}, the retry got the stored 201 · two at once: ${codes.join(" + ")}, charged ${twoAtOnce} · same key, other amount: ${otherAmount.code}`);
node server.ts (Node 23.6+ · on Node 22 add --experimental-strip-types)It printed: response lost, no key: charged 2 · with a key: charged 1, the retry got the stored 201 · two at once: 201 + 409, charged 1 · same key, other amount: 422A real node:http server and client. One response is dropped on purpose; without a key the retry charges again, with one it gets the stored 201. Two requests with the same key at once: one 201, one 409. The same key with another amount: 422. Really run; below is what it printed.
Common questions
What does idempotent mean?
Doing it twice has the same effect as doing it once. Setting status = paid again is still paid; adding 990 to a balance twice adds twice. In HTTP, GET, PUT and DELETE are meant to be idempotent; POST isn't.
Why not stop retrying altogether?
A request lost on the way loses the sale, and worse, a charge whose answer is lost shows the customer a failure. Networks fail sometimes, so you have to retry. The job is making the retry safe.
How does an idempotency key work?
The client makes one random key per action, not per attempt, and sends the same key with every retry, for example in an Idempotency-Key header as Stripe's API does. The server stores the key with its answer, and the same key gets the same answer without the work running again.
Isn't checking for the key, then saving it, enough?
Not when two requests with the same key arrive milliseconds apart: both ask, both hear no, both charge. Claim the key first, in one step, with an INSERT into a table with a unique constraint, and the database lets only one through.
What should the second request get while the first is still running?
A 409 (Conflict) telling it to come back later. Once the first finishes, a retry gets the stored answer. What it must never do is run the work a second time.
Is exactly-once delivery real?
Not over a network that can lose messages: a sender that hears nothing must give up (maybe lost) or send again (maybe twice). What you can build is an effect that happens once: at-least-once delivery, and a receiver that skips what it has already done.
How does a queue worker skip a message it already handled?
Write the message id into a processed table, unique on that id, in the same transaction as the work. If the worker crashed before its ack and the queue delivers the message again, it hits that key and is skipped.
How long should the server keep idempotency keys?
At least as long as any client may still retry. Drop a key too soon and a late retry looks brand new and runs again. Stripe keeps them for at least 24 hours.
Next lesson
Circuit breakers, retries and timeoutsLevel: Deep
Now a repeat is safe; next, when and how to retry, with backoff and jitter, and when to stop calling.