How to Design Idempotent APIs
Design idempotency keys that survive retries: tenant scoping, atomic claims, concurrent requests, retention, and tests against duplicate effects.
On this page
Introduction
Retries are normal for every network client, load balancer, and queue. A client times out after the server committed a payment, retries, and now two payments exist. Idempotency makes repeated attempts harmless: the same logical operation produces one final state and ideally the same response.
GET, HEAD, PUT, and DELETE are idempotent by HTTP specification; POST is not. The real work happens on POST-like operations such as creating a payment. A client-supplied idempotency key is the usual tool, but the header is easy. Scoping the key, coordinating it with the business transaction, handling concurrent retries, and defining the guarantee window are hard.
What Idempotency Actually Guarantees
Idempotency is about effects, not transport. Sending the same request twice still runs handler code twice; what must not happen is two charges. The guarantee is conditional: it holds for a defined operation, key namespace, and retention window. After that window, the server no longer remembers the first attempt and a retry is a new operation.
It is also not exactly-once delivery. Queues generally provide at-least-once delivery, and idempotency reduces the effect to at-most-once within the deduplication window. Exactly-once is a property of a closed transactional system, not a header spanning a database, a payment provider, and an email service.
The trade-offs are real. Every keyed request needs an extra write and usually a stored response body, adding latency, storage cost, and sensitive data to protect. Apply keys where duplicates are expensive, and prefer natural idempotency where it exists: an UPSERT, a unique constraint, or a state machine that accepts only valid transitions.
Choosing and Scoping Keys
The client should generate a random key, typically a UUID, once per logical operation and reuse it only when retrying that payload. Deriving the key from the body is a mistake: two intentional identical purchases would collapse into one.
Scope the key to the authenticated tenant. A global namespace lets customers collide and can expose another tenant’s response. Use (tenant_id, idempotency_key) as the primary key, validate format and maximum length, and treat keys as opaque. Fingerprint the request — method, route, and a canonical body hash — to distinguish a retry from key reuse with different data.
Keep keys at least as long as any proxy, client, or queue may retry. Payment APIs commonly use 24 hours; internal job APIs may need days. Longer windows cost more storage and retain more personal data, so delete expired rows on a schedule and document the exact guarantee.
Claiming Work Atomically
Use the database’s unique constraint as the arbiter, never a check-then-insert in application code. The key table stores one row per tenant and key, the request fingerprint, the attempt state, and the response needed for replay.
CREATE TABLE idempotency_keys (
tenant_id text NOT NULL,
key text NOT NULL,
fingerprint text NOT NULL,
state text NOT NULL CHECK (state IN ('in_progress', 'completed')),
response_status integer,
response_body jsonb,
claimed_at timestamptz NOT NULL DEFAULT now(),
completed_at timestamptz,
PRIMARY KEY (tenant_id, key)
);
The claim is a single INSERT ... ON CONFLICT DO NOTHING. If it inserts, this request owns the work. If not, inspect the existing row: a different fingerprint is a client error, an in-progress row means another request is working, and a completed row is replayed with its stored status and body.
async function claim(pool: Pool, tenant: string, key: string, fingerprint: string) {
const inserted = await pool.query(
`INSERT INTO idempotency_keys (tenant_id, key, fingerprint, state)
VALUES ($1, $2, $3, 'in_progress')
ON CONFLICT (tenant_id, key) DO NOTHING
RETURNING state`,
[tenant, key, fingerprint],
);
if (inserted.rowCount === 1) return { kind: "claimed" as const };
const { rows } = await pool.query(
`SELECT fingerprint, state, response_status, response_body
FROM idempotency_keys WHERE tenant_id = $1 AND key = $2`,
[tenant, key],
);
const row = rows[0];
if (!row) return { kind: "retry" as const };
if (row.fingerprint !== fingerprint) return { kind: "mismatch" as const };
if (row.state !== "completed") return { kind: "in_progress" as const };
return {
kind: "replay" as const,
status: row.response_status as number,
body: row.response_body as unknown,
};
}
Complete the row in the same transaction as the business write. If the payment and key records commit together, there is no window in which the effect exists without the record. On failure, roll back both and remove the claim so a retry can genuinely attempt the operation. An external provider cannot join the transaction; record the intent, pass a deterministic provider key, and reconcile asynchronously.
Concurrent Retries and Stale Claims
Two requests with the same key can arrive together. The unique constraint lets one claim succeed; the other sees in_progress. Return 409 Conflict with Retry-After rather than a 500 or a fake success, and let the client retry to receive the stored response.
Stale claims are harder. A process can crash after inserting the claim but before completing the work, leaving in_progress forever. A sweeper may mark old claims abandoned, but not while the original worker is merely slow, or two workers will run concurrently. Store an owner identifier and heartbeat long operations, or keep operations short enough that a fixed timeout is safe.
For external side effects, add a second defense. Give the payments table a unique (tenant_id, idempotency_key) constraint and derive the provider’s key from the same operation. If the process dies after the charge but before the local row completes, reconciliation can query the provider instead of charging again.
Failure Modes and Retention
Reusing a key with a different payload is the most common bug. Reject it with 422 and never overwrite the original result; otherwise one operation silently disappears. Store the exact response and version its shape as the API evolves.
Expiry is a guarantee boundary. If a key is deleted after an hour but a queue retries after two, a duplicate is possible. Derive the window from the maximum retry horizon, not convenience. Replication also matters: if the key table is strongly consistent only on the primary and a failover promotes an asynchronous replica, recent keys can vanish.
Do not cache 5xx responses permanently; transient failures should be retryable. Protect stored responses like the underlying data, and monitor mismatch, stale-claim, and replay rates; a rise signals a client bug or an aggressive retry policy.
Testing, Limitations, and When Not to Bother
Use the real database, because the guarantee depends on a unique constraint and transaction isolation. Test sequential duplicates, concurrent duplicates, the same key with a different body, a crash between claim and completion, tenant isolation, and behavior after the retention window. Concurrent duplicates should yield one success, one conflict, and one effect; a replay should match the original body.
Keys do not make an operation safe forever, cannot roll back an external effect, and do not replace authorization. For naturally idempotent PUT and DELETE endpoints, a key adds little. Generic middleware that wraps every POST rarely understands transaction boundaries or long-running jobs. Prefer a small explicit mechanism: a tenant-scoped key, a fingerprint, an atomic claim, a stored outcome, and a documented retention window. That makes retries boring.
Sources: RFC 9110: HTTP Semantics, The Idempotency-Key HTTP Header Field, Stripe: Idempotent requests.
FAQ
- Should idempotency keys be generated by the client or the server?
- The client must generate the key because only it knows that two attempts represent the same logical operation. A server-generated key would differ on every retry and could not deduplicate anything.
- How long should an idempotency key be retained?
- Keep it at least as long as any client, proxy, or queue may retry the request. Payment APIs often retain keys for 24 hours; choose a window based on your retry policy and document that a retry after expiry can create a second effect.
- Does an idempotency key guarantee exactly-once processing?
- No. It provides at-most-once effect within the retention window when the claim, business write, and stored response are coordinated correctly. Outside that window, or when an external side effect cannot be rolled back, duplicates remain possible.
Report a problem with this articleOpens a pre-filled issue on GitHub.