How to implement Idempotency-Key in a Node.js API with PostgreSQL
By David Garcia Berenguer · Published 2026-10-30 · Updated 2026-10-30 · Markdown version
Short answer: the client sends an Idempotency-Key header, the same one on every retry. The server claims the key with one atomic database statement, runs the handler once, stores the response, and replays it to every retry. Concurrent duplicates get 409, a key reused for a different request gets 422, transient failures release the key, and a lease lets a retry take over from a request that crashed.
The bug it fixes
A client sends POST /payments. The server charges the card, then the connection drops before the 201 arrives. The client can't tell "never arrived" from "done but unanswered", so it retries, and the customer pays twice. Double-clicks, mobile networks, load balancer retries and SDK auto-retries all produce the same shape.
The lifecycle of a keyed request
parse key ─▶ fingerprint request ─▶ claim key (atomic) ─┬─ claimed ───▶ run handler ─┬─ final status ─▶ store ─▶ respond
│ └─ 5xx/408/429/throw ─▶ release
├─ completed ─▶ replay stored response
├─ in progress ─▶ 409 + Retry-After
└─ different request ─▶ 422
Six details implementations get wrong
1. The lock must be the database
if (!(await exists(key))) { run(); save(); } lets two concurrent requests both run. Claim the key in one statement on a primary key of (scope, key):
insert into idempotency_keys as r (scope, idem_key, fingerprint, status, lock_token, locked_until, expires_at)
values ($1, $2, $3, 'in_progress', $4, now() + interval '30 seconds', now() + interval '24 hours')
on conflict (scope, idem_key) do update set
fingerprint = excluded.fingerprint, status = 'in_progress', lock_token = excluded.lock_token,
locked_until = excluded.locked_until, expires_at = excluded.expires_at
where r.expires_at <= now() -- an expired key starts over
or (r.status = 'in_progress' and r.locked_until <= now()
and r.fingerprint = excluded.fingerprint) -- a crashed request is taken over by its own retry
returning lock_token;
Exactly one concurrent request gets a row back. The others read the row to learn why they lost: finished, still running, or a different request.
2. Fingerprint the request, not just the key
Clients reuse keys by mistake (one per page instead of one per checkout). If you only look at the key, a $99 order can receive the $49 order's response. Store a SHA-256 of method, path and query, and the exact body bytes, and answer 422 on a mismatch.
3. Scope keys per user
Keys are client-generated, not secrets. Without a namespace, user B sending user A's key receives user A's response. Make the primary key (scope, key) with the user or tenant id as the scope.
4. Leases survive crashes
A request killed mid-way can't release its key. Give the claim a locked_until; while it's in the future, retries get 409. After it passes, the next retry of the same request takes over. Make the lease longer than your slowest handler.
5. Ownership tokens stop stale writers
After a takeover, the original slow request may still finish and overwrite the retry's result. Write a random token on each claim and only accept complete from the token that still owns the row.
6. Store final answers only, and fail closed
- Store 2xx, 3xx and 4xx: a validation error or a declined card won't change on retry.
- Release on 5xx, 408, 429 or a thrown error: those mean "try again".
- Never replay
Set-Cookie: a retry must not receive a session minted for another moment. - If the store is down, answer
503and don't run the handler. Running without the lock is exactly the double execution you set out to prevent.
What no HTTP layer can promise
A request that crashes after its side effect and before its response is stored will run again on retry. Close that gap by passing the key downstream: as Stripe's own Idempotency-Key on the charge, or as a unique column on the row you insert.
Implementing it in TypeScript
Idempotent Requests is this design in about 640 lines of strict TypeScript with zero runtime dependencies, a PostgreSQL store, and a client that retries with the same key:
import { Pool } from "pg";
import { createIdempotency, idempotentFetch, PostgresStore } from "@softreuse/idempotency-kit";
export const idempotency = createIdempotency({
store: new PostgresStore(new Pool({ connectionString: process.env.DATABASE_URL })),
leaseMs: 30_000, // longer than your slowest request
});
// app/api/orders/route.ts
export async function POST(request: Request) {
const userId = await currentUserId(request);
return idempotency.handle(request, { scope: userId }, async (req, { idempotencyKey }) => {
const order = await createOrder(await req.json(), idempotencyKey); // runs once per key
return Response.json(order, { status: 201 });
});
}
// browser: one key per operation, reused on every retry
await idempotentFetch("/api/orders", { method: "POST", body: JSON.stringify(order) }, { key: crypto.randomUUID() });
Errors use application/problem+json (RFC 9457), as the IETF draft recommends. Its tests include twelve concurrent claims with exactly one winner, crash takeover, stale writers and cross-user replay, run against a real PostgreSQL.
Checklist
- Key required on the endpoints that create things (payments, orders, signups).
- Atomic claim on
(scope, key), fingerprint check,409while running,422on mismatch. - Lease longer than the slowest handler; ownership token on completion.
- Final answers stored, transient ones released,
Set-Cookienever replayed. - Fail closed when the store is down.
- Keys passed downstream; expired keys purged daily.
Sources
Frequently asked questions
What is an Idempotency-Key?
A unique value the client sends in the Idempotency-Key header to name one operation. The server runs the operation once for that key and returns the stored response to every retry. Stripe popularised it, and the IETF HTTPAPI working group is standardising the header.
Should the client or the server generate the idempotency key?
The client, once per operation (for example, once per checkout, not once per click), and it must send the same key on every retry of that operation. A random UUID is fine.
What should the server return for a request that is still running?
409 Conflict with a Retry-After header. Running it again would defeat the purpose, and the first request's answer isn't ready yet.
What if a client reuses a key with a different body?
Answer 422. Store a fingerprint (a hash of method, path and body) with the key; if a later request with the same key has a different fingerprint, returning the stored response would silently answer the wrong request.
Should I store 500 errors for an idempotency key?
No. 5xx, 408 and 429 mean try again; storing them turns a transient failure into a permanent one. Release the key so the retry runs. Do store final answers such as 201, 400 or a declined card's 402.
How long should idempotency keys be kept?
At least as long as clients retry. 24 hours is common and is what Stripe documents; purge older keys with a daily job.