Skip to main content

Idempotency & Exactly-Once

Learning objectives
  • Define at-most-once, at-least-once and exactly-once, and explain why exactly-once delivery is impossible over an unreliable network
  • Design an idempotency-key API: key scope, storage, TTL, fingerprinting, concurrent duplicates and response replay
  • Use natural idempotency and dedup tables to make consumers safe under redelivery
  • Explain what Kafka's idempotent producer and transactions do — and what they do not cover
  • Implement idempotency middleware in Go and know where it is not enough

TL;DR​

  • Over a network, a sender cannot tell "request lost" from "response lost". So you either risk losing the operation (at-most-once) or risk doing it twice (at-least-once). There is no third option for delivery.
  • Exactly-once = at-least-once delivery + idempotent processing. The effect happens once even if the message arrives many times.
  • Idempotency keys: the client generates one key per logical operation (not per attempt) and sends it on every retry. The server stores key → request fingerprint, status and response, and replays the stored response for duplicates.
  • Handle the hard parts: concurrent duplicates (one wins, the other gets 409 or waits), key reuse with a different body (422), crashes mid-request (leases and recovery), TTL (≈ 24 hours or longer, matched to your clients' retry window).
  • Prefer natural idempotency where possible: conditional updates, upserts keyed by business IDs, unique constraints. They protect you even when the key layer fails.
  • Kafka idempotent producer removes duplicates caused by producer retries within a partition; Kafka transactions make read-process-write within Kafka atomic. Neither covers your database or an external PSP.

Why it matters​

A customer taps "Pay $120" in your app on a train. The request reaches your API, the card is charged, and the response is lost when the train enters a tunnel. The app times out and retries. Without idempotency, the customer is charged $240 — and they will call the bank, not you.

Duplicates come from everywhere:

  • Mobile clients and SDKs retrying on timeout.
  • API gateways, service meshes and load balancers with retry policies.
  • Users double-clicking "Place order" or refreshing a confirmation page.
  • Message consumers redelivering after a crash or rebalance.
  • Saga orchestrators resuming after a restart.
  • PSPs and partner banks resending webhooks until you return 2xx.

In payments and checkout, idempotency is not an optimization; it is the property that lets you safely use retries at all, and retries are how every resilient system recovers from transient failures (see Resilience Patterns). Expect interviewers at banks and marketplaces to ask for the full design, including the concurrent-duplicate case.

Core concepts​

Delivery semantics​

SemanticsMechanismFailure outcomeExample
At-most-onceSend once, no retry; or ack before processingOperation may be lostMetrics, best-effort notifications
At-least-onceRetry until acknowledged; ack after processingOperation may be applied more than onceAlmost all reliable messaging
Exactly-once (effect)At-least-once + idempotent or deduplicated processingApplied once, even if delivered many timesPayments, ledger posting, order creation

The impossibility of exactly-once delivery is a version of the Two Generals problem: no finite number of acknowledgements makes both sides certain. "Exactly-once" in product marketing always means exactly-once processing within a defined boundary — and the boundary is the important part of the claim.

Natural idempotency​

An operation is idempotent if applying it twice has the same effect as applying it once. Design for it first:

  • Set, don't increment: UPDATE orders SET status = 'PAID' WHERE id = $1 AND status = 'PENDING' is idempotent; UPDATE wallet SET balance = balance + 120 is not.
  • Conditional transitions: state machines that only move forward ignore repeated or late events.
  • Upsert by business key: INSERT ... ON CONFLICT (payment_id) DO NOTHING.
  • Unique constraints as the last line of defence: a ledger table with UNIQUE (transfer_id, leg) cannot contain a duplicate posting, no matter how many times the code runs.
  • Client-chosen IDs: if the client creates transfer_id (a UUID) and the server inserts it, a retry hits the unique constraint instead of creating a second transfer. HTTP PUT /transfers/{id} is idempotent by design.

When the operation is not naturally idempotent — "charge this card", "send this transfer" — you add idempotency keys.

Idempotency keys​

Design decisions:

  • Who generates the key: the client, once per logical operation, persisted with the pending operation so it survives app restarts. A UUIDv4 (or v7) is typical. The server can also issue the key up front (see "Server-issued keys" below).
  • Scope: keys are unique per client or merchant (scope, key), never globally — otherwise one merchant's key can collide with or probe another's. Derive the scope from the authenticated principal, never from the request body.
  • Fingerprint: store a hash of method, path and body. A retry with the same key but a different body (different amount!) is a client bug — reject it (the IETF draft on the Idempotency-Key header suggests 422) rather than replaying an unrelated response.
  • What to store: status (IN_PROGRESS, COMPLETED), response code and body, timestamps, and a lease (locked_until) for in-progress requests.
  • What to replay: final outcomes — success (2xx) and deterministic business failures (402/422 such as "insufficient funds"). Do not permanently store transient failures (5xx, timeouts); release the key so the client can retry.
  • TTL: long enough to cover the client's full retry window, including offline mobile clients. Stripe documents that keys can be pruned after 24 hours; banks often keep them longer for money movement, or rely on a permanent unique transfer_id behind the key.

The key's lifecycle​

Concurrent duplicates​

Two identical requests arrive within milliseconds (double-click, aggressive client retry). Both look up the key and find nothing. Without care, both execute.

  • Make "claim the key" atomic: INSERT with a primary key on (scope, key) — exactly one insert succeeds. Redis SET key value NX PX ttl works as a fast pre-filter but is not atomic with your database transaction.
  • The loser sees IN_PROGRESS and either returns 409 Conflict with Retry-After (Stripe's behavior for concurrent requests with the same key), or waits briefly for the winner to finish and then replays. Some references use 429 Too Many Requests instead, including the payment chapter of System Design Interview Vol. 2. Stripe answers 409 (as of 2026, verify). Either works if the API documents it and clients treat it as "retry later with the same key".
  • Crashed winners: if the process holding the key dies, the key would stay IN_PROGRESS forever. A lease (locked_until) lets a later retry take over — but only safely if the work itself is resumable or naturally idempotent.

Server-issued keys​

Client-generated keys need a client you control. The alternative is for the server to mint the key before the user commits. The hotel reservation design in System Design Interview Vol. 2 works this way (see Ch 7 · Hotel Reservation System). When it renders the review page, the reservation service takes a fresh id from a global ID generator (see Unique ID Generation) and embeds it in the form. The submit inserts the reservation with that id as its primary key, so a second submit violates the unique constraint and the service returns the existing reservation.

AspectClient-generated keyServer-issued key
Round tripsNone extraThe page or form must be fetched first
Clients it suitsApps and SDKs you control, which can persist the keyPlain HTML forms, simple partner integrations
Where duplicates are stoppedA key table with fingerprint and stored responseA unique constraint on the business table itself
After a page refreshSame key, if the client stored itA reloaded page mints a new id, so a submit from it counts as a new operation

The refresh row is the catch: a user who reloads the review page and submits again gets a second reservation unless something else catches it, such as a short hold or a check for an identical pending booking. Expire issued ids along with the page, and answer a duplicate submit with the original result rather than an error.

Storage: where the key lives matters​

WhereAtomic with side effect?Notes
Same database and transaction as the business writeYesStrongest. Key row, payment row and outbox row commit together
Separate database / RedisNoFast and decoupled, but a crash between "effect" and "mark completed" can re-run the effect; needs natural idempotency underneath
Gateway-level idempotencyNoGood for blocking duplicate traffic early; must not be the only protection for money

When the operation calls an external system (a PSP), you cannot make the call atomic with your database. Handle it with recovery points (an approach described well by Brandur Leach for Stripe-like keys in PostgreSQL): persist "about to call PSP" with the derived PSP key, make the call, persist the result. On retry after a crash, resume from the last recovery point and call the PSP again with the same derived key — the PSP's own idempotency makes the repeated call safe.

Propagating keys downstream​

One logical operation fans out: authorize at the PSP, post to the ledger, emit events. Derive child keys deterministically (k1:authorize, k1:ledger) or use stable business IDs (payment_id). Most major PSPs accept idempotency keys on payment-creating calls; use them.

In a checkout this gives two layers of keys, and each stops a different duplicate:

LayerTypical keyWhat it stops
Client → your APIThe cart or checkout id, or a UUID the app creates when checkout startsDouble-clicks, and client or gateway retries reaching your API
Your service → PSPYour payment order or attempt id, sent as the PSP's idempotency key. In hosted-page flows, the nonce you register with, which the PSP maps to its tokenA charge retried after a lost PSP response, including retries by a recovery worker

Don't pass the client's key straight through to the PSP. One checkout can split into several payment orders (one per seller), and a genuine new attempt after a decline needs a fresh PSP key, so derive PSP keys from your own payment or attempt ids. See Payments & Card Flows and Ch 11 · Payment System.

Dedup tables for consumers​

For messages, the "key" is the event ID. The consumer inserts (consumer, event_id) into a dedup (inbox) table in the same transaction as its side effect and skips on conflict; it commits its broker offset only after the database transaction. See Transactional Outbox & CDC. Retain entries longer than the maximum redelivery horizon (broker retention, replay windows).

Kafka: idempotent producer and transactions​

Idempotent producer (enable.idempotence=true, the default since Kafka 3.0): the broker assigns the producer an ID, the producer numbers each batch per partition, and the broker discards batches it has already written. This eliminates duplicates and reordering caused by producer retries, per partition, per producer session. It does not deduplicate two separate Send calls your application makes for the same business event.

Transactions (transactional.id set): a producer can atomically write to several partitions and commit consumer offsets (sendOffsetsToTransaction). Consumers with isolation.level=read_committed only see committed transactional messages. A new producer instance with the same transactional.id fences off "zombie" predecessors via an epoch. Together these give exactly-once read-process-write within Kafka — the model behind Kafka Streams processing.guarantee=exactly_once_v2.

# producer
enable.idempotence=true
acks=all
transactional.id=fx-rates-enricher-0

# consumer
isolation.level=read_committed
enable.auto.commit=false

What it does not cover: writing to PostgreSQL, calling a PSP, sending an email. If your consumer's side effect is outside Kafka, you are back to at-least-once delivery plus your own idempotent processing.

Trade-offs​

OptionStrengthsWeaknessesChoose when
Natural idempotency (conditional writes, unique constraints)Always on; no extra store; survives bugs in higher layersNot every operation can be expressed this wayAlways, as the base layer
Idempotency keys in the same DB transactionAtomic; replay exact responsesCouples key storage to the service database; table growthMoney-moving APIs: payments, transfers, payouts
Idempotency keys in RedisFast; offloads DBNot atomic with effects; eviction loses keysPre-filtering high-volume duplicates; paired with DB constraints
Gateway-level idempotencyCentral, reusableCannot know business semantics; not atomic with effectsPlatform-wide duplicate suppression for retries
Consumer dedup tableSimple, reliable for messagesStorage grows; needs the same DB as the side effectEvent consumers with database side effects
Kafka transactionsExactly-once within Kafka pipelinesKafka-only; latency of transaction commits; operational subtletyStream processing: enrichment, aggregation, Kafka-to-Kafka

In practice​

Key table (PostgreSQL):

CREATE TABLE idempotency_keys (
scope text NOT NULL, -- merchant or client ID from auth
idem_key text NOT NULL,
fingerprint text NOT NULL, -- sha256 of method, path, body
status text NOT NULL, -- IN_PROGRESS, COMPLETED
response_code int,
response_body bytea,
locked_until timestamptz,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (scope, idem_key)
);
-- Purge with a scheduled job or daily partitions, e.g. keep 7 days for payments.

Begin is INSERT ... ON CONFLICT DO NOTHING RETURNING ...; if nothing is returned, read the existing row. If it is IN_PROGRESS with an expired lease and the same fingerprint, take it over with a conditional UPDATE ... WHERE locked_until < now().

Go middleware sketch:

package idem

import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"io"
"log/slog"
"net/http"
"time"
)

type Record struct {
Fingerprint string
Status string // "IN_PROGRESS" or "COMPLETED"
StatusCode int
Body []byte
}

type Store interface {
// Begin atomically claims (scope, key) or returns the existing record.
Begin(ctx context.Context, scope, key, fp string, lease time.Duration) (rec Record, claimed bool, err error)
Complete(ctx context.Context, scope, key string, code int, body []byte) error
Release(ctx context.Context, scope, key string) error
}

func Middleware(store Store, scopeOf func(*http.Request) string, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
key := r.Header.Get("Idempotency-Key")
if key == "" || len(key) > 255 {
http.Error(w, "valid Idempotency-Key header required", http.StatusBadRequest)
return
}
body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
if err != nil {
http.Error(w, "cannot read body", http.StatusBadRequest)
return
}
r.Body = io.NopCloser(bytes.NewReader(body))

h := sha256.New()
io.WriteString(h, r.Method+" "+r.URL.Path+"\n")
h.Write(body)
fp := hex.EncodeToString(h.Sum(nil))
scope := scopeOf(r) // authenticated client, never from the body

rec, claimed, err := store.Begin(r.Context(), scope, key, fp, 30*time.Second)
if err != nil {
http.Error(w, "try again", http.StatusServiceUnavailable)
return
}
if !claimed {
switch {
case rec.Fingerprint != fp:
http.Error(w, "key reused with a different request", http.StatusUnprocessableEntity)
case rec.Status == "COMPLETED":
w.Header().Set("Idempotent-Replayed", "true")
w.WriteHeader(rec.StatusCode)
_, _ = w.Write(rec.Body)
default:
w.Header().Set("Retry-After", "1")
http.Error(w, "request in progress", http.StatusConflict)
}
return
}

rw := &recorder{ResponseWriter: w, status: http.StatusOK}
next.ServeHTTP(rw, r)

ctx := context.WithoutCancel(r.Context()) // finish bookkeeping even if client left
if rw.status >= 500 {
_ = store.Release(ctx, scope, key)
return
}
if err := store.Complete(ctx, scope, key, rw.status, rw.buf.Bytes()); err != nil {
slog.ErrorContext(ctx, "idempotency: complete failed", "key", key, "err", err)
}
})
}

type recorder struct {
http.ResponseWriter
status int
buf bytes.Buffer
}

func (r *recorder) WriteHeader(code int) {
r.status = code
r.ResponseWriter.WriteHeader(code)
}

func (r *recorder) Write(b []byte) (int, error) {
r.buf.Write(b)
return r.ResponseWriter.Write(b)
}

Where this sketch is not enough: Complete runs after the handler's own transaction, so a crash between them (or a 5xx after the effect committed) lets a retry re-run the handler. For money movement, the handler itself must be safe to re-run: write the key's COMPLETED record in the same transaction as the payment row, and/or rely on a unique payment_id derived from the key. Treat middleware as a convenience layer, not the guarantee.

Rough sizing: 2,000 payment requests/s with 7-day retention ≈ 1.2 billion rows. Partition the key table by day and drop old partitions; keep the primary key index in memory for the hot day.

Common pitfalls​

  • New key per retry. The client generates the key inside the retry loop. Symptom: duplicates exactly when the network is flaky — idempotency did nothing.
  • Global key namespace. Merchant A's key collides with merchant B's, returning B's response to A. A data-leak and correctness bug.
  • No fingerprint check. A client bug reuses a key for a different amount and silently gets the old response. Symptom: "payment succeeded" for an amount that was never charged.
  • Caching 5xx responses. A transient database error becomes a permanent failure for that key.
  • Non-atomic check-then-insert. SELECT the key, then INSERT if missing. Symptom: duplicates under concurrent double-clicks.
  • Idempotency only at the gateway. The gateway's store and the service's database disagree after a crash; duplicates reach the ledger. Always back it with natural idempotency.
  • Assuming Kafka exactly-once covers the database. Symptom: duplicate rows from a consumer that "uses transactions".
  • TTL shorter than the retry window. An offline mobile client retries after two days and creates a second transfer.

Interview angle​

  • Typical prompt: "The client times out on a payment request and retries. How do you avoid double charging?" or "Design an idempotent transfer API."
  • Strong answer covers: client-generated key per logical operation; scope by client; fingerprint; atomic claim via unique constraint; replay of stored final responses; 409 for concurrent in-flight duplicates; release on transient failure; lease for crashed workers; TTL matched to retry window; derived keys to the PSP; natural idempotency (unique transfer_id in the ledger) underneath; consumers with dedup tables.
  • Follow-ups: "Where do you store keys and why?" "What if the server crashes after charging the PSP but before saving?" (recovery points + PSP idempotency key). "Is Kafka exactly-once enough?" "What does 'exactly-once' even mean here?"
  • Red flags: "we use exactly-once delivery"; check-then-insert without a constraint; ignoring concurrent duplicates; idempotency in Redis only for a ledger.

Self-check​

1. Why is exactly-once delivery impossible, and what do systems that claim it actually provide?

The sender cannot distinguish a lost request from a lost response, so it must either give up (possible loss) or retry (possible duplicate). Systems that claim exactly-once provide exactly-once processing within a boundary: at-least-once delivery plus deduplication or idempotent application, such as Kafka transactions within Kafka or an inbox table within one database.

2. What must an idempotency-key record store, and why the fingerprint?

Scope and key, a fingerprint of the request, status (in progress or completed), the final response code and body, a lease for in-progress work, and timestamps for TTL. The fingerprint detects a key reused with a different request — replaying the old response would tell the client an unrelated operation succeeded.

3. Two requests with the same key arrive 5 ms apart. Walk through what happens.

Both try to insert the key row; the primary key on (scope, key) lets exactly one succeed. The winner proceeds. The loser reads the existing record: it is IN_PROGRESS with a matching fingerprint, so it returns 409 with Retry-After (or waits briefly). When the client retries after the winner completes, it gets the stored response replayed.

4. The server charged the PSP and crashed before saving the result. How does a retry avoid a double charge?

Before calling the PSP, the server persisted a recovery point with a derived PSP idempotency key (e.g., k1:charge). The retry finds the key in progress with an expired lease, resumes at that recovery point, and calls the PSP again with the same derived key. The PSP recognizes it and returns the original charge instead of creating a new one; the server then saves the result and completes.

5. What does Kafka's idempotent producer prevent, and what doesn't it prevent?

It prevents duplicates and reordering caused by the producer's internal retries of the same batch to a partition, by sequence-numbering batches per producer ID. It does not prevent the application from calling Send twice for the same business event, and it doesn't make consumer side effects idempotent.

6. Give three ways to make a ledger posting consumer naturally idempotent.

A unique constraint on (transfer_id, leg) in the entries table; INSERT ... ON CONFLICT DO NOTHING keyed by the event or transfer ID; a dedup (inbox) table written in the same transaction; and conditional state transitions on the transfer row (WHERE status = 'PENDING').

7. Which responses should be replayed for a repeated key, and which should not?

Replay final outcomes: successful creations and deterministic business errors (insufficient funds, validation failures). Do not store transient failures such as 5xx or timeouts as final; release the key so the client's retry can execute. Otherwise a brief outage permanently fails those operations.

8. When would you have the server issue the idempotency key instead of the client, and what is the catch?

When you don't control the client (plain web forms, simple partner integrations), or when you want the key to double as the business id. The server mints an id from a global ID generator when it renders the confirmation step and uses it as the primary key, so a duplicate submit hits a unique constraint. The catch: it costs an extra round trip, and reloading the page mints a new id, so a submit after a refresh counts as a new operation unless another check catches it.

🧠 Flashcards0/10 learned · 0 retries

Exercise​

Implement and attack an idempotent transfer API:

  1. POST /transfers in Go with PostgreSQL: keys stored in the same transaction as the transfer row and its outbox event; fingerprinting; replay; 409 for in-flight duplicates; lease takeover.
  2. Add a fake PSP with its own idempotency (map of keys) and recovery points before and after calling it.
  3. Write a load script that sends each logical transfer 1–5 times, concurrently and with random delays, and kills the server process at random points.
  4. Verify with SQL that every logical transfer produced exactly one transfer row, one PSP charge and one pair of ledger entries.

Done when: 10,000 logical transfers under chaos produce zero duplicates and zero losses, and you can point to the line of code (or constraint) that prevents each duplicate source.

Further reading​

  • Brandur Leach, "Implementing Stripe-like Idempotency Keys in Postgres" (brandur.org, 2017).
  • Stripe API documentation: "Idempotent requests".
  • IETF HTTPAPI working group draft: "The Idempotency-Key HTTP Header Field".
  • Apache Kafka documentation: idempotent producer, transactions and "exactly-once semantics"; KIP-98.
  • Martin Kleppmann, Designing Data-Intensive Applications, ch. 11 (exactly-once, idempotence, end-to-end argument).
  • Saltzer, Reed & Clark, "End-to-End Arguments in System Design" (1984).
  • Pat Helland, "Idempotence Is Not a Medical Condition" (ACM Queue, 2012).
Finished this page?

Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).