How to Implement Idempotency Keys
Make retried requests safe by storing a client-supplied key and replaying the original result instead of performing the work twice.
On this page
Introduction
Networks drop responses, clients time out, and load balancers retry. When a write is retried after its response was lost, the server may perform the same operation twice: two charges, two orders, two emails. Making the operation idempotent means that repeating it with the same key produces the same result as the first attempt, without repeating the side effect. An idempotency key is the standard technique: the client sends a unique key with the request, the server records the key and the result, and any later request with the same key gets the recorded result back. This article shows how to store and replay keys safely, including the concurrency and expiry traps.
Why Retries Duplicate Work
A retry is unavoidable because a request can fail after the server has processed it but before the response reaches the client. The client sees a timeout and cannot tell whether the write happened. Retrying is correct behaviour, but without a deduplication key the server has no way to recognize the retry and processes it as a new request. The result is a duplicate side effect, which for a payment means charging twice.
Idempotency removes the ambiguity. The client generates a key once per logical operation, and reuses it for every retry. The server, on seeing a key it has already handled, returns the stored result instead of doing the work again. The client’s timeout no longer risks a duplicate, and the retry becomes safe to perform automatically.
Client-Supplied Idempotency Keys
The key must come from the client, generated per logical operation and stable across retries. A server-generated key cannot help, because the retry is a new request and would get a new key. Use a random UUID or a value the client derives deterministically from the operation’s own identity, such as an order id it already has. Send it in a header, conventionally Idempotency-Key, so it is independent of the request body.
Scope the key: the same key should be meaningful only within one client or tenant and one operation type. A key from client A must not collide with a key from client B, or one client would receive another’s result. Include the tenant in the key or in the lookup, and store the operation identity alongside so a key reused for a different operation can be rejected rather than answered with the wrong result.
Persisting the Key and Result
Store the key, the request fingerprint, the response body and status, and a timestamp, in a durable store. The store must enforce uniqueness on the key so two concurrent requests cannot both start the operation. A unique index on the key column is what makes the second request fail its insert and therefore know to wait for or read the first request’s outcome.
CREATE TABLE idempotency_keys (
key text PRIMARY KEY,
tenant_id uuid NOT NULL,
request_hash text NOT NULL,
status text NOT NULL DEFAULT 'in_progress', -- in_progress | done
response_body jsonb,
response_code int,
created_at timestamptz NOT NULL DEFAULT now(),
expires_at timestamptz NOT NULL
);
-- Reject a concurrent duplicate: the second insert fails on the primary key.
INSERT INTO idempotency_keys (key, tenant_id, request_hash, expires_at)
VALUES ($1, $2, $3, now() + interval '24 hours')
ON CONFLICT (key) DO NOTHING
RETURNING key;
Replaying a Cached Response
The request flow has three cases. If the key is new, run the operation and store the result. If the key exists and is done, replay the stored status and body without running the operation. If the key exists and is in progress, another request is mid-flight: either wait a short time and re-check, or return a conflict telling the client to retry. The third case is what stops two concurrent requests from both performing the write.
async function handleWithIdempotency(key, tenantId, request, operation) {
const hash = digest(JSON.stringify(request));
const inserted = await db.query(
`INSERT INTO idempotency_keys (key, tenant_id, request_hash, expires_at)
VALUES ($1,$2,$3, now() + interval '24 hours')
ON CONFLICT (key) DO NOTHING RETURNING key`,
[key, tenantId, hash],
);
if (inserted.rowCount === 0) {
const existing = await loadKey(key, tenantId);
if (existing.request_hash !== hash) throw new Conflict('key reused for a different request');
if (existing.status === 'in_progress') throw new Retry_('in progress, retry shortly');
return { status: existing.response_code, body: existing.response_body }; // replay
}
const result = await operation();
await saveResult(key, result);
return result;
}
Key Scope, Expiry and Concurrency
Keys must expire or the table grows without bound. Choose a retention longer than any client’s retry window, typically a day, and delete expired rows on a schedule. Expiring too soon reintroduces the duplicate: a retry after expiry looks like a new request. Expiring too late wastes storage but is safe, so err on the long side.
Handle the in-progress case explicitly, because it is where correctness lives. If a key is claimed but the first request crashes before storing its result, the key is stuck in progress forever and every retry gets told to try later. Add a lease: an in-progress key has a deadline, and if the lease expires the key can be reclaimed and the operation retried. Record enough that a reclaimed key does not double-charge; for payments, make the operation itself idempotent at the provider as the final backstop.
Common Mistakes
The most common mistake is scoping the key too broadly or too narrowly, causing either cross-tenant collisions or accidental new keys on every retry. The second is not storing the request fingerprint, so a client reusing a key for a different body gets the first body’s response silently. The third is treating in-progress as done, which lets a concurrent duplicate through. The fourth is not expiring keys, which grows the table forever.
A fifth is relying on idempotency keys for operations that are not the same each time, such as a request whose body legitimately changes; the fingerprint check catches this and must reject it. Finally, keep the key out of URLs and logs where it could leak or be guessed, and never trust a client-provided key as authorization; it identifies an operation, not a user.
Conclusion
Idempotency keys make retries safe by letting the server recognize a repeat and replay the original result. Let the client generate a stable key per operation, scope it to the tenant and operation type, store it with a unique constraint and the request fingerprint, replay the stored response for duplicates, handle the in-progress case with a lease, and expire keys on a schedule longer than the retry window. Reject a key reused for a different request rather than answering with the wrong result. Then a dropped response costs a harmless retry instead of a duplicate charge.
Sources: Stripe: idempotent requests, Idempotency key pattern, RFC 9110: Idempotent methods.
FAQ
- Where should the idempotency key be generated?
- On the client, once per logical operation and reused for every retry. A server-generated key cannot help, because each retry arrives as a new request and would receive a new key. Use a UUID or a value derived from the operation identity.
- How long should idempotency keys be retained?
- Longer than the longest retry window any client might use, which is typically a day. Expiring too soon reintroduces the duplicate because a late retry looks like a new request; expiring too late only costs storage, so prefer the longer side.
Report a problem with this articleOpens a pre-filled issue on GitHub.