A timeout does not tell you whether the request failed. The server may have finished the work and lost the response on the way back. If the client retries, the work happens twice: two orders, two charges, two emails. An idempotency key lets the server recognise the retry and return the first result instead.
The contract#
The client generates a unique key per logical operation and sends it with every attempt. The server guarantees that, for a given key, the operation runs at most once and every attempt gets the same answer.
- Same key, same payload: return the stored result.
- Same key, different payload: reject it. The client has a bug.
- Same key while the first attempt is still running: tell the client to retry later.
The table#
CREATE TABLE idempotency_keys (
key text PRIMARY KEY,
scope text NOT NULL, -- e.g. 'create-order'
request_hash text NOT NULL,
status text NOT NULL DEFAULT 'started',
response jsonb,
created_at timestamptz NOT NULL DEFAULT now(),
CHECK (status IN ('started', 'completed'))
);The primary key does the hard work. Two concurrent attempts cannot both insert the same key; the database decides which one wins.
Claiming the key#
async function withIdempotency<T>(
db: Db,
key: string,
scope: string,
payload: unknown,
work: (tx: Tx) => Promise<T>,
): Promise<{ status: number; body: T | { error: string } }> {
const requestHash = sha256(stableStringify(payload));
const claimed = await db.query(
`INSERT INTO idempotency_keys (key, scope, request_hash)
VALUES ($1, $2, $3)
ON CONFLICT (key) DO NOTHING
RETURNING key`,
[key, scope, requestHash],
);
if (claimed.rowCount === 0) {
const existing = await db.one(
"SELECT request_hash, status, response FROM idempotency_keys WHERE key = $1",
[key],
);
if (existing.request_hash !== requestHash) {
return { status: 422, body: { error: "Key reused with a different request" } };
}
if (existing.status === "started") {
return { status: 409, body: { error: "Request in progress, retry shortly" } };
}
return { status: 200, body: existing.response as T };
}
return db.transaction(async (tx) => {
const result = await work(tx);
await tx.query(
"UPDATE idempotency_keys SET status = 'completed', response = $2 WHERE key = $1",
[key, result],
);
return { status: 201, body: result };
});
}The business write and the completed update share one transaction, so a crash can never record a result for work that did not commit.
Side effects outside the database#
The transaction protects your own tables. It cannot un-send an email or un-call a payment API. For those:
| Side effect | Approach |
|---|---|
| Third-party API that accepts idempotency keys | Pass a key derived from yours, so their retry protection lines up with your own |
| Email, notifications | Write an outbox row in the transaction; a worker sends it and marks it sent |
| Webhooks you emit | Same outbox, with the event ID in the payload so receivers can deduplicate |
Keys for incoming webhooks#
When you are the receiver, the provider's event or delivery ID is the key. The same table works; the scope is the provider name. Store the ID before doing the work, not after, or a crash halfway through will process the event twice on redelivery.
Housekeeping#
Keys only need to outlive the client's retry window. A scheduled job that deletes completed rows older than a few days keeps the table small. Document that window in the API, so clients know how long a key protects them.