You press Buy, the loading icon spins for a long time, then the screen says "Connection failed". You press Buy once more. The next day two identical parcels arrive, and you've been charged twice. The first request did reach the server. Only its answer got lost.
What prevents this is called idempotency: the same request can be sent once or many times, and the end result on the server stays the same. It's like paying a cashier when the QR payment app loses its signal while loading. You don't know whether the money left your account. A good cashier writes a receipt number before you pay. When you come back and ask "receipt 0457, did my payment work?", the cashier matches the number and gives you the same receipt instead of charging you again. You are the client, and the cashier is the server. The receipt number is the Idempotency-Key, and the same receipt is the response the server stored. One difference: in an API, the client makes the number itself.
The methods that are idempotent by definition
In the HTTP Methods lesson you met two properties: safe (doesn't change data) and idempotent. According to the HTTP standard:
| Method | Idempotent? | Why |
|---|---|---|
GET, HEAD |
yes | they only read |
PUT |
yes | it replaces the whole thing: twice is still the same |
DELETE |
yes | what's deleted stays deleted (the second answer may be 404) |
POST |
no | every send creates new data |
PATCH |
depends on its body | see the example below |
A PATCH is idempotent when it sets an absolute value (it writes the final number directly), and not when it adds or subtracts:
PATCH /books/1with body{"stock": 11}sent 3 times: the stock stays 11.PATCH /books/1with body{"stock_delta": -1}("subtract one") sent 3 times: the stock goes from 12 to 9. An add-or-subtract command (a relative command) such as+1isn't idempotent. Turn the command into an absolute value, or protect it with an Idempotency-Key.
A retry after a timeout
A client that gets no answer before a timeout can't tell the difference between two cases: "the request never arrived" and "the request arrived, but the answer got lost". For the client, there is only one sensible move: send it again (a retry). For POST /orders, that's dangerous:
| Time | What happens | Orders | The Rainbow Troops stock |
|---|---|---|---|
| 10:20:00 | POST /orders with body {"book_id": 1, "qty": 1} |
501 | 11 |
| 10:20:00 | the server answers 201, the answer gets lost |
501 | 11 |
| 10:20:10 | the client gives up after 10 seconds, then retries | 501, 502 | 10 |
The result is two orders, and the book's price is charged twice for one book. The server did nothing wrong: from the server's side, the second request really is a new order.
Idempotency-Key: a receipt number from the client
The client makes one unique key once per action (one press of Buy) and sends it in the Idempotency-Key header. A retry uses the same key. The key is made with crypto.randomUUID(), which gives a UUID: a long random code that is almost certainly never the same as another one.
const key = crypto.randomUUID(); // once, when the Buy button is pressed
function createOrder() {
return fetch("https://api.bookshop.test/orders", {
method: "POST",
headers: { "Content-Type": "application/json", "Idempotency-Key": key },
body: JSON.stringify({ book_id: 1, qty: 1 }),
});
}
The server records each key, together with a fingerprint of its body (the body written as text, to compare) and its response. The records are kept in a Map, a JavaScript container of key and value pairs:
const saved = new Map(); // key -> { fingerprint, status, body }
app.post("/orders", (req, res) => {
const key = req.headers["idempotency-key"];
const fingerprint = JSON.stringify(req.body);
const hit = key ? saved.get(key) : undefined;
if (hit) {
if (hit.fingerprint !== fingerprint) {
return res.status(422).json({ error: "Idempotency-Key reused with a different body" });
}
res.set("Idempotent-Replayed", "true");
return res.status(hit.status).json(hit.body); // the stored answer, as it was
}
const order = { id: nextId++, book_id: 1, qty: req.body.qty, total: 89000 * req.body.qty };
stock -= req.body.qty;
if (key) saved.set(key, { fingerprint, status: 201, body: order });
res.status(201).json(order);
});
req.headers["idempotency-key"]: Express stores header names in lowercase.- If there is a
hit, this key was processed before. The server replays the stored response:201with the same order 501, plus the headerIdempotent-Replayed: true(Stripe uses this header too). The stock stays 11. - If the
fingerprintdiffers, the same key is used for another body, sayqty: 2. That's the client's mistake, so the request is refused with422. saved.set(...)stores the response once the order is made, so the next retry gets the same answer.
With a key, the table above changes: the retry at 10:20:10 gets 201 with order 501, the stock stays 11, and the price is charged only once.
The status codes here follow the IETF draft standard for the Idempotency-Key header. 422 is for the same key coming with a different body. 409 Conflict is for a retry that arrives while the first request with that key is still being processed (say the button was double-clicked). To be able to answer 409, the server marks the key "in progress" before it starts working. Many payment APIs require this key, and answer 400 when the header is missing.
The core is just a Map
Without Express, the logic is simple. If the key is recorded, return the stored response. If not, make the response, store it, then return it.
function createOrderHandler() {
const store = new Map();
return {
order(key, qty) {
if (store.has(key)) {
return { ...store.get(key), replayed: true }; // a copy, the stored one stays as it is
}
const response = { id: "ord_" + store.size, qty, replayed: false };
store.set(key, response);
return response;
},
};
}
const h = createOrderHandler();
h.order("k1", 1); // { id: "ord_0", qty: 1, replayed: false }
h.order("k1", 1); // { id: "ord_0", qty: 1, replayed: true }
h.order("k2", 2); // { id: "ord_1", qty: 2, replayed: false }
"ord_" + store.sizeis computed beforestore.set: an empty Map meansord_0, a Map with one entry meansord_1.{ ...store.get(key), replayed: true }makes a new object. If you writestore.get(key).replayed = true,replayedin the first response turnstrueas well.- This mini version doesn't compare bodies yet. A real server compares them, and answers
422when they differ. - A Map is lost when the server restarts, and it is not shared between servers. So a real server stores the pair
(user_id, key)in a database table with a UNIQUE index (no two rows may be the same), so the keys of two users never clash.
How long a key is kept
If keys are kept forever, the storage keeps growing. Stripe, for example, may remove keys once they're more than 24 hours old. So a retry two days later with the same key can count as a new action. A client that was offline for a long time should check first before resending, for example with GET /orders?status=pending.
⚠️ Keys made wrong, answers stored wrong
- Making a new key on every retry.
crypto.randomUUID()inside the retry loop makes the server treat each attempt as a new action, so the order is still doubled. Make the key once per click. - Reusing a key for another action. Order 501's key used to buy
qty: 2: refused with422. A new action, a new key. - Changing the stored response. Mark a replay on a copy (
{ ...saved, replayed: true }), not on the original object. - Thinking every method needs a key.
PUTandDELETEare already idempotent. The ones that need a key:POST, and aPATCHthat adds or subtracts.
TL;DR: Idempotent means that sending a request many times leaves the same end result on the server. GET, PUT and DELETE are idempotent by definition. POST isn't, and neither is a PATCH that adds (+1). A client that times out will send the request again (retry), so an unprotected POST /orders makes double orders. The guard is the Idempotency-Key header. The client makes one UUID (a unique random code) per action, sends it in that header, and reuses it on retry. The server stores the response per key, then replays the same response for a retry. The same key with a different body is refused with 422, and a key whose first request is still being processed gets 409. When you replay, return a copy of the response, and keep keys for a sensible time, say 24 hours.
⚡ Idempotent: repeat it and the result is the same
Guess first: book 1 has a stock of 12. PATCH /books/1 with the body {"stock_delta": -1} ("subtract one") is sent 3 times. What's the stock now?
It goes from 12 to 9. An add-or-subtract command such as +1 isn't idempotent. The body {"stock": 11} sent 3 times still gives 11.
Meaning: An idempotent request can be sent many times, and the end result on the server stays the same. GET, PUT and DELETE are idempotent by definition. POST isn't, and PATCH depends on its body: an absolute value (the final number written directly) can be repeated, adding or subtracting can't.
⚡ A retry after a timeout
Meaning: A client that gets no answer before its waiting time ends (a timeout) can't tell "the request never arrived" from "the request arrived, the answer got lost". So the client sends it again (a retry), and an unprotected POST /orders makes two orders for one book.
⚡ Idempotency-Key: a receipt number from the client
Write:
const key = crypto.randomUUID(); // once, when the Buy button is pressed
function createOrder() {
return fetch("https://api.bookshop.test/orders", {
method: "POST",
headers: { "Content-Type": "application/json", "Idempotency-Key": key },
body: JSON.stringify({ book_id: 1, qty: 1 }),
});
}
Meaning: The client makes one key per action (one press of Buy) with crypto.randomUUID(), which gives a unique random code, then sends it in the Idempotency-Key header. A retry uses the same key, like the same receipt number. The server stores the response per key, then sends the same response for a retry, without making a new order.