APIs · Advanced · 28 min
Make POST requests safe to retry with idempotency keys
By Padding · Updated 18 Nov 2026
Debian (node:26 image) · Node.js 26.13.1 · node:sqlite
You will add Idempotency-Key handling to a Node.js 26 payments endpoint backed by SQLite, so a retried, duplicated or simultaneous request charges the customer exactly once.
On this page
A customer taps Pay. Your API charges their card, but the answer takes a moment too long and the phone's request times out. The app does the sensible thing and tries again. Your server has no way to tell the second request from a new payment, so it charges the card again.
GET, PUT and DELETE are idempotent by definition: sending one twice has the same effect as sending it once. POST is not, and "create a payment" is almost always a POST. The fix is for the client to name each operation it means to perform. It sends a random key in an Idempotency-Key header and reuses that key on every retry. The server remembers each key, does the work once, and answers repeats with the saved response.
The header is being standardised by the IETF HTTP APIs working group in draft-ietf-httpapi-idempotency-key-header (version 08 at the time of writing, still a draft). This tutorial follows it: a key reused with a different body gets 422, a repeat that arrives while the first is still running gets 409, and keys expire under a published policy.
You will build a small payments API with Node's built-in node:http and node:sqlite modules, so there is nothing to install from npm. A fake card processor stands in for a real one and answers slowly on purpose. You first watch a retry charge a customer twice, then fix it, and finish with a retry storm script that fires 25 clients at one payment and proves there is exactly one charge.
This matters everywhere, and more so where most people pay from a phone on mobile data, as in much of Africa. Connections on a weak signal drop in the middle of requests, and people press Pay again when nothing seems to happen. Both look like duplicates to your server.
Step 1 · Set up the project and a slow fake processor
Check your Node.js version. This tutorial needs 26 or newer for the Database class in node:sqlite:
node --versionThe output starts with v26.. Create a demo folder and mark it as an ES module project:
mkdir -p ~/idempotency-demo
cd ~/idempotency-demo
cat > package.json <<'JSON'
{ "name": "idempotency-demo", "private": true, "type": "module" }
JSONCreate db.mjs. It opens payments.db in the current folder and creates two tables. provider_charges stands in for the card processor's own ledger: one row is one real charge on a customer's card. payments is your app's record. WAL mode and a busy timeout let more than one process share the file without errors:
cat > db.mjs <<'JS'
import { Database } from 'node:sqlite';
export const db = new Database(process.env.DB_FILE ?? 'payments.db');
db.exec(`
PRAGMA journal_mode = WAL;
PRAGMA busy_timeout = 5000;
-- Stands in for the payment provider's own ledger: one row per real charge.
CREATE TABLE IF NOT EXISTS provider_charges (
id TEXT PRIMARY KEY,
customer TEXT NOT NULL,
amount_minor INTEGER NOT NULL,
currency TEXT NOT NULL,
created_at INTEGER NOT NULL
);
-- Your app's record of each payment.
CREATE TABLE IF NOT EXISTS payments (
id TEXT PRIMARY KEY,
customer TEXT NOT NULL,
amount_minor INTEGER NOT NULL,
currency TEXT NOT NULL,
charge_id TEXT NOT NULL,
created_at INTEGER NOT NULL
);
`);
JSCreate provider.mjs, the fake processor. It records the charge at once and then waits before it answers, which is exactly the situation that causes double charges: the money has moved, but the caller does not know yet. The delay is 1.5 seconds unless you set PROVIDER_DELAY_MS:
cat > provider.mjs <<'JS'
import { randomUUID } from 'node:crypto';
import { db } from './db.mjs';
const delayMs = Number(process.env.PROVIDER_DELAY_MS ?? 1500);
const record = db.prepare(
'INSERT INTO provider_charges (id, customer, amount_minor, currency, created_at) VALUES (?, ?, ?, ?, ?)',
);
// A fake card processor. The money moves at once; the answer comes back slowly.
export async function chargeCard({ customer, amountMinor, currency }) {
const id = `ch_${randomUUID()}`;
record.run(id, customer, amountMinor, currency, Date.now());
await new Promise((resolve) => setTimeout(resolve, delayMs));
return { id };
}
JSCreate http-helpers.mjs with four small functions the server uses: sending JSON, building an RFC 9457 problem body, reading the request body with a 16 KB limit, and validating a payment. Amounts are integers in the currency's minor unit (kobo, pesewas, cents), never floating-point numbers:
cat > http-helpers.mjs <<'JS'
export function send(res, status, body, headers = {}) {
const text = typeof body === 'string' ? body : JSON.stringify(body);
const type = status >= 400 ? 'application/problem+json' : 'application/json';
res.writeHead(status, { 'content-type': type, ...headers });
res.end(text);
}
export function problem(status, title, detail) {
return { type: '/docs/idempotency', title, status, detail };
}
export async function readBody(req, limit = 16 * 1024) {
const chunks = [];
let size = 0;
for await (const chunk of req) {
size += chunk.length;
if (size > limit) throw Object.assign(new Error('body too large'), { status: 413 });
chunks.push(chunk);
}
return Buffer.concat(chunks);
}
export function parsePayment(raw) {
let data;
try {
data = JSON.parse(raw.toString('utf8'));
} catch {
return null;
}
const valid =
typeof data?.customer === 'string' &&
/^cus_[A-Za-z0-9_]{1,40}$/.test(data.customer) &&
Number.isInteger(data.amountMinor) &&
data.amountMinor > 0 &&
typeof data.currency === 'string' &&
/^[A-Z]{3}$/.test(data.currency);
return valid ? { customer: data.customer, amountMinor: data.amountMinor, currency: data.currency } : null;
}
JSThe problem type is a relative URI, /docs/idempotency. Point it at the page where you publish your key policy, which the draft asks every API to do.
Check it worked
Import db.mjs once and list the tables it created:
node --input-type=module -e "
import { db } from './db.mjs';
const rows = db.prepare(\"SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name\").all();
console.log(rows.map((r) => r.name).join(' '));
"The output is payments provider_charges, and payments.db now exists in the folder.
Step 2 · Watch a retry charge twice
Create server.mjs, a payments API with no protection. POST /payments validates the body, charges the card and saves the payment. GET /charges?customer=... counts the charges the processor made for one customer, so you can see the damage. GET /health says which version of the server is running:
cat > server.mjs <<'JS'
import { createServer } from 'node:http';
import { randomUUID } from 'node:crypto';
import { db } from './db.mjs';
import { chargeCard } from './provider.mjs';
import { send, problem, readBody, parsePayment } from './http-helpers.mjs';
const port = Number(process.env.PORT ?? 3000);
const insertPayment = db.prepare(
'INSERT INTO payments (id, customer, amount_minor, currency, charge_id, created_at) VALUES (?, ?, ?, ?, ?, ?)',
);
const countCharges = db.prepare('SELECT count(*) AS n FROM provider_charges WHERE customer = ?');
async function handle(req, res) {
const url = new URL(req.url, 'http://localhost');
if (req.method === 'GET' && url.pathname === '/health') {
return send(res, 200, { ok: true, idempotent: false });
}
if (req.method === 'GET' && url.pathname === '/charges') {
const customer = url.searchParams.get('customer') ?? '';
return send(res, 200, { customer, charges: countCharges.get(customer).n });
}
if (req.method === 'POST' && url.pathname === '/payments') {
const input = parsePayment(await readBody(req));
if (!input) return send(res, 400, problem(400, 'Invalid payment', 'Send customer, amountMinor and currency.'));
const charge = await chargeCard(input);
const payment = { id: `pay_${randomUUID()}`, ...input, chargeId: charge.id };
insertPayment.run(payment.id, input.customer, input.amountMinor, input.currency, charge.id, Date.now());
return send(res, 201, payment);
}
send(res, 404, problem(404, 'Not found', `${req.method} ${url.pathname} does not exist.`));
}
createServer((req, res) => {
handle(req, res).catch((err) => {
console.error(err);
if (!res.headersSent) send(res, err.status ?? 500, problem(err.status ?? 500, 'Request failed', 'Try again later.'));
});
}).listen(port, '127.0.0.1', () => console.log(`payments API on http://127.0.0.1:${port}`));
JSStart it in your second terminal, from ~/idempotency-demo, and leave it running:
node server.mjsIt prints payments API on http://127.0.0.1:3000.
Now write the client. retry.mjs behaves like a careful mobile app. It generates one key for the payment, serialises the body once, and gives the first attempt only one second, as a phone on a weak signal might. When an attempt times out, or the server answers 409 or a 5xx error, it waits 1.5 seconds and tries again with the same key and the same bytes:
cat > retry.mjs <<'JS'
import { randomUUID } from 'node:crypto';
const api = process.env.API ?? 'http://127.0.0.1:3000';
const customer = process.argv[2] ?? 'cus_demo';
// Serialise the body once and send the same bytes on every attempt.
const body = JSON.stringify({ customer, amountMinor: 250000, currency: 'NGN' });
// One key per payment the user meant to make, reused on every retry of it.
const key = randomUUID();
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
for (let attempt = 1; attempt <= 4; attempt++) {
const timeoutMs = attempt === 1 ? 1000 : 5000;
try {
const res = await fetch(`${api}/payments`, {
method: 'POST',
headers: { 'content-type': 'application/json', 'idempotency-key': `"${key}"` },
body,
signal: AbortSignal.timeout(timeoutMs),
});
const data = await res.json();
const replayed = res.headers.get('idempotency-replayed') === 'true' ? ' (replayed)' : '';
console.log(`attempt ${attempt}: ${res.status}${replayed} ${data.id ?? data.title}`);
if (res.status !== 409 && res.status < 500) break;
} catch (err) {
if (err.name !== 'TimeoutError') throw err;
console.log(`attempt ${attempt}: no answer after ${timeoutMs} ms`);
}
await sleep(1500);
}
const res = await fetch(`${api}/charges?customer=${encodeURIComponent(customer)}`);
const { charges } = await res.json();
console.log(`charges for ${customer}: ${charges}`);
JSThe client already sends an Idempotency-Key. Run it against the unprotected server, in your first terminal:
node retry.mjs cus_naiveCheck it worked
The output is something like this, with different IDs:
attempt 1: no answer after 1000 ms
attempt 2: 201 pay_3f0c9a1e-...
charges for cus_naive: 2The customer paid once and was charged twice. Sending a key is not enough: the header does nothing until the server acts on it.
Step 3 · Build the idempotency key store
The server needs to remember four things about each key: a fingerprint of the request it came with, whether that request is still running, the response it produced, and when the key expires. Create idempotency.mjs:
cat > idempotency.mjs <<'JS'
import { createHash } from 'node:crypto';
import { db } from './db.mjs';
const ttlMs = Number(process.env.IDEMPOTENCY_TTL_SECONDS ?? 24 * 60 * 60) * 1000;
const KEY_FORMAT = /^[A-Za-z0-9_-]{16,255}$/;
db.exec(`
CREATE TABLE IF NOT EXISTS idempotency_keys (
key TEXT PRIMARY KEY,
fingerprint TEXT NOT NULL,
status TEXT NOT NULL CHECK (status IN ('processing', 'done')),
response_status INTEGER,
response_body TEXT,
created_at INTEGER NOT NULL,
expires_at INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS idempotency_keys_expires_at ON idempotency_keys (expires_at);
`);
const dropExpired = db.prepare('DELETE FROM idempotency_keys WHERE key = ? AND expires_at <= ?');
const insertClaim = db.prepare(`
INSERT INTO idempotency_keys (key, fingerprint, status, created_at, expires_at)
VALUES (?, ?, 'processing', ?, ?)
ON CONFLICT (key) DO NOTHING
`);
const findKey = db.prepare('SELECT fingerprint, status, response_status, response_body FROM idempotency_keys WHERE key = ?');
const markDone = db.prepare(`
UPDATE idempotency_keys
SET status = 'done', response_status = ?, response_body = ?, expires_at = ?
WHERE key = ? AND status = 'processing'
`);
const deleteProcessing = db.prepare("DELETE FROM idempotency_keys WHERE key = ? AND status = 'processing'");
const deleteAllExpired = db.prepare('DELETE FROM idempotency_keys WHERE expires_at <= ?');
// The header is a Structured Field string, so clients send it in double quotes.
export function readKey(headerValue) {
if (typeof headerValue !== 'string') return null;
let value = headerValue.trim();
if (value.length >= 2 && value.startsWith('"') && value.endsWith('"')) value = value.slice(1, -1);
return KEY_FORMAT.test(value) ? value : null;
}
// Same method, path and body bytes give the same fingerprint.
export function fingerprint(method, path, rawBody) {
return createHash('sha256').update(`${method} ${path}\n`).update(rawBody).digest('hex');
}
// Try to take the key. Exactly one caller gets "new"; everyone else learns why not.
export function claim(key, print) {
const now = Date.now();
dropExpired.run(key, now);
if (insertClaim.run(key, print, now, now + ttlMs).changes === 1) return { outcome: 'new' };
const row = findKey.get(key);
if (!row) return { outcome: 'in-progress' };
if (row.fingerprint !== print) return { outcome: 'mismatch' };
if (row.status === 'processing') return { outcome: 'in-progress' };
return { outcome: 'replay', status: row.response_status, body: row.response_body };
}
// Save the response that every later retry with this key will receive.
// The key stays valid for the full time to live after the response exists.
export function complete(key, status, body) {
if (markDone.run(status, body, Date.now() + ttlMs, key).changes !== 1) throw new Error(`key ${key} was not being processed`);
}
// Give the key back when the work failed before anything happened, so a retry can run it.
export function release(key) {
deleteProcessing.run(key);
}
export function purgeExpired() {
return deleteAllExpired.run(Date.now()).changes;
}
JSEach function has one job:
readKeyaccepts the header with or without the double quotes the draft specifies (it defines the value as a Structured Field string, soIdempotency-Key: "8e03978e-..."). It rejects anything shorter than 16 characters or containing odd characters. A UUID passes.fingerprinthashes the method, path and the raw body bytes with SHA-256. Two requests match only if they are byte for byte the same, which is why the client serialises the body once. If your clients cannot promise that, hash a canonical form of the fields that matter instead; the draft allows either.claimis the lock.INSERT ... ON CONFLICT (key) DO NOTHINGagainst the primary key succeeds for exactly one caller. Everyone else reads the existing row and learns whether the body differs (mismatch), the first request is still running (in-progress) or a saved response is ready (replay). An expired row is deleted first, so an old key behaves like a new one.completesaves the response and restarts the expiry clock, so a key always lives for the full time to live after its response exists.releaseremoves a key whose work failed before anything happened, so a retry can run it again.
The node:sqlite API is synchronous. Inside one Node process no other request can run between the INSERT and the SELECT in claim. Across processes, the primary key does the work: SQLite, and PostgreSQL with the same INSERT ... ON CONFLICT DO NOTHING statement, let only one insert of a key succeed.
Create a script that exercises every outcome without a server:
cat > check-store.mjs <<'JS'
import { randomUUID } from 'node:crypto';
import { readKey, fingerprint, claim, complete } from './idempotency.mjs';
const key = readKey(`"${randomUUID()}"`);
const first = fingerprint('POST', '/payments', Buffer.from('{"amountMinor":100}'));
const other = fingerprint('POST', '/payments', Buffer.from('{"amountMinor":999}'));
console.log('bad key accepted:', readKey('abc') !== null);
console.log('first request: ', claim(key, first).outcome);
console.log('while running: ', claim(key, first).outcome);
console.log('different body: ', claim(key, other).outcome);
complete(key, 201, '{"id":"pay_example"}');
const again = claim(key, first);
console.log('after finishing: ', again.outcome, again.status, again.body);
JS
node check-store.mjsCheck it worked
The output is:
bad key accepted: false
first request: new
while running: in-progress
different body: mismatch
after finishing: replay 201 {"id":"pay_example"}The key in this script is random, so you can run it again and get the same result.
Step 4 · Protect the payments endpoint
Replace server.mjs with a version that uses the store. The order of checks matters. A missing key is rejected before the body is read. Validation errors are not stored, because the client must change the body to fix them, and a changed body is a different request. Only then does the request try to claim the key:
cat > server.mjs <<'JS'
import { createServer } from 'node:http';
import { randomUUID } from 'node:crypto';
import { db } from './db.mjs';
import { chargeCard } from './provider.mjs';
import { send, problem, readBody, parsePayment } from './http-helpers.mjs';
import { readKey, fingerprint, claim, complete, release, purgeExpired } from './idempotency.mjs';
const port = Number(process.env.PORT ?? 3000);
const insertPayment = db.prepare(
'INSERT INTO payments (id, customer, amount_minor, currency, charge_id, created_at) VALUES (?, ?, ?, ?, ?, ?)',
);
const countCharges = db.prepare('SELECT count(*) AS n FROM provider_charges WHERE customer = ?');
async function createPayment(req, res, url) {
const key = readKey(req.headers['idempotency-key']);
if (!key) {
return send(res, 400, problem(400, 'Idempotency-Key is missing or invalid',
'Send a new UUID in the Idempotency-Key header for each payment, and the same one on every retry.'));
}
const raw = await readBody(req);
const input = parsePayment(raw);
if (!input) return send(res, 400, problem(400, 'Invalid payment', 'Send customer, amountMinor and currency.'));
const result = claim(key, fingerprint(req.method, url.pathname, raw));
if (result.outcome === 'mismatch') {
return send(res, 422, problem(422, 'Idempotency-Key is already used',
'This key was sent before with a different body. Use a new key for a new payment.'));
}
if (result.outcome === 'in-progress') {
return send(res, 409, problem(409, 'A request with this Idempotency-Key is in progress',
'Wait a moment, then retry with the same key and body.'));
}
if (result.outcome === 'replay') {
return send(res, result.status, result.body, { 'idempotency-replayed': 'true' });
}
// Outcome "new": this request owns the key until it completes or releases it.
let charge;
try {
charge = await chargeCard(input);
} catch (err) {
release(key);
throw err;
}
const payment = { id: `pay_${randomUUID()}`, ...input, chargeId: charge.id };
const body = JSON.stringify(payment);
db.exec('BEGIN IMMEDIATE');
try {
insertPayment.run(payment.id, input.customer, input.amountMinor, input.currency, charge.id, Date.now());
complete(key, 201, body);
db.exec('COMMIT');
} catch (err) {
db.exec('ROLLBACK');
throw err;
}
return send(res, 201, body);
}
async function handle(req, res) {
const url = new URL(req.url, 'http://localhost');
if (req.method === 'GET' && url.pathname === '/health') {
return send(res, 200, { ok: true, idempotent: true });
}
if (req.method === 'GET' && url.pathname === '/charges') {
const customer = url.searchParams.get('customer') ?? '';
return send(res, 200, { customer, charges: countCharges.get(customer).n });
}
if (req.method === 'POST' && url.pathname === '/payments') return createPayment(req, res, url);
send(res, 404, problem(404, 'Not found', `${req.method} ${url.pathname} does not exist.`));
}
setInterval(() => {
const removed = purgeExpired();
if (removed) console.log(`purged ${removed} expired idempotency keys`);
}, 60_000).unref();
createServer((req, res) => {
handle(req, res).catch((err) => {
console.error(err);
if (!res.headersSent) send(res, err.status ?? 500, problem(err.status ?? 500, 'Request failed', 'Try again with the same Idempotency-Key.'));
});
}).listen(port, '127.0.0.1', () => console.log(`payments API on http://127.0.0.1:${port}`));
JSThree details carry the weight:
- The payment row and the saved response are written in one transaction. Either both exist or neither does.
- If the charge throws, the key is released so the client's retry can try again. If anything fails after the charge succeeded, the key stays in
processingon purpose: retries get409rather than a second charge, and someone reconciles that payment by hand. - A replay sends the stored status and body byte for byte, plus an
Idempotency-Replayed: trueheader so clients and logs can tell a replay from a fresh result. The draft does not define a header for this; the name is this API's own choice.
Stop the old server with Ctrl+C in the second terminal and start the new one:
node server.mjsRun the same client again, for a new customer:
node retry.mjs cus_safeFor a closer look, create pay.mjs, a one-shot client that sends a single payment with a key you choose (or - for no key) and an optional amount:
cat > pay.mjs <<'JS'
const api = process.env.API ?? 'http://127.0.0.1:3000';
const [key, customer = 'cus_demo', amount = '250000'] = process.argv.slice(2);
const headers = { 'content-type': 'application/json' };
if (key && key !== '-') headers['idempotency-key'] = `"${key}"`;
const res = await fetch(`${api}/payments`, {
method: 'POST',
headers,
body: JSON.stringify({ customer, amountMinor: Number(amount), currency: 'NGN' }),
signal: AbortSignal.timeout(10_000),
});
const data = await res.json();
const replayed = res.headers.get('idempotency-replayed') === 'true' ? ' (replayed)' : '';
console.log(`${res.status}${replayed} ${data.id ?? data.title}`);
JSSend the same payment twice with one key:
KEY=$(node -p "crypto.randomUUID()")
node pay.mjs "$KEY" cus_replay
node pay.mjs "$KEY" cus_replayCheck it worked
retry.mjs now prints attempt 2: 201 (replayed) pay_... and ends with charges for cus_safe: 1. The first attempt still timed out, but the server finished that work and saved the result, so the retry got it back.
The two pay.mjs lines show the same payment ID. The first takes about 1.5 seconds and prints 201 pay_...; the second answers at once with 201 (replayed) pay_....
Step 5 · Reject reused keys and simultaneous duplicates
Keep the server running. A client bug that reuses one key for a different payment must not get someone else's receipt back. Send the key from the last step with a different amount:
node pay.mjs "$KEY" cus_replay 999The answer is 422 Idempotency-Key is already used. Now leave the key out:
node pay.mjs - cus_replayThat prints 400 Idempotency-Key is missing or invalid. Finally, fire two identical requests at the same moment with a fresh key, the way a double tap does. The & runs the first in the background:
KEY=$(node -p "crypto.randomUUID()")
node pay.mjs "$KEY" cus_twin & node pay.mjs "$KEY" cus_twin; waitCheck it worked
One line is 201 pay_... and the other is 409 A request with this Idempotency-Key is in progress, in either order. The 409 came back at once, while the first request was still waiting on the processor. That is the draft's answer for a concurrent duplicate: the client changes nothing, waits and retries, and then receives the saved response. curl -s 'http://127.0.0.1:3000/charges?customer=cus_twin' shows "charges":1.
Step 6 · Expire old keys
Keys cannot live forever: the table would grow without limit, and a stored response may hold data you should not keep. The store gives each key a time to live, 24 hours by default, counted from when its response was saved. claim treats an expired key as unused, and the server deletes expired rows every minute.
To see expiry happen, restart the server with a three-second time to live. Stop it with Ctrl+C and run:
IDEMPOTENCY_TTL_SECONDS=3 node server.mjsSend a payment, repeat it at once, wait past the time to live and repeat it again:
KEY=$(node -p "crypto.randomUUID()")
node pay.mjs "$KEY" cus_expiry
node pay.mjs "$KEY" cus_expiry
sleep 4
node pay.mjs "$KEY" cus_expiry
curl -s 'http://127.0.0.1:3000/charges?customer=cus_expiry'Check it worked
The first two lines share a payment ID, the second marked (replayed). The third line is a new 201 pay_... with a different ID, and the count is {"customer":"cus_expiry","charges":2}.
That second charge is the trade-off. After expiry, a retry is a new payment. Set the time to live longer than the longest time any client keeps retrying, including an app that retries a saved payment when it next opens, and publish the policy on the page your problem type points to. Stop this server with Ctrl+C before the next step.
Step 7 · Run a retry storm
Restart the server with the default 24-hour time to live:
node server.mjsCreate storm.mjs. It starts 25 clients at once, all sending the same payment with the same key. Each uses a random timeout between 0.8 and 1.6 seconds, so some give up before the 1.5-second processor answers, and each retries after a short random pause until it gets a 201. At the end it sends the key once more with a different body, then checks three things: every client got the same payment ID, the processor charged once, and the reused key got 422. It sets a failing exit code if any of them is wrong, so you can use it in CI:
cat > storm.mjs <<'JS'
import { randomUUID } from 'node:crypto';
const api = process.env.API ?? 'http://127.0.0.1:3000';
const clients = Number(process.argv[2] ?? 25);
// A new customer each run, so the charge count only covers this run.
const customer = `cus_storm_${Date.now()}`;
const key = randomUUID();
const body = JSON.stringify({ customer, amountMinor: 120000, currency: 'GHS' });
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
function post(payload, timeoutMs) {
return fetch(`${api}/payments`, {
method: 'POST',
headers: { 'content-type': 'application/json', 'idempotency-key': `"${key}"` },
body: payload,
signal: AbortSignal.timeout(timeoutMs),
});
}
// Each client keeps retrying the same payment, with a short, random timeout.
async function client(n) {
const seen = [];
for (let attempt = 1; attempt <= 15; attempt++) {
try {
const res = await post(body, Math.round(800 + Math.random() * 800));
const data = await res.json();
seen.push(res.status);
if (res.status === 201) return { seen, paymentId: data.id };
if (res.status !== 409 && res.status < 500) throw new Error(`client ${n}: unexpected ${res.status}`);
} catch (err) {
if (err.name !== 'TimeoutError') throw err;
seen.push('timeout');
}
await sleep(200 + Math.random() * 300);
}
throw new Error(`client ${n} gave up`);
}
const results = await Promise.all(Array.from({ length: clients }, (_, i) => client(i + 1)));
const tally = {};
for (const { seen } of results) for (const s of seen) tally[s] = (tally[s] ?? 0) + 1;
const paymentIds = new Set(results.map((r) => r.paymentId));
const reuse = await post(JSON.stringify({ customer, amountMinor: 1, currency: 'GHS' }), 5000);
const { charges } = await (await fetch(`${api}/charges?customer=${customer}`)).json();
console.log('responses:', tally);
console.log('distinct payment ids:', paymentIds.size);
console.log('same key, different body:', reuse.status);
console.log(`charges for ${customer}:`, charges);
const ok = paymentIds.size === 1 && charges === 1 && reuse.status === 422;
console.log(ok ? 'PASS: charged exactly once' : 'FAIL: see the numbers above');
if (!ok) process.exitCode = 1;
JS
node storm.mjsCheck it worked
The output is something like this. The response counts and the customer name change from run to run; the result does not:
responses: { '201': 25, '409': 117, timeout: 1 }
distinct payment ids: 1
same key, different body: 422
charges for cus_storm_1763541234567: 1
PASS: charged exactly onceRun node storm.mjs 100 for 100 clients. The result is still one charge.
Before you ship this
- Scope keys to the caller. Make the primary key
(account_id, key), so one client can never collide with, or read the saved response of, another. - Pass the key on. If your processor accepts its own idempotency key (Stripe does, on every
POST), send it a key derived from yours, so a crash between their charge and your commit cannot become a second charge either. - Run more than one server against shared storage. A SQLite file works for several processes on one machine. Across machines, put the table in PostgreSQL; the claim statement stays the same.
- A request stuck in
processingafter a crash blocks its key with409until it expires. Alert on oldprocessingrows and reconcile them against the processor.
Step 8 · Clean up
Stop the server with Ctrl+C in the second terminal. Then delete the demo folder, which holds the code and payments.db:
cd ~
rm -rf ~/idempotency-demoCheck it worked
ls ~/idempotency-demo reports that the folder does not exist, and curl http://127.0.0.1:3000/health fails to connect.
Next steps
- Make the calling side behave well too: call third-party APIs with timeouts and retries.
- Apply the same thinking to events you send: send webhooks with signatures and retries.
- Give every error body the same shape: return consistent API errors with Problem Details.
- Check which methods and status codes your endpoints use: design REST endpoints: resources, methods and status codes.
Part of these paths
Related tutorials
- Send webhooks with signatures, retries and backoffYou will build a Node.js 26 webhook sender that signs each delivery the Standard Webhooks way, keeps a queue and an attempt log in SQLite, retries failures with exponential backoff and jitter, gives up after a limit, and replays a delivery on request.
- Call third-party APIs reliably with timeouts, retries and a circuit breakerYou will build a reusable Node.js 26 API client that gives every request a deadline, retries only what is safe with backoff and jitter, honours Retry-After, stops calling a dead service with a circuit breaker and logs each attempt without leaking the API key.
- Design REST endpoints: resources, methods and status codesYou will design the endpoints of an event ticketing API on one page, build an Express 5 stub that follows it, and prove every status code in the design with curl.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials