Distributed SystemsVol. 5 · Part V
0 / 0

Shelves / Distributed Systems

DS·74

Idempotency

Making retries safe: idempotence defined mathematically and practically, naturally idempotent versus non-idempotent operations, HTTP method semantics, idempotency keys end to end (the Stripe model and the IETF Idempotency-Key header), storing and replaying responses, handling concurrent duplicates and mismatched payloads with request fingerprinting, unique constraints and conditional writes as deduplication, idempotent state transitions, idempotent message consumers, and calling third-party APIs safely. Implementations in Java, Go, Python, Rust and SQL.

26 topics · ~18 min read · 29-question quiz
Updated Suggest a correction

Start here: making retries safe

The retry that charges twice

A client calls POST /payments for ₹499. The card network is slow, the client's 200 ms timeout fires, and the client, seeing no answer, retries:

Text
1) POST /payments ₹499, client timeout 200 ms, then the client retries:
   attempt 1: timeout
   attempt 2: (201, {'id': 1, 'status': 'succeeded', 'amount': 499})
   charges in the database: (2, 998)

The first request wasn't lost; it was slow. It finished after the client gave up, so the retry charged the customer again. A timeout tells the client nothing about whether the server acted (the Start Here chapter's ambiguous timeout). Clients must retry to survive failures, so the server must make retries harmless: the operation must be idempotent, meaning that doing it twice has the same effect as doing it once.

Some operations are idempotent by nature

HTTP method Idempotent? Why
GET, HEAD Yes They don't change anything
PUT /users/7 {name: "Asha"} Yes Sets state; the second time sets the same state
DELETE /carts/42 Yes (by effect) Already gone the second time; the response may be 404
POST /payments No Each call creates something new
PATCH {balance: +100} No Relative changes accumulate

The fix for the others is to give each intended operation an identity that survives retries.

Idempotency keys

The client generates a unique key (a UUID) for each payment it means to make, and sends the same key on every retry. The server stores the key with the result; a repeat returns the stored result instead of acting again:

Python
row = c.execute("INSERT INTO idem_keys(key, request_hash, status) VALUES (%s, %s, 'started') "
                "ON CONFLICT DO NOTHING RETURNING key", (key, h)).fetchone()
if not row: …return the stored response (or 409 if still in progress, 422 if the body differs)…
with c.transaction():
    resp = charge(c, body)
    c.execute("UPDATE idem_keys SET status='done', response=%s WHERE key=%s", (json.dumps(resp), key))
Text
2) same, with header Idempotency-Key: 12364c11…
   attempt 1: timeout
   attempt 2: 201 {'id': 1, 'amount': 499, 'status': 'succeeded'}, Idempotent-Replayed: true
   charges in the database: (1, 499)
3) the same key with a different amount: 422 {'error': 'Idempotency-Key reused with a different request'}

The retry got the original response (the same charge ID), and the database held one charge. A key reused with a different body was rejected rather than silently replayed, because that's almost always a client bug. Stripe, Adyen, PayPal and most payment APIs work this way; the IETF has a draft standard for the Idempotency-Key header.

How deep to go in idempotency

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.

Level What you can do
L1 Explain idempotence, safe methods and why retries create duplicates
L2 Implement idempotency keys with stored responses, request fingerprints and expiry
L3 Handle concurrency, partial failure, recovery points and third-party idempotency
L4 Diagnose duplicate effects from retries, proxies, queues and double clicks
L5 Define retry and idempotency contracts across an API surface and its clients
L6 Set organisation-wide standards (headers, retention, SDK behaviour) and audit them

What idempotence means

Definition

In mathematics, f is idempotent if f(f(x)) = f(x): applying it twice equals applying it once. Absolute value, max(x, 5), and "set to 7" are idempotent; "add 1" isn't.

In distributed systems: an operation is idempotent if performing it multiple times has the same effect on system state as performing it once. (The response may differ: a second DELETE may return 404, but the state is the same.)

Why it's essential: chapter 65 showed that a timeout leaves the client not knowing whether the operation happened, and chapter 68 showed that at-least-once delivery causes duplicates. Retries are the only way to recover from ambiguity, and retries are only safe for idempotent operations.

Idempotency turns "at-least-once" into "effectively-once".

Natural idempotence

Operation Idempotent? Why
SET status = 'SHIPPED' WHERE id = 42 Yes Same final state
DELETE FROM carts WHERE id = 7 Yes Second delete finds nothing
UPSERT user {id: 9, email: …} Yes Overwrite with the same value
balance = balance - 100 No Each application subtracts again
INSERT INTO orders (…) with generated ID No Two orders created
Send email / SMS / push No Two messages delivered
Charge a card No Charged twice
x = x + 1 WHERE version = 5 then version = 6 Yes (conditionally) The second attempt fails the version check

The goal is to make every operation that may be retried idempotent, either by design (express it as setting state rather than applying deltas) or by deduplication (remember what was already done).

HTTP semantics

RFC 9110 defines method semantics:

Method Safe (no state change) Idempotent
GET, HEAD, OPTIONS, TRACE Yes Yes
PUT No Yes: replace the resource with this representation
DELETE No Yes
POST No No
PATCH No Not necessarily (JSON Merge Patch setting fields is; a "increment" patch isn't)

Clients, proxies and libraries automatically retry idempotent methods on connection failures (browsers, Envoy and gRPC retry policies, many HTTP clients). Declaring POST endpoints idempotent requires extra machinery: idempotency keys.

Design techniques for retry-safe APIs:

  • Client-generated IDs with PUT: PUT /orders/{client-generated-uuid} creates or replaces; a retry is naturally idempotent.
  • Conditional requests: If-Match: "etag" (optimistic concurrency, 412 Precondition Failed on mismatch) and If-None-Match: * (create only if absent). S3 supports both for writes since 2024.
  • State transitions instead of commands: POST /orders/42/cancel should succeed (or return the same result) if already cancelled.
  • Idempotency keys for POST operations that create things or have side effects.

Idempotency keys

The model

Popularised by Stripe, now an IETF draft (Idempotency-Key HTTP header, draft-ietf-httpapi-idempotency-key-header):

  1. The client generates a unique key (UUID v4/v7) per logical operation, before the first attempt, and sends it with every retry of that operation.
  2. The server records the key with the request fingerprint and, once done, the response.
  3. On a repeat with the same key, the server returns the stored response without re-executing.

The key identifies intent, not an HTTP request. A user clicking "Pay" once creates one key; network retries reuse it; clicking "Pay" again for a new purchase creates a new key.

client API server key store POST + key K lookup K absent → claim K (IN_PROGRESS, fingerprint) → execute → store 201 + body → return 201 COMPLETED, same fingerprint → return stored 201 (no re-execution) IN_PROGRESS → 409 Conflict (retry later) or wait for the first to finish COMPLETED/IN_PROGRESS, different fingerprint → 422: key reused for another request
Idempotency key lifecycle. The first request with key K claims it, executes the operation and stores the response. A retry with K returns the stored response. A concurrent duplicate while K is in progress gets 409 Conflict. A request reusing K with a different payload gets 422.

Design decisions

Decision Recommendation
Key scope Per client/account + endpoint: (api_key_id, key), so different clients can't collide or probe each other
Request fingerprinting Store a hash of the method, path and canonicalised body. A reused key with a different payload is a client bug: reject with 422 rather than return the wrong response
What to store Status code, response body (or the created resource's ID to re-render), important headers
Concurrent duplicates Claim the key atomically (INSERT … ON CONFLICT DO NOTHING, or SET NX); a second concurrent request gets 409 (Stripe's behaviour) or waits
Failures If execution fails before any side effect, release the key (delete or mark failed-retryable) so the client can retry. If it failed after partial side effects, the record must reflect that (recovery points, below)
Which responses to store Store final outcomes, including deterministic business errors (400, 402 declined). Don't store transient 5xx or 429 as final, so retries can succeed
Expiry Keep keys at least as long as clients may retry (Stripe: 24 hours); document it
Atomicity Store the key's completion in the same transaction as the business effect; otherwise a crash between them re-executes or loses the record

Recovery points for multi-step operations

When one API call does several things (local DB write, external charge, email), a crash mid-way must resume, not restart. Brandur Leach's design (from Stripe's architecture, described on brandur.org) stores a recovery point with the key:

  1. started, then local transaction 1 (create the payment row), then payment_created
  2. Call the external API with its own idempotency key derived from ours, then charge_created
  3. Enqueue email via the outbox, then finished

A retry with the same key resumes from the last recovery point. Each phase is either a local transaction (atomic) or an external call made idempotent by a derived key.

Implementations

-- SQL: idempotency key table (PostgreSQL)
CREATE TABLE idempotency_keys (
    account_id     bigint      NOT NULL,
    key            text        NOT NULL,
    request_hash   bytea       NOT NULL,
    status         text        NOT NULL CHECK (status IN ('in_progress', 'completed')),
    response_code  int,
    response_body  jsonb,
    recovery_point text        NOT NULL DEFAULT 'started',
    locked_at      timestamptz,
    created_at     timestamptz NOT NULL DEFAULT now(),
    PRIMARY KEY (account_id, key)
);
-- Claim atomically; RETURNING tells us whether we won
INSERT INTO idempotency_keys (account_id, key, request_hash, status, locked_at)
VALUES ($1, $2, $3, 'in_progress', now())
ON CONFLICT (account_id, key) DO NOTHING
RETURNING key;
-- Expire: DELETE FROM idempotency_keys WHERE created_at < now() - interval '24 hours';

Deduplication techniques

Unique constraints

The most robust deduplication is a unique constraint on the effect: the database enforces "this happened once" atomically with the write.

  • payments(idempotency_key UNIQUE), ledger_entries(source_event_id UNIQUE), emails_sent(campaign_id, user_id) UNIQUE.
  • On conflict, treat it as "already done": INSERT … ON CONFLICT DO NOTHING and look up the existing row.

Request fingerprinting

When clients don't send keys (legacy clients, webhooks, form posts), derive a fingerprint from the request: hash(account, endpoint, canonical body) within a short time window. Risky: two legitimate identical requests (buying the same item twice on purpose) would be merged. Use only with a short window and for operations where accidental duplicates are far more likely than intentional ones (double-submitted forms). Canonicalise JSON (sorted keys, normalised numbers) before hashing.

Deduplication windows and storage

  • Database table with TTL cleanup: strongest when in the same DB as the effect.
  • Redis SET key value NX EX 86400: fast filter, but not atomic with DB effects (chapter 68).
  • Broker-level: SQS FIFO deduplication ID (5 minutes), NATS Nats-Msg-Id, Azure Service Bus duplicate detection, Kafka idempotent producer (retries only).

Idempotent consumers

For message handlers (chapter 68):

  • Use the event ID as the dedup key, recorded in an inbox table in the same transaction as the effect.
  • Or make the effect idempotent: upserts, version-guarded updates (WHERE version < $new), set-based operations.
  • Derive downstream idempotency keys deterministically from the incoming message: charge_key = "order-" + orderId + "-charge", so a redelivered message calls the payment API with the same key.

Calling third parties

External APIs are the hardest part, because you can't put their effect in your transaction:

  1. Use their idempotency support if it exists (Stripe, Adyen, PayPal PayPal-Request-Id, most payment and messaging APIs). Pass a key derived from your operation's ID.
  2. Record intent before calling: write "charge requested with key K" in your DB, then call, then record the result. On recovery, an intent without a result means "outcome unknown": query the provider by key or reference, rather than calling again blindly.
  3. Reconciliation jobs: periodically compare your records with the provider's (settlement reports, list APIs) and fix discrepancies. Every payments system has one.
  4. Non-idempotent providers: serialise calls per entity, use their reference fields to look up prior attempts, and accept that a residual window of duplicate (or missed) side effects remains: decide which is worse.

Checklist for retry-safe APIs

  • Every non-GET endpoint is either naturally idempotent (PUT, DELETE, state transitions) or accepts an Idempotency-Key.
  • Keys are scoped per client, fingerprinted, stored atomically with the effect, and expire after a documented window.
  • Concurrent duplicates are handled (409 or wait), not executed twice.
  • Transient failures don't poison the key; deterministic outcomes are replayed.
  • Downstream calls carry derived keys.
  • Consumers deduplicate by event ID or apply idempotent effects.
  • Clients retry with exponential backoff and jitter, a retry budget, and the same key (Vol. 3 ch. 52).

Lab: an idempotent payments API under retries

The book's payments API (Python ThreadingHTTPServer, psycopg 3 connection pool, PostgreSQL 16), with an idem_keys table (key primary key, request hash, status, stored response). A client with a 150 ms timeout and exponential backoff (50, 100, 200, 400 ms; up to five attempts).

Experiment 1: retries against a sometimes-slow server

200 payments; 20% of charges take 200 ms inside the server, so the client times out on those and retries:

Text
no key:          46 retries, 246 charges
Idempotency-Key: 70 retries, 200 charges

Without keys, every timeout became an extra charge: 46 customers paid twice. With keys there were more retries (a retry arriving while the first attempt was still running got 409 Conflict and retried again) and exactly 200 charges. Retries are what make a system reliable, and they're only safe when the server is idempotent; Google's SRE book and AWS's Builders' Library both treat "retry with backoff and jitter" and "idempotent APIs" as one design.

Experiment 2: duplicates in flight at the same time

50 payments, each sent twice at the same instant with the same key (a double-click, or a proxy retrying while the first is still running); charges take 200 ms:

Text
responses {409: 50, 201: 50}, charges 50

The INSERT … ON CONFLICT DO NOTHING on the key's primary key admitted exactly one request per key; the other found the key started and got 409 with Retry-After, so a well-behaved client waits and then receives the replayed result. A check with SELECT first would race exactly like chapter 68's experiment 2.

Experiment 3: what the key store costs

1,000 sequential payments:

Text
without an idempotency key: median 1.38 ms
with an idempotency key:    median 2.33 ms
idempotency keys stored: 1000 rows, 384 kB

The key insert and the final update added about 1 ms here (two extra statements, one of them a separate commit). Keys must expire: Stripe keeps them for 24 hours. Partition the table by day or delete old rows on a schedule, and size it as requests per day × row size.

What this design doesn't cover yet

  • Crash between steps: the key is committed as started before the charge; if the server process dies there, the key stays started and every retry gets 409. Production designs record recovery points (Brandur Leach's write-up of Stripe's approach) or expire started keys after a timeout, after checking whether the downstream effect happened.
  • Third-party calls: the charge here is a row; a real card network call can't join the database transaction. Pass your own idempotency key to the provider (most payment APIs accept one), or record intent first and reconcile against the provider's records.
  • Scope: keys should be scoped per account ((account_id, key)), so one customer can't replay another's response.

Try it yourself

  1. Kill the server with SIGKILL in the middle of a slow charge, restart it, and retry. Implement expiry for stale started keys.
  2. Add per-account scoping to the key's primary key and test cross-account replay.
  3. Put an Nginx or Envoy proxy with proxy_next_upstream retries in front and count duplicates without keys.
  4. Make PATCH /balance idempotent by turning it into PUT with an expected version (If-Match).

Revision sheet: idempotency

Key ideas

  • Idempotence: f(f(x)) = f(x); for systems, repeating a request has no extra effect. Safety (no side effects) is stronger.
  • HTTP (RFC 9110): GET, HEAD, OPTIONS, TRACE safe; PUT and DELETE idempotent; POST and PATCH not.
  • Why it matters: retries on timeouts, at-least-once queues, proxies and load balancers, double clicks, mobile networks.
  • Idempotency keys: client-generated per intended operation; server stores key, request fingerprint, status and response; replay, 409 for in-progress, 422 for mismatched body; expiry (often 24 h); scoped per account.
  • Natural idempotence: PUT with full state, conditional updates (If-Match/ETags, version columns), upserts, set semantics, unique constraints on business IDs.
  • Dedup techniques: unique constraints, inbox tables, broker windows, bloom filters for large streams (with false positives), TTL caches.
  • Third parties: forward your key, use their idempotency features, record intent and reconcile.
  • Crash safety: atomic phases, recovery points, expiry of in-progress keys.

Numbers to remember

  • Lab: 46 of 200 payments doubled without keys under timeouts; 0 with keys; concurrent duplicates gave 50 × 201 and 50 × 409 with 50 charges; key handling cost about 1 ms per request; 1,000 keys took 384 kB.

Pitfalls

  • Generating a new key on each retry (it must be per intended operation).
  • Storing "seen" without the response.
  • SELECT-then-INSERT key checks.
  • Keys never expiring, or expiring before clients stop retrying.
  • Unscoped keys shared across accounts.
  • Assuming PUT is idempotent when the handler appends or increments.

Glossary

  • Idempotent: repeated application has the same effect as one.
  • Safe method: has no side effects on the server.
  • Idempotency key: client-chosen operation identifier.
  • Request fingerprint: hash of the request body used to detect key reuse.
  • Recovery point: stored progress marker for a multi-step request.
  • Replay: returning a stored response for a duplicate request.