Full answer
Why it is needed
- A client sends POST /payments and the connection times out. Did the server process it? The client cannot know. A blind retry may charge twice. The key makes the retry safe.
Implementation
- Client generates a key per logical operation (one per payment attempt, reused for retries of it).
- Server inserts a row (key, request hash, status) with a unique constraint on the key, in the same transaction as the business change.
- If the insert succeeds, do the work, store the response (status and body) in the same row, commit, and respond.
- If the key exists with the same request hash: return the stored response (many APIs add a replay header). If the stored response is not ready yet, the original request is still running: wait for it or answer 409.
- If the key exists with a different request hash: answer 422 (the key was reused for something else).
- Expire keys after a window (24 hours is common).
Details
- Scope keys per user or API client.
- Doing the key insert and the business change in one transaction removes the crash window where one exists without the other.
- Safe by nature: GET, PUT and DELETE do not need keys. POST and PATCH may.
- For calls to other systems, pass your own key on to them, such as a payment provider.
javascript
const { Client } = require('pg');
const crypto = require('node:crypto');
(async () => {
const db = new Client(); await db.connect();
await db.query(`DROP TABLE IF EXISTS bk36_idem; DROP TABLE IF EXISTS bk36_payments;
CREATE TABLE bk36_payments (id serial PRIMARY KEY, amount int NOT NULL);
CREATE TABLE bk36_idem (key text PRIMARY KEY, request_hash text NOT NULL, response jsonb)`);
async function createPayment(key, body) {
const hash = crypto.createHash('sha256').update(JSON.stringify(body)).digest('hex');
await db.query('BEGIN');
const claimed = await db.query('INSERT INTO bk36_idem (key, request_hash) VALUES ($1, $2) ON CONFLICT DO NOTHING RETURNING key', [key, hash]);
if (claimed.rowCount === 1) { // first time we see this key: do the work
const { rows } = await db.query('INSERT INTO bk36_payments (amount) VALUES ($1) RETURNING id', [body.amount]);
const response = { status: 201, body: { id: rows[0].id, amount: body.amount } };
await db.query('UPDATE bk36_idem SET response = $2 WHERE key = $1', [key, response]);
await db.query('COMMIT');
return { ...response, replay: false };
}
const { rows } = await db.query('SELECT request_hash, response FROM bk36_idem WHERE key = $1', [key]);
await db.query('COMMIT');
if (rows[0].request_hash !== hash) return { status: 422, body: { error: 'idempotency key reused with a different request' } };
return { ...rows[0].response, replay: true };
}
const show = (label, r) => console.log(label.padEnd(30), r.status, JSON.stringify(r.body), r.replay === undefined ? '' : 'replay=' + r.replay);
show('first request, key k-1', await createPayment('k-1', { amount: 500 }));
show('retry after a timeout, k-1', await createPayment('k-1', { amount: 500 }));
show('same key, different amount', await createPayment('k-1', { amount: 900 }));
show('new key k-2', await createPayment('k-2', { amount: 500 }));
console.log('payments stored (not 4):', (await db.query('SELECT count(*)::int AS n FROM bk36_payments')).rows[0].n);
await db.query('DROP TABLE bk36_idem; DROP TABLE bk36_payments');
await db.end();
})();Runs on the local PostgreSQL. The key claim and the payment are in one transaction. Concurrent requests with the same key are covered in the next item. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): first request, key k-1 201 {"id":1,"amount":500} replay=false retry after a timeout, k-1 201 {"id":1,"amount":500} replay=true same key, different amount 422 {"error":"idempotency key reused with a different request"} new key k-2 201 {"id":2,"amount":500} replay=false payments stored (not 4): 2
Key points
- The client sends a unique key and reuses it when retrying.
- The server stores key, request hash and response.
- Same key and same request: return the stored response.
- Same key and different request: 422.
- Store the key in the same transaction as the work.
Common mistakes
- Generating a new key on every retry.
- Storing the key outside the transaction of the work.
- Not comparing the request body with the stored one.
- Letting keys live forever.
- Using the key for a different user's request (no scoping).
Follow-ups
- How long should keys be kept?
- What does Stripe return for a replayed request?
- How do you make a webhook consumer idempotent?
Tips
- Open with the timeout problem.
- Walk through insert, work, store, replay.
- Mention 422 for mismatches.