Idempotency keys are supposed to make retries safe: the client sends the same key on every attempt, and the server runs the operation once and replays the saved response after that. Most implementations keep the keys in Redis, next to the API, while the operation itself writes to a database. If the server crashes after the database write and before the key is updated, the two disagree.
In my guide to idempotency in APIs with Node.js, I build an idempotent() wrapper for Express with an in-memory store and then a Redis store, and I mention this gap near the end: if the server dies after the work but before the response is saved, a retry can run the work again. This article picks up from there. I reproduce the double charge for real, and then close the gap by putting the key and the payment in the same PostgreSQL transaction.
Everything below was run with Node.js 24.21, Express 5.3.0, pg 8.23.1, the redis package 6.3.1, Redis 8.10.2 and PostgreSQL 18.6 (both in Docker), on Windows 11 with Git Bash, in November 2026. The output is copied from those runs.
The setup
I took the code from the guide as is: idempotency.js with the idempotent(store, handler) wrapper, redis-store.js with SET ... NX and a 60-second processing lock, and the client.js that retries with the same key. The only change is that payments now go to a real table instead of an array:
CREATE TABLE payments ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), amount integer NOT NULL, status text NOT NULL, created_at timestamptz NOT NULL DEFAULT now() ); npm i express pg redis db.js creates a connection pool:
import pg from 'pg' export const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL }) And createPayment() inserts the row, then does something slow, like sending the receipt email. To get a crash at exactly the wrong moment, I added a line that kills the process right after the INSERT when an environment variable is set. In real life this is a deploy, an out-of-memory kill or a pod being rescheduled:
async function createPayment(db, amount) { const { rows } = await db.query( `INSERT INTO payments (amount, status) VALUES ($1, 'succeeded') RETURNING id, amount, status`, [amount], ) if (process.env.CRASH_AFTER_INSERT) process.exit(1) // simulate a crash await sleep(2000) // e.g. send the receipt email return rows[0] } app.post( '/payments', idempotent(redisStore, async (req) => { const payment = await createPayment(pool, req.body.amount) return { status: 201, body: payment } }), ) Reproducing the double charge
I started the server with the crash flag and sent one request:
$ CRASH_AFTER_INSERT=1 node server-redis.js $ curl -sS -X POST http://localhost:3000/payments \ -H "Content-Type: application/json" \ -H "Idempotency-Key: 7f9c2b1e-3d4a-4c6b-9e8f-1a2b3c4d5e6f" \ -d '{"amount":4999}' curl: (56) Recv failure: Connection was reset The client got no answer. Here's what the crash left behind:
$ docker exec idem-pg psql -U postgres -c 'SELECT id, amount, status FROM payments' id | amount | status --------------------------------------+--------+----------- 3a1df61b-7a8c-4efe-a3ec-3b432f1ffb0c | 4999 | succeeded (1 row) $ docker exec idem-redis redis-cli GET "idem:POST:/payments:7f9c2b1e-3d4a-4c6b-9e8f-1a2b3c4d5e6f" {"state":"processing","fingerprint":"2a9171e9d44f62b0d98368f20620dd1b0d7392d541b497bc93286e56789c6265"} $ docker exec idem-redis redis-cli TTL "idem:POST:/payments:7f9c2b1e-3d4a-4c6b-9e8f-1a2b3c4d5e6f" (integer) 59 The payment exists, but Redis still thinks the request is in progress, and it will keep thinking so for 59 more seconds. I restarted the server normally and retried with the same key:
HTTP/1.1 409 Conflict {"error":"A request with this key is in progress"} So far, so good: the wrapper did its job. Then I waited for the lock to expire and retried again:
HTTP/1.1 201 Created {"id":"778a7a30-4b1b-4835-b0ce-f7c4411ac898","amount":4999,"status":"succeeded"} $ docker exec idem-pg psql -U postgres -c 'SELECT id, amount, status FROM payments' id | amount | status --------------------------------------+--------+----------- 3a1df61b-7a8c-4efe-a3ec-3b432f1ffb0c | 4999 | succeeded 778a7a30-4b1b-4835-b0ce-f7c4411ac898 | 4999 | succeeded (2 rows) That's two payments for one idempotency key. The lock expiration that frees a key after a crash is what lets the work run twice. The code does what it was written to do, but Redis and Postgres can't commit together, so the key says "not done" while the database says "done".
Put the key in the same database
If the operation's side effects are writes to your own Postgres, the fix is to store the key there too and do everything in one transaction: claim the key, insert the payment, save the response, commit. If the process dies at any point before COMMIT, Postgres rolls back all of it, the key included. A retry then finds no key and no payment, and runs normally.
The table for the keys:
CREATE TABLE idempotency_keys ( key text PRIMARY KEY, fingerprint text NOT NULL, status integer, body jsonb, created_at timestamptz NOT NULL DEFAULT now() ); status and body stay NULL until the request finishes. And pg-idempotency.js, a new wrapper with the same checks as the guide's (400 without a key, 422 for a different body, replay with Idempotent-Replayed):
import { createHash } from 'node:crypto' export function idempotentTx(pool, handler) { return async (req, res) => { const key = req.get('Idempotency-Key') if (!key) { return res.status(400).json({ error: 'Missing Idempotency-Key header' }) } const storeKey = `idem:${req.method}:${req.path}:${key}` const fingerprint = createHash('sha256') .update(JSON.stringify(req.body ?? null)) .digest('hex') const db = await pool.connect() try { await db.query('BEGIN') // claim the key: a duplicate waits here until the first transaction ends const claim = await db.query( `INSERT INTO idempotency_keys (key, fingerprint) VALUES ($1, $2) ON CONFLICT (key) DO NOTHING`, [storeKey, fingerprint], ) if (claim.rowCount === 0) { await db.query('ROLLBACK') const { rows } = await db.query( 'SELECT fingerprint, status, body FROM idempotency_keys WHERE key = $1', [storeKey], ) const saved = rows[0] if (saved.fingerprint !== fingerprint) { return res .status(422) .json({ error: 'Idempotency-Key reused with a different body' }) } res.set('Idempotent-Replayed', 'true') return res.status(saved.status).json(saved.body) } // the handler writes with the same connection, in the same transaction const { status, body } = await handler(req, db) await db.query( 'UPDATE idempotency_keys SET status = $2, body = $3 WHERE key = $1', [storeKey, status, body], ) await db.query('COMMIT') res.status(status).json(body) } catch (err) { await db.query('ROLLBACK') throw err } finally { db.release() } } } The important detail is that the handler receives db, the connection that holds the transaction, and must use it for its writes. If it used pool.query(), the payment would be committed on another connection, outside the transaction, and we'd be back to two systems that commit separately.
The route only changes the wrapper and passes db along:
app.post( '/payments', idempotentTx(pool, async (req, db) => { const payment = await createPayment(db, req.body.amount) return { status: 201, body: payment } }), ) Notice there's no processing state anymore, and no lock with an expiration time. The uncommitted row is the lock, and it disappears when the transaction ends, whether it commits or the connection dies.
The same crash, again
Same test, same flag, a new key:
$ curl -sS -X POST http://localhost:3000/payments \ -H "Content-Type: application/json" \ -H "Idempotency-Key: 0d8f6a52-91c4-4b1e-a7d3-5e2f8c9b4a10" \ -d '{"amount":4999}' curl: (56) Recv failure: Connection was reset $ docker exec idem-pg psql -U postgres -c 'SELECT count(*) FROM payments' -c 'SELECT key, status FROM idempotency_keys' count ------- 0 (1 row) key | status -----+-------- (0 rows) The INSERT into payments ran, but it was never committed. When the process died, its connection closed and Postgres threw the transaction away, so neither the payment nor the key exists. I restarted the server and retried with the same key, twice:
HTTP/1.1 201 Created {"id":"e20ea825-9f99-4caf-9dfc-3c0d30fe4fa5","amount":4999,"status":"succeeded"} HTTP/1.1 201 Created Idempotent-Replayed: true {"id":"e20ea825-9f99-4caf-9dfc-3c0d30fe4fa5","amount":4999,"status":"succeeded"} One payment in the table. The same key with {"amount":9900} returns 422 Unprocessable Entity, like in the guide. And no waiting for a lock to expire: the retry worked right after the restart.
What happens to a concurrent retry
With the Redis store, a retry that arrives while the first request is still running gets 409 right away, and the client has to try again later. With Postgres, the second INSERT ... ON CONFLICT DO NOTHING sees a row with the same key that isn't committed yet, so it can't know whether that row will exist or not. It waits. When the first transaction commits, the INSERT does nothing and the wrapper replays the saved response. If the first one rolls back, the INSERT goes through and the retry does the work itself.
I sent request A, and request B with the same key 300 ms later:
A: HTTP 201 after 2.054941s B: HTTP 201 after 1.744528s B didn't get a 409. It sat there for about 1.7 seconds and then got A's response. The guide's retrying client shows the same thing: attempt 2 used to get 409, and now it gets the payment:
$ node client.js http://localhost:3000/payments Attempt 1 failed: The operation was aborted due to timeout Attempt 2: HTTP 201 { id: '7a45d43e-6fbc-43cf-a16c-1e0c1d5a284a', amount: 4999, status: 'succeeded' } For short operations that's nicer for the client. For long ones it's a problem: every waiting duplicate holds a connection from the pool, and pg.Pool has 10 by default. A client stuck in a retry loop could use up the pool by itself.
If you'd rather keep the 409, tell Postgres how long to wait. lock_timeout cancels a statement that waits too long for a lock, with SQLSTATE 55P03. SET LOCAL limits it to the current transaction:
await db.query('BEGIN') await db.query("SET LOCAL lock_timeout = '500ms'") } catch (err) { await db.query('ROLLBACK') if (err.code === '55P03') { // lock_timeout: the first request still holds the key return res .status(409) .json({ error: 'A request with this key is in progress' }) } throw err } Same test:
B: HTTP 409 after 0.517783s A: HTTP 201 after 2.048949s And the guide's client is back to the behavior from the Redis version:
$ node client.js http://localhost:3000/payments Attempt 1 failed: The operation was aborted due to timeout Attempt 2 failed: HTTP 409 Attempt 3: HTTP 201 { id: '59522393-3398-4728-852b-29b6d2ce1ddb', amount: 4999, status: 'succeeded' } What this doesn't cover
- Side effects outside your database. A transaction can roll back rows, not a card charge at a payment provider or an email that was already sent. For those, pass the same key to the provider (the guide shows how with Stripe), and keep slow external calls out of the transaction, since the connection is held for as long as the transaction is open.
- Cleanup. Postgres doesn't expire rows on its own. You need a scheduled job that deletes keys older than your retention window (24 hours is common), using
created_at. - Scoping. As in the guide, put the user or account ID in
storeKey, or two clients that happen to send the same key will see each other's responses.
Wrapping up
With the key and the work in one transaction:
- A crash before
COMMITleaves nothing behind, so a retry runs the operation once, right away, with no lock to wait out. - A duplicate that arrives during the first request waits and gets the same response, or gets a
409if you setlock_timeout. - The "processing" state and its expiration time are gone, because the uncommitted row does that job.
The trade-off is that it only works when the side effects live in the same database as the keys. When they don't, it doesn't matter where the keys live: you still need to pass the key downstream. The concepts this builds on (idempotent HTTP methods, the Idempotency-Key header draft, the fingerprint check and the Redis store) are in my step-by-step guide to idempotency keys in Node.js.
