Idempotency
Every network can lose a response. When it does, the client cannot tell “it never arrived” from “it arrived and the answer was lost”. The only safe reaction is to retry, and the only way to retry safely is to make the operation idempotent.
The 60-second answer
Section titled “The 60-second answer”An operation is idempotent if repeating it has the same effect as performing it once. HTTP methods have this property by definition —
GET,PUT,DELETEare idempotent,POSTis not. For unsafe operations the client sends anIdempotency-Key; the server stores the key with a fingerprint of the request and the response it produced, and replays that response on retry instead of doing the work again. Exactly-once delivery is not achievable across a network; what you build is at-least-once delivery plus idempotent processing, which is effectively once.
Why retries are mandatory
Section titled “Why retries are mandatory”A client that does not retry loses work on transient failures. A client that retries blindly duplicates work. Neither is acceptable for anything involving money, inventory, or state transitions.
Failure modes that produce ambiguity:
- Timeout waiting for the response: the server may have committed.
- Connection reset mid-response.
- Load balancer returns
502after the origin processed the request. - The client’s own process is killed between send and read.
In all of them, the operation’s outcome is unknown. Retry plus idempotency is the only resolution.
Natural idempotency
Section titled “Natural idempotency”Prefer designing operations that are idempotent without extra machinery:
| Operation | Idempotent? | How |
|---|---|---|
PUT /users/42 {name:"Ana"} |
Yes | Full replace; same body, same result |
DELETE /users/42 |
Yes | Second call returns 404 or 204, state unchanged |
SET status = 'shipped' |
Yes | Absolute assignment |
UPDATE balance = balance - 100 |
No | Relative change |
INSERT INTO orders (...) |
No | Each call creates a row |
POST /orders with a generated id |
Yes | The id makes the retry a duplicate you can detect |
Three techniques that make writes naturally idempotent:
- Client-generated identifiers. The client picks the UUID; a duplicate insert fails on the primary key and you return the existing record.
- State machines.
POST /orders/42/shiptransitionspaid → shipped. A second attempt seesshippedand returns success without side effects. - Upserts.
INSERT ... ON CONFLICT (id) DO UPDATEconverges regardless of repetition.
Absolute assignments beat relative ones. If you must have a counter, make increments distinguishable (an event id per increment) so duplicates can be rejected.
Idempotency keys
Section titled “Idempotency keys”The standard for POST endpoints (Stripe popularised it).
POST /v1/payments HTTP/1.1Idempotency-Key: 3f0c2b1e-9a4d-4f7e-8b21-6d5c4a3e2f10Content-Type: application/json
{"amount_cents": 4200, "currency": "BRL", "customer_id": 42}Server algorithm:
1. key := header, scoped to (account_id, endpoint)2. row := SELECT * FROM idempotency_keys WHERE account_id=? AND key=?3. if row is null: INSERT (account_id, key, request_hash, state='processing', expires_at=now()+24h) -- unique constraint on (account_id, key) makes concurrent duplicates fail here result := perform_operation() UPDATE row SET state='completed', status_code=?, response_body=? return result4. if row.state = 'completed': if row.request_hash != hash(body): return 422 (key reused with different payload) return row.status_code, row.response_body -- replay, do not redo5. if row.state = 'processing': return 409 with Retry-AfterThe schema:
CREATE TABLE idempotency_keys ( account_id bigint NOT NULL, key text NOT NULL, request_hash bytea NOT NULL, state text NOT NULL, -- processing | completed status_code int, response_body jsonb, created_at timestamptz NOT NULL DEFAULT now(), expires_at timestamptz NOT NULL, PRIMARY KEY (account_id, key));Details that matter and are usually missed:
- Scope by principal. A global key space lets one tenant block another’s key or read its stored response.
- Store the response, not just the fact. A retry must return the same body and status; otherwise a client that timed out gets a different answer than the one already recorded.
- Fingerprint the request. Reusing a key with different content is a client bug; returning the
original response silently would be worse than a
422. - Concurrency. The unique constraint is what makes two simultaneous identical requests safe. Do not check-then-insert without it.
- TTL. Long enough to outlive plausible retries (24h is common), then expire. Growing forever is a bill and a privacy problem.
- Do not hold a transaction open for the whole operation. Insert, commit, do the work, then
update — and accept that a crash leaves a
processingrow to clean up.
Exactly-once is not a thing
Section titled “Exactly-once is not a thing”The two-generals problem: two parties cannot agree on a message delivery over an unreliable channel with certainty. Any protocol that retries on missing acknowledgement can duplicate; any protocol that does not retry can lose.
So:
- At-most-once: send and forget, or ack before processing. Loses work.
- At-least-once: retry until acknowledged. Duplicates.
- Exactly-once: only inside a single system that controls both the commit of the input and the output — Kafka transactions, a database with a dedupe table.
Cross-system, you build effectively once: at-least-once delivery plus deduplication at the consumer.
Kafka’s exactly-once semantics (enable.idempotence, transactions, read_committed) make
produce-and-commit atomic within Kafka. If your consumer then writes to Postgres and calls a
payment API, that boundary is gone.
Deduplication patterns
Section titled “Deduplication patterns”Unique constraint on a business key. Cheapest and most reliable.
INSERT INTO payments (id, charge_id, amount_cents)VALUES ($1, $2, $3)ON CONFLICT (charge_id) DO NOTHING;Processed-events table keyed by event id, written in the same transaction as the effect:
BEGIN;INSERT INTO processed_events (event_id) VALUES ($1) ON CONFLICT DO NOTHING;-- if 0 rows inserted, ROLLBACK and skipUPDATE accounts SET balance_cents = balance_cents + $2 WHERE id = $3;COMMIT;The transaction is what makes it correct: the dedupe marker and the effect commit together.
Dedupe window / cache. A Redis SET NX with a TTL catches duplicates in a short window. It is
fast but not durable — a Redis restart loses the marker. Use it as a first line, with a durable
constraint behind it.
Naturally idempotent effects. Setting a value is idempotent; incrementing is not. Prefer “set status to X” over “increment state”.
Retry policy
Section titled “Retry policy”Idempotency makes retries safe; backoff makes them survivable.
- Exponential backoff with jitter: base 100ms, factor 2, cap 30s, full jitter. Without jitter, all clients retry in lockstep and create a second spike.
- Bounded attempts with a deadline. Infinite retries turn an outage into a permanent load.
- Retry only what is retryable: network errors,
429,502,503,504. Never retry a400,401,403,404or422. - Respect
Retry-After. Ignoring it is the fastest way to be banned. - Circuit breakers stop retrying a dependency that is clearly down, so recovery is possible.
- A retry budget. Cap retries at a fraction of total traffic (e.g. 10%) so a partial outage does not double your request volume.
Follow-up questions
Section titled “Follow-up questions”- Two identical
POST /paymentsarrive at the same millisecond. Walk me through the database. - Why store the response body rather than just a “done” flag?
- What happens if the process crashes between the operation and the key update?
- How do you make a Kafka consumer that writes to Postgres effectively-once?
- Is
DELETEidempotent if the second call returns 404? - How long should an idempotency key live, and what governs that?
Common traps
Section titled “Common traps”- “We will dedupe by request id.” Only if the client sends the same id on retry. Server-generated ids differ per attempt.
- “Exactly-once is a configuration option.” It is a property of one system’s boundary. Cross it and you are at-least-once.
- “Retries are safe because TCP.” TCP guarantees ordered delivery on one connection. A retry after a timeout is a new request, and the first one may have succeeded.
- “The key is unique globally.” It must be scoped per account, or tenants collide.
- “We can hold the row lock for the whole operation.” That serialises every retry behind a slow request and exhausts the connection pool.