Idempotency keys for payments: stop double charges on retries
Guide/ 13 min read
One key per payment attempt, stored on the server with the response it got: a retry, a double click or a timeout charges once. Tested Node code, no dependencies.
- Node.js
- Databases
In this article (8)
Idempotency keys stop double charges: the client generates one unique key per payment attempt and sends it in the Idempotency-Key header. The server stores the key with a fingerprint of the body and the response; when the same key arrives again, it replays that response instead of charging again. A double click, retry or timeout charges once.
This guide covers why double charges happen, what Stripe and the IETF draft say about the header, and how to build it in Node with no dependencies: the client, the server and the tests we ran. If you also sell limited stock, the sibling problem is selling units you do not have, covered in how to prevent inventory overselling.
Why double charges happen: retries, double clicks, timeouts
A double charge is rarely the payment processor's fault. It is your system sending the same charge twice, for one of three reasons:
- Double clicks. The shopper taps "Pay", the page is slow, they tap again. Two identical
POSTrequests leave almost at once. - Automatic retries. Your
fetchwrapper, an SDK, a proxy or a queue retries a request it thinks failed. Stripe's SDKs, for example, can generate keys and retry on their own. - Timeouts. The server charged the card, but the response was lost on the way back: a flaky mobile network, a load balancer that dropped the connection. The client sees an error, cannot tell whether it was charged, and retries.
The third one is the expensive one, because disabling the button does nothing for it. Stripe's advanced error handling guide puts it plainly: when a connection fails, you cannot know whether the server received or ran the request. A missing response does not mean a missing charge.
Scroll the figure sideways to see all of it
The fix is not to stop retrying. It is to make retrying safe, so the server recognises the second request as the same operation and does not run it twice.
What an idempotency key is
An operation is idempotent when doing it several times leaves the same result as doing it once. Per RFC 9110, which the IETF draft cites, GET, PUT and DELETE are idempotent; POST and PATCH are not. A charge is a POST: two requests, two charges.
An idempotency key is a unique string the client generates for one operation and sends with every attempt at that operation. The server uses it to spot retries: the first time it processes the request, after that it returns what it already answered. Two references are worth reading:
- Stripe's idempotent requests documentation, for its v1 API.
- The IETF httpapi working group's draft-ietf-httpapi-idempotency-key-header-08, published on October 22, 2026. It is an active Internet-Draft, not an RFC: it can still change, and it expires on April 25, 2027 unless renewed.
| Topic | Stripe (API v1) | IETF draft -08 |
|---|---|---|
| Header | Idempotency-Key | Idempotency-Key |
| Format | Up to 255 characters; suggests V4 UUIDs or another random string with enough entropy | A Structured Fields String, in double quotes; recommends a UUID or a similar random identifier |
| How long it lasts | At least 24 hours; after that it may be pruned, and the same key starts a new request | Each API defines an expiry policy and publishes it |
| Same key, different body | Error: it compares the parameters with the original request | 422 Unprocessable Content |
| Same key, request still running | 409 Conflict, nothing saved | 409 Conflict |
| No key | Nothing to deduplicate: every POST is new | 400 Bad Request if the API requires one |
| Which requests | Every POST; no effect on GET and DELETE | Non-idempotent methods such as POST and PATCH |
Two Stripe details are worth copying. It saves the status code and body of the first response as soon as execution begins, 500 errors included, and flags replays with Idempotent-Replayed: true. And when the parameters fail validation, or another request with the same key is still running, it saves nothing, so you can retry with the same key.
Scroll the figure sideways to see all of it
Client side: one idempotency key per payment attempt
The client rule fits on one line: the key is born when the payment attempt starts and is reused by every retry and every repeated click of that attempt. A fresh key per request protects nothing. This is the whole client, client.mjs:
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
export async function postPayment(url, payment, key, { retries = 3, timeoutMs = 10000 } = {}) {
for (let attempt = 0; ; attempt++) {
try {
const res = await fetch(url, {
method: "POST",
headers: { "content-type": "application/json", "idempotency-key": key },
body: JSON.stringify(payment),
signal: AbortSignal.timeout(timeoutMs),
});
if ([409, 502, 503, 504].includes(res.status) && attempt < retries) {
await sleep(200 * 2 ** attempt);
continue;
}
return { status: res.status, replayed: res.headers.get("idempotent-replayed") === "true", body: await res.json() };
} catch (err) {
if (attempt >= retries) throw err;
await sleep(200 * 2 ** attempt);
}
}
}
let key = null;
export async function onPay(payment, url = "/payments") {
key ??= crypto.randomUUID();
const result = await postPayment(url, payment, key);
if (result.status < 500 && result.status !== 409) key = null;
return result;
}
postPaymenttakes the key as an argument and never makes one up, so all of its retries send the same key and the same body.AbortSignal.timeout(timeoutMs)caps the wait. A timeout says nothing about whether the card was charged, which is why it is retried with the same key.- It retries
409(another request with this key is still running) and502,503and504(the server never answered), backing off 200, 400 and 800 ms. It does not retry a500: the server has stored that response and would replay it. - A network error, the
catch, is retried with the same key too, up toretriestimes, and then thrown. replayedreads theidempotent-replayedheader our server sends, the same name Stripe uses.onPayis what you wire to the "Pay" button.key ??= crypto.randomUUID()only creates a key when there is none, so the second click of a double click reuses the first one's key.- After a final answer (a
201, or a4xxother than409) the key is dropped and the next purchase gets a new one. After a network error, a409or a5xxit is kept, so the next click repeats the same attempt instead of starting another.
crypto.randomUUID() returns a v4 UUID from a cryptographically secure generator, but per MDN it is only available in secure contexts (HTTPS). And yes, disable the button while the payment runs. It is good UX, but it does not replace the key, because it does nothing for retries or timeouts.
Server side: store the key and replay the response
The server does four things in order: validate, fingerprint the body, look the key up and, if it is new, claim it before charging. This is the whole server, server.mjs, built on node:http with no dependencies:
import { createServer } from "node:http";
import { createHash } from "node:crypto";
export function createPaymentServer(charge) {
const keys = new Map();
const send = (res, status, body, headers = {}) => {
res.writeHead(status, { "content-type": "application/json", ...headers });
res.end(JSON.stringify(body));
};
return createServer(async (req, res) => {
if (req.method !== "POST" || req.url !== "/payments") return send(res, 404, { error: "not found" });
const key = req.headers["idempotency-key"];
if (!key || key.length > 255) return send(res, 400, { error: "Idempotency-Key is missing or too long" });
let raw = "";
for await (const chunk of req) raw += chunk;
let payment;
try {
payment = JSON.parse(raw);
} catch {
return send(res, 400, { error: "body is not JSON" });
}
if (!Number.isInteger(payment?.amount) || payment.amount <= 0 || !/^[a-z]{3}$/.test(payment.currency)) {
return send(res, 400, { error: "amount (integer, cents) and currency (e.g. mxn) are required" });
}
const fingerprint = createHash("sha256").update(raw).digest("hex");
const saved = keys.get(key);
if (saved) {
if (saved.fingerprint !== fingerprint) return send(res, 422, { error: "Idempotency-Key already used with another body" });
if (!saved.done) return send(res, 409, { error: "a request with this Idempotency-Key is in progress" });
return send(res, saved.status, saved.body, { "idempotent-replayed": "true" });
}
keys.set(key, { fingerprint, done: false });
let status, body;
try {
body = await charge(payment);
status = 201;
} catch {
status = 500;
body = { error: "payment outcome unknown; check the order before trying again" };
}
keys.set(key, { fingerprint, done: true, status, body });
send(res, status, body);
});
}
keysis an in-memoryMapwith one entry per key, andsendwrites a JSON response with any extra headers.- No key, or one longer than 255 characters (Stripe's limit), gets a
400, as the draft recommends. - It reads and validates the body:
amounta positive integer in cents,currencythree letters. An invalid body gets a400and nothing is stored, as at Stripe, so the client can fix it and retry with the same key. fingerprintis the SHA-256 of the raw body. It is the fingerprint the draft describes, and it catches a key reused with different content.- If the key exists: different fingerprint,
422; still running,409; finished, it replays the stored status and body withidempotent-replayed: true. keys.set(key, { fingerprint, done: false })claims the key before the provider is called. There is noawaitbetweenkeys.getandkeys.set, so within one Node process two requests with the same key cannot both get past that point.charge(payment)is your call to the payment provider. If it throws, the500is stored too: the outcome is unknown and a retry must not charge again. That is what Stripe does.- Finally it stores the status and body, and responds.
Scroll the figure sideways to see all of it
With more than one instance
The Map lives in one process's memory: it is lost on restart and not shared between instances. Our recommendation for production is a shared table with the key as PRIMARY KEY, claimed with INSERT ... ON CONFLICT (key) DO NOTHING RETURNING key. The unique constraint lets only one request insert the row, and RETURNING only returns inserted rows (see PostgreSQL's INSERT documentation). It is the same claim as the Map, moved into the database. That SQL is not part of the code we tested here. Also decide how long each key is kept (Stripe: at least 24 hours) and delete older ones.
Send a key to your provider as well. If your server calls Stripe and that call times out, your own retry to Stripe is another possible charge. Stripe accepts Idempotency-Key on every POST: use one stable key per attempt, such as the one the client sent you.
Full Node.js idempotency example
The full example is three files: the client and server above, plus demo.mjs, which starts the server with a fake provider that takes 300 ms and numbers each charge. We ran it with Node 22 on Windows 11.
import { createPaymentServer } from "./server.mjs";
let charges = 0;
const charge = async ({ amount, currency }) => {
await new Promise((resolve) => setTimeout(resolve, 300));
return { id: `ch_${++charges}`, amount, currency, status: "succeeded" };
};
createPaymentServer(charge).listen(8787, () => console.log("POST http://localhost:8787/payments"));
Start it with node demo.mjs and, in another bash terminal (Git Bash works on Windows), run bash curl.sh:
KEY=8e03978e-40d5-43e8-bc93-6894a57f9324
BODY='{"orderId":"A-1001","amount":129900,"currency":"mxn"}'
pay() { curl -s http://localhost:8787/payments -H "content-type: application/json" -H "Idempotency-Key: $1" -d "$2" -w ' -> %{http_code} %header{idempotent-replayed}\n'; }
pay $KEY "$BODY"
pay $KEY "$BODY"
pay $KEY '{"orderId":"A-1001","amount":1,"currency":"mxn"}'
pay other-key "$BODY" & pay other-key "$BODY"; wait
This is the output we got:
{"id":"ch_1","amount":129900,"currency":"mxn","status":"succeeded"} -> 201
{"id":"ch_1","amount":129900,"currency":"mxn","status":"succeeded"} -> 201 true
{"error":"Idempotency-Key already used with another body"} -> 422
{"error":"a request with this Idempotency-Key is in progress"} -> 409
{"id":"ch_2","amount":129900,"currency":"mxn","status":"succeeded"} -> 201
- First payment:
201and chargech_1. - Same order, same key: the same response, the same
ch_1, flagged as a replay. The provider did not charge again. - Same key, different amount:
422, and no charge. - Two simultaneous requests with the key
other-key: one gets409while the other chargesch_2. Those two lines can swap order from run to run.
Our 11 tests, in payments.test.mjs with Node's built-in test runner, count the fake provider's charges in every case, and all passed with node --test payments.test.mjs: a same-key retry, the same key with another body, two simultaneous requests, a client timeout, a double click and a failing charge. The most instructive one sends the same order with two different keys, and it is charged twice. The key only protects you if the retry repeats it.
Common mistakes
- Generating a new key on every retry. The most common mistake, and the test proves it: two keys, two charges. The key belongs to the payment attempt, not to the request.
- Storing the key after charging. If you claim it at the end, two simultaneous requests both pass the lookup and both charge. Claim it before calling the provider.
- Comparing only the key. Without a body fingerprint, a client bug that reuses a key with another amount gets the previous payment's response as if it were its own. Answer
422. - Deleting the key when the charge fails with an unknown error. If the provider did charge and you deleted the key, the retry charges again. Store the
500and reconcile the order before starting a new attempt. - Using personal data as the key, or one key space for every customer. Stripe asks you to avoid email addresses and personal identifiers; a random UUID reveals nothing. And our recommendation: store each key with the account that sent it, so nobody receives someone else's stored response.
- Thinking a disabled button is enough. It helps with double clicks, not with retries or timeouts.
Frequently asked questions
How long should I keep each idempotency key?
The IETF draft leaves it to each API and asks you to publish the policy. Stripe keeps keys for at least 24 hours and may prune them after that; a key reused after pruning starts a new request. Our recommendation for a checkout: 24 hours, which covers the retries of one payment attempt.
Does the key go in quotes?
The draft defines the value as a Structured Fields String, so it writes it in double quotes: Idempotency-Key: "8e03978e-40d5-43e8-bc93-6894a57f9324". Stripe's examples send it without quotes. For your own API, treat the value as an opaque string and document what you expect: as long as the client repeats exactly the same value, it works.
Do GET and DELETE requests need a key?
No. Stripe says a key has no effect on GET and DELETE because they are already idempotent, and the draft targets POST and PATCH. Put it on anything that creates or charges something.
What if the first attempt returned a 500?
Treat it as an unknown outcome: the charge may have happened. Stripe advises against retrying with a new key until you have reconciled what happened, for example through webhooks or by fetching the object. Our server stores the 500 so a retry with the same key cannot charge again.
Checklist
- The client creates the key when the payment attempt starts, with
crypto.randomUUID(). - Retries and repeated clicks of that attempt send the same key and the same body.
- The server claims the key before charging, in a shared store if you run several instances.
- You store a body fingerprint and answer
422when it changes. - A request with the same key still running gets
409, and the client retries it. - Replays match the original response,
500errors included. - Keys expire under a written policy (for example, 24 hours).
- Your server also sends a stable key to the payment provider.
With a key in place, a retry stops being a risk and becomes the normal way to recover from a flaky network. The next weak spot in a checkout is usually inventory: how to prevent overselling when two shoppers buy the last unit. And remember that this endpoint needs its own authentication: CORS does not protect your API. If an agent is making this change for you, ask it for a plan first with Claude Code plan mode.
Saw this on Instagram? Comment PAGOS on the Reel and I'll send you the guide.
Written by

Published October 30, 2026 · updated November 1, 2026