Every checkout eventually meets the same incident. A payment provider takes too long to answer, the request times out, something retries, and a customer is charged twice. The support ticket arrives before the alert does.
The instinct is to make the timeout longer or to remove the retry. Both are wrong. The retry is the correct behaviour for a distributed system. What is missing is a way for the other side to recognise that it has seen this request before.
The failure nobody designs for
A network timeout tells you nothing about what happened on the server. The request may never have arrived. It may have arrived, been processed fully, and had its response lost on the way back. From the caller's point of view these two cases look identical, and they require opposite responses.
This is why retry logic added without thought is dangerous specifically on writes. Reading a product twice is free. Placing an order twice is not.
What an idempotency key actually does
An idempotency key is a unique token the caller generates and attaches to a write request. The server stores the key alongside the result of the first successful execution. If the same key arrives again, the server skips the work and replays the stored response.
The important detail is that the key is generated by the caller, once, before the first attempt. If the client generates a new key on retry, the mechanism does nothing at all. I have seen that bug ship more than once.
// generated once, at the start of the attempt, and reused for every retry
const idempotencyKey = crypto.randomUUID();
async function placeOrder(basket, attempt = 1) {
try {
return await paymentClient.post('/orders', basket, {
headers: { 'Idempotency-Key': idempotencyKey },
timeout: 4000
});
} catch (error) {
if (!isRetryable(error) || attempt >= 3) throw error;
await backoff(attempt);
return placeOrder(basket, attempt + 1);
}
}
Implementing the server side
The server side is where most implementations get it subtly wrong. Storing the key after the work completes leaves a window where two concurrent requests with the same key both pass the check. The record has to be claimed before the work starts.
A unique constraint on the key column does this for you. Insert first, and let the database reject the duplicate.
CREATE TABLE idempotency_record (
idempotency_key VARCHAR(64) NOT NULL PRIMARY KEY,
request_hash CHAR(64) NOT NULL,
state VARCHAR(16) NOT NULL, -- IN_PROGRESS | COMPLETED
response_body JSON NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
The flow becomes four steps, and the order of them is the whole design.
- Insert the key with state
IN_PROGRESS. A duplicate-key error means someone else got here first. - If the insert failed and the stored record is
COMPLETED, return the stored response and do no work. - If the insert failed and the record is still
IN_PROGRESS, return409 Conflictso the caller backs off rather than racing. - On success, do the work, then update the record to
COMPLETEDwith the response body in the same transaction.
Hash the request body too
Storing a hash of the request alongside the key protects against a real client bug: reusing a key for a different payload. If the key matches but the hash does not, the correct answer is an error rather than a replayed response. Returning the old response in that case hides the bug and produces a wrong order.
Where this pays off
On a headless migration I worked on, fraud verification and payment capture both sat on the synchronous checkout path. Moving verification to asynchronous processing cut the latency, but it also widened the window in which a retry could arrive. Idempotency keys were what made that change safe rather than merely faster.
The pattern costs a table, a unique constraint and about an afternoon. It removes an entire category of incident, permanently. There are not many trades in backend engineering that good.