Skip to content

Idempotency and Safe Retries

Intermediate 39 min read Part 4 of 18

Why retries create duplicates and how to make them safe: idempotent methods, idempotency keys, dedupe tables, unique constraints and idempotent consumers.

Summary#

An operation is idempotent if doing it twice has the same effect as doing it once. Networks fail in ways that leave the client unsure whether a request succeeded, so clients retry, and retries of non-idempotent operations create duplicate orders, double charges and repeated notifications. The fix is to make operations safe to repeat: use naturally idempotent methods (GET, PUT, DELETE), give each create or payment a client-generated idempotency key that the server stores together with the result, enforce unique constraints in the database, and build idempotent consumers that skip messages they have already processed.

Why It Exists#

Why retries create duplicates#

When a client sends a request and gets no answer, there are three possibilities: the request never arrived, it arrived and failed, or it succeeded but the response was lost. The client cannot tell which. Timeouts, dropped mobile connections, load balancer resets and crashed servers all produce this uncertainty.

The only safe reaction to uncertainty is to retry, and almost every layer does: SDKs, gateways, service meshes, message queues and impatient users pressing "Pay" again. If "create payment" is retried after it already succeeded, the customer is charged twice.

At scale this is not rare: 10 million payments a day with a 0.01% timeout rate means about 1,000 uncertain requests a day.

Why retries create duplicates in depth#

The ambiguous failure. When a client sends a request and gets no answer, there are three possibilities. The request never arrived. It arrived and the server failed before doing anything. Or the server did the work and the response was lost on the way back. From the client's side, all three look identical: a timeout. No amount of waiting tells them apart, because the only evidence would be the reply that went missing. This is a small version of the classic Two Generals problem: over an unreliable channel, two parties can never be completely sure they agree on what happened. The practical consequence is that a client must choose between two failure modes:

  • Do not retry, and risk losing an operation the user asked for (at-most-once).
  • Retry, and risk doing it twice (at-least-once).

Idempotency removes the dilemma. If repeating the request has no extra effect, the client can always retry, and the result is the same as if the operation happened exactly once. This is often called exactly-once effect, as opposed to exactly-once delivery, which networks cannot promise.

Retries come from many places, not just your code. Engineers often think of retries as a loop they wrote. In a real system, many layers retry on their own:

  • Users double-click a button, or press back and submit again, or refresh a page that was posting a form.
  • Client SDKs and HTTP libraries retry on timeouts and connection errors, often by default.
  • Mobile apps queue actions while offline and replay them when the network returns, sometimes hours later.
  • Load balancers, gateways and service meshes can retry failed upstream calls automatically.
  • Message queues redeliver a message if the consumer does not acknowledge it in time.
  • Job schedulers and workflow engines rerun failed tasks, and operators rerun jobs by hand after an incident.

Each of these is a reasonable reliability feature, and together they mean any write in a distributed system will, sooner or later, arrive twice.

How often does it really happen? Rarely per request, often in total. Suppose 0.1% of requests hit a timeout where the server actually completed the work. At 1,000 payment requests per second, that is one ambiguous request every second, about 86,000 a day. If clients retry all of them without idempotency, that is tens of thousands of double charges per day. At that scale, "rare" means "constant".

Timeouts make it worse under load. Ambiguous failures are most common exactly when a system is struggling. Slow responses cross client timeouts, clients retry, and the retries add load, which makes more responses slow. Without idempotency, an overload incident becomes a duplicate-data incident too, and cleaning up duplicates by hand afterwards is slow, error-prone and sometimes impossible (an email cannot be unsent).

How It Works#

What idempotency means#

Formally, f(f(x)) = f(x): applying the operation again does not change the result further. Examples:

  • Idempotent: "set the order status to shipped", "delete item 42", "set balance to 100".
  • Not idempotent: "add 10 to the balance", "append a message", "create a new order".

Idempotency concerns the effect on the server, not the response. Deleting an already deleted item may return 404 the second time; the state is still the same.

What idempotency means in depth#

The precise definition. An operation is idempotent if doing it twice has the same effect on the system as doing it once. In mathematics, a function f is idempotent if f(f(x)) = f(x): applying the absolute value twice gives the same as once, and so does rounding, or taking the maximum with a fixed number. "Set the status to shipped" is idempotent, while "add 10 to the balance" is not.

Same state, not necessarily the same response. Idempotency is about the server's state, not the bytes returned. The first DELETE /bookings/7 returns 204 No Content. The second might return 404 Not Found, because the booking is already gone. Both leave the system in the same state, so DELETE is idempotent even though the responses differ. Well-designed idempotency-key systems go further and replay the original response, so the client cannot tell a retry from the first call. That makes client code simpler.

Related properties that are not the same thing:

  • Safe means no change at all (GET, HEAD). Every safe method is idempotent, but not the other way round: DELETE changes state, but only once.
  • Deterministic means the same input always gives the same output. A "create order" endpoint can be made idempotent without being deterministic in time, for example by returning the order created the first time.
  • Commutative means order does not matter. Two idempotent updates, "set price to 10" and "set price to 12", are each safe to repeat, but the final state depends on which runs last. So idempotency does not protect against reordering. That needs versions or timestamps, discussed below.

Making non-idempotent operations idempotent. There are three basic techniques, and the rest of this page is variations on them:

  1. Turn relative changes into absolute ones. "Add 10" becomes "set balance to 110 if it is currently 100". The condition makes a repeat harmless.
  2. Give the operation an identity. "Create a payment" becomes "create payment pay_abc if it does not already exist". The identity is an idempotency key, a client-supplied ID, or a natural business key.
  3. Remember what has been done. Store processed request or message IDs, and skip anything already seen.

Idempotent HTTP methods#

MethodSafe (no change)?Idempotent?Notes
GET, HEAD, OPTIONSYesYesRead only; always safe to retry
PUTNoYesReplaces the whole resource with the same content
DELETENoYesSecond delete leaves the same state
POSTNoNoUsually creates something new each time
PATCHNoDepends"Set field to X" is idempotent; "increment counter" is not

These are promises in the HTTP specification, but your implementation must honour them. A GET that increments a counter, or a PUT that appends to a list, breaks the promise. POST is the method that needs extra help: idempotency keys.

HTTP methods in depth#

The HTTP specification (RFC 9110) defines which methods are idempotent: GET, HEAD, OPTIONS, TRACE, PUT and DELETE. Clients, proxies and libraries rely on that promise. A browser or proxy may automatically repeat an idempotent request after a dropped connection, but should not repeat a POST without asking. So the method is part of the contract: if you implement PUT so that it appends, you break tools that assume it is safe to repeat.

PUT versus POST for creation. POST to a collection (POST /orders) lets the server choose the new ID, which is what makes a retry dangerous: each call mints a new ID. An alternative is to let the client choose the ID and use PUT: PUT /orders/ord_7f3a with the full order. The first call creates it. A retry overwrites it with identical content, which changes nothing. This works well when clients can generate globally unique IDs (UUIDs), and it gives idempotency with no extra key store. The downside is that clients now control your primary keys, so you must validate their format and stop one tenant from guessing another's.

PATCH depends on the patch. A JSON Merge Patch that says "set email to x" is idempotent. A JSON Patch operation that adds an element to an array, or a custom "increment" operation, is not. If your PATCH endpoints accept relative operations, give them idempotency keys like a POST.

Conditional requests as an idempotency tool. HTTP has built-in preconditions:

  • If-None-Match: * on a PUT means "create only if nothing exists here". A retry after success gets 412 Precondition Failed instead of a duplicate, and the client can treat that as "already done".
  • If-Match: "v7" on an update means "apply only if the current version is 7". A late retry of an old update fails instead of overwriting newer data.

These turn a blind write into a compare-and-set, which is idempotent and safe against reordering at the same time.

Idempotent does not mean "free to retry forever". Even GET retries cost capacity. Retry with backoff and jitter, cap the attempts, and respect Retry-After. Idempotency makes retries correct; it does not make them cheap.

Idempotency keys#

The client generates a unique key (usually a UUID v4) for each logical operation and sends it in a header. If it has to retry, it sends the same key. The server records the key with the result the first time, and on any later request with that key it returns the stored result instead of doing the work again.

Implementation details that matter:

  • Client-generated, one per operation. Create the key when the user starts the action (for example, when the checkout page loads or "Pay" is first pressed) and reuse it for every retry. A new key per retry defeats the purpose.
  • Scope keys per account (store (account_id, key)) so one customer cannot collide with or read another's results.
  • Store the request fingerprint (a hash of the body). If the same key arrives with different parameters, reject it with an error (400 or 422) rather than silently returning the old result.
  • Handle concurrent duplicates. Two requests with the same key may arrive at the same moment. Insert the key as in_progress with a unique constraint before doing any work; the loser of the race gets 409 Conflict and retries later.
  • Store the result (status code and body) once the operation finishes, and return it for later requests with the same key.
  • Expire keys with a TTL, typically 24 hours to a few days: long enough to cover any realistic retry window, short enough to bound storage.
  • Decide what to do with failures. Validation errors (4xx) can be stored and replayed. If the server crashed mid-operation, the key is left in_progress. Recovery must check the downstream system (did the processor charge?) before allowing a retry. This is why downstream calls should carry their own idempotency key too.
CREATE TABLE idempotency_keys (
  account_id    BIGINT       NOT NULL,
  idem_key      UUID         NOT NULL,
  request_hash  BYTEA        NOT NULL,
  status        TEXT         NOT NULL,        -- in_progress | completed
  response_code INT,
  response_body JSONB,
  created_at    TIMESTAMPTZ  NOT NULL DEFAULT now(),
  PRIMARY KEY (account_id, idem_key)
);
-- Step 1: claim the key; zero rows inserted means a duplicate
INSERT INTO idempotency_keys (account_id, idem_key, request_hash, status)
VALUES ($1, $2, $3, 'in_progress')
ON CONFLICT DO NOTHING;
-- Cleanup job: DELETE ... WHERE created_at < now() - interval '24 hours';

If the business write and the key record live in the same database, write them in one transaction, so either both are saved or neither is. That removes most crash edge cases. Redis (SET key value NX EX 86400) is a fast alternative for the claim step, but it is not transactional with your main database, so a crash between the two writes needs careful handling.

Idempotency keys in depth#

The idea is simple: the client sends a unique key with each logical operation, and the server remembers the outcome per key. Doing it correctly under concurrency and crashes takes care. Each key record moves through a small set of states.

A storage schema. A typical relational design stores the key next to the business data, so both can change in one transaction:

CREATE TABLE idempotency_keys (
  account_id     BIGINT       NOT NULL,
  idem_key       TEXT         NOT NULL,
  request_hash   BYTEA        NOT NULL,   -- fingerprint of method, path, body
  state          TEXT         NOT NULL,   -- started, completed, rejected
  locked_until   TIMESTAMPTZ,             -- lease for the request in progress
  response_code  INT,
  response_body  JSONB,
  recovery_point TEXT,                    -- last completed step, for resumption
  created_at     TIMESTAMPTZ  NOT NULL DEFAULT now(),
  PRIMARY KEY (account_id, idem_key)
);
CREATE INDEX ON idempotency_keys (created_at);  -- for TTL cleanup

The request algorithm.

  1. Claim the key atomically. Insert the row with state started and a short lease (locked_until about 30 to 60 seconds ahead). The primary key guarantees that only one insert succeeds. Never check whether a key exists and then insert it in a separate step: two concurrent requests can both see "no key" and both proceed.
  2. If the insert conflicts, read the existing row:
    • Different request_hash: the client reused a key for a different request. Return 422 (or 400), since this is a client bug and must never silently replay another request's result.
    • State completed or rejected: return the stored status code and body. The client gets exactly what the first call returned.
    • State started with a live lease: another copy is running right now. Return 409 Conflict, asking the client to retry shortly, or wait briefly and then read the result.
    • State started with an expired lease: the earlier attempt crashed. Reclaim the key and resume from its recovery point.
  3. Do the work, ideally in the same database transaction that updates the key to completed with the response. If the effect and the key commit together, there is no window where one exists without the other.
  4. Return the response and keep the record until the TTL expires.

The fingerprint. Hash a canonical form of the request: method, path and body with keys sorted and whitespace removed, so harmless formatting differences do not look like a different request. Exclude headers that vary per attempt, such as timestamps or trace IDs. Storing the hash rather than the full body keeps the table small and avoids keeping sensitive data longer than needed.

Which errors to store. Deterministic outcomes should be stored and replayed: success, and validation errors such as "card declined" or "seat unavailable". Otherwise a retry might succeed where the original failed, which surprises clients that already showed an error. Transient outcomes should not be stored as final: a 500, a timeout to a downstream service, or a lost lease. Leave those retryable, so the next attempt with the same key can try again.

When the work crosses systems. If processing calls an external service, such as a card network or an email provider, the database transaction cannot include it. A crash after the external call but before the commit leaves the key started while the money has moved. The robust answer is to break the work into atomic phases with recorded recovery points, and to pass an idempotency key to the external system too:

  • Phase 1, local transaction: create the charge record as pending, and set the recovery point to charge_created.
  • External call: charge the card with key charge_42, so the payment provider dedupes any repeat.
  • Phase 2, local transaction: mark the charge succeeded, store the response, and set the recovery point to finished.

A retry that finds charge_created repeats the external call with the same downstream key, which is safe, and continues. Brandur Leach's 2017 article "Implementing Stripe-like Idempotency Keys in Postgres" describes this approach in detail.

Generating keys on the client. Use a random UUID (version 4) or a time-ordered one (version 7, which indexes better). The rule that matters most: one key per user intention, reused for every retry of it. Create the key when the user taps "Pay", store it with the pending action, and reuse it on every retry, including after an app restart. Generating a fresh key inside the retry loop silently disables the whole mechanism. Some systems derive the key from business data instead, such as the checkout session ID, which survives even if the client loses local state.

Scope and security. Scope keys to the account or API key, so one customer's key can never collide with or reveal another customer's stored response. Treat stored responses as sensitive data: they may contain personal or payment details, so apply the same access controls and retention rules as the main data.

TTL and sizing. Keys must outlive any realistic retry window, but not forever. A day is common for synchronous APIs, and longer for clients that replay offline queues. Sizing is easy to estimate: 10 million keyed requests a day with about 1 KB per record (hash, status, a small stored body and indexes) is roughly 10 GB per day of retention. That fits easily in a relational table with a daily cleanup job that deletes old rows in batches, or in a partitioned table where whole partitions are dropped. Key-value stores with native expiry, such as DynamoDB TTL or Redis EX, avoid the cleanup job. The catch is that they are a separate system from the main database, which reopens the crash window described above.

Redis versus the main database. A Redis SET key value NX EX 86400 is a fast, simple claim. It is good enough for duplicates that are merely annoying, such as a repeated notification. For money, keep the key in the same transactional store as the effect, because a Redis failover can lose recent writes, and a crash between the Redis claim and the database write leaves them disagreeing.

Dedupe tables and unique constraints#

Often the data itself gives you a natural key, and the database can enforce "only once" for you:

  • Unique constraints on business keys: UNIQUE (order_id) on payments ensures one payment per order, however many times the code runs. UNIQUE (user_id, event_id, seat_id) prevents double booking.
  • Upserts: INSERT ... ON CONFLICT DO NOTHING or DO UPDATE turns "create" into "create if missing".
  • Conditional updates: UPDATE orders SET status = 'paid' WHERE id = 7 AND status = 'pending' only works the first time; later attempts affect zero rows.
  • Dedupe table: a table of processed IDs (message_id, event_id) checked and written in the same transaction as the effect.

These database guarantees are the last line of defence: even if application-level checks have a bug or a race, the constraint rejects the duplicate.

Dedupe tables and unique constraints in depth#

Idempotency keys live at the API edge. Underneath, the database is the final guard, because it is the one component that sees every write and can enforce rules atomically.

Natural keys versus synthetic keys. A natural business key is something that must be unique in the real world: one payment per order, one seat per event per booking, one daily report per account per date. A unique constraint on it makes duplicates impossible no matter where they came from: a retry, a bug, a rerun job, or two servers racing. A synthetic key, such as an idempotency key or message ID, identifies a request rather than a business fact. Use both where you can. The natural key protects the invariant, and the synthetic key lets you replay the right response.

Upserts by database.

-- PostgreSQL: create if missing, otherwise do nothing
INSERT INTO payments (order_id, amount_cents, status)
VALUES (7, 4999, 'pending')
ON CONFLICT (order_id) DO NOTHING
RETURNING id;
 
-- MySQL: same idea
INSERT INTO payments (order_id, amount_cents, status)
VALUES (7, 4999, 'pending')
ON DUPLICATE KEY UPDATE order_id = order_id;

With DO NOTHING, PostgreSQL returns no row on conflict, so the code must then select the existing row to answer the caller. DynamoDB does the same with a conditional write: PutItem with attribute_not_exists(pk) succeeds once and fails with a conditional-check error afterwards. Cassandra offers INSERT ... IF NOT EXISTS, a lightweight transaction that uses Paxos under the hood and is noticeably slower than a normal write, so use it only where duplicates truly matter.

Conditional state transitions. Many operations are state changes, and a guard on the current state makes them idempotent:

UPDATE orders SET status = 'paid', paid_at = now()
WHERE id = 7 AND status = 'pending';
-- 1 row updated: we made the change. 0 rows: already paid (or cancelled), check and respond.

This is a compare-and-set. It also blocks invalid transitions, such as paying a cancelled order, which a plain SET status = 'paid' would allow.

Versions and sequence numbers protect against reordering. Idempotency stops duplicates, but a late retry of an old request can still overwrite newer data. Attach a version to each update and apply it only if it is newer:

UPDATE profiles SET display_name = 'Ana', version = 8
WHERE user_id = 42 AND version < 8;

For streams of events per entity, consumers keep a high-water mark: the highest sequence number applied so far for each entity. Any event at or below it is a duplicate or stale, and is skipped.

Dedupe tables for processed IDs. When there is no natural key, record processed request or message IDs in their own table, and insert into it in the same transaction as the effect. If the insert conflicts, the work was already done, so roll back and acknowledge. The table grows without limit unless you prune it, so keep IDs for longer than the longest possible redelivery delay (for example 7 days for a queue with 4-day retention), then delete them.

Probabilistic dedupe at huge scale. Pipelines that handle billions of events sometimes dedupe with a Bloom filter, a compact bit array that answers "definitely new" or "probably seen". It uses a few bits per item instead of storing every ID. The catch is false positives: a small fraction of genuinely new events are wrongly treated as duplicates and dropped. That is acceptable for analytics counts and never acceptable for payments. See Probabilistic Data Structures for how the false-positive rate is tuned.

Idempotent consumers#

Message queues and event streams usually deliver at least once: after a consumer crash or rebalance, a message is delivered again. Exactly-once delivery across systems is very hard, so the practical approach is at-least-once delivery plus idempotent processing, which gives an effectively-once outcome. See Delivery Semantics.

on message m:
  begin transaction
    inserted = INSERT INTO processed_messages(id) VALUES (m.id) ON CONFLICT DO NOTHING
    if inserted == 0: commit; ack(m); return      # already handled
    apply effect of m (update balance, create shipment, ...)
  commit
  ack(m)                                          # if we crash before ack, the redelivery is skipped

When the effect is an external call (send an email, call a payment processor), you cannot put it in your transaction. Pass a stable idempotency key derived from the message ID to the external API, or record "sent" before acknowledging and accept a small risk of a duplicate, depending on what costs more: a duplicate or a missed action.

Idempotent consumers in depth#

Almost every message broker gives at-least-once delivery by default. Duplicates are not a bug in the broker. They are the price of not losing messages:

  • A consumer processes a message, then crashes before acknowledging it. The broker redelivers it.
  • In SQS, a message whose visibility timeout expires before the consumer deletes it becomes visible again, and another consumer picks it up.
  • In Kafka, a consumer that processes records and crashes before committing its offset will reread them after restart. A rebalance can also hand a partition to a new consumer, which resumes from the last committed offset.
  • A producer that times out waiting for an acknowledgement resends, and the broker may now hold two copies.

So the consumer must make processing idempotent. The standard pattern is an inbox or processed-messages table written in the same transaction as the effect:

If the consumer crashes after the commit but before the acknowledgement, the message comes back, the insert conflicts, and the consumer simply acknowledges it. If it crashes before the commit, nothing was saved, and the retry does the work properly. Either way, the effect happens once.

Side effects outside the database break this neat picture. Sending an email or calling a partner API cannot be rolled back with the transaction. The options, from best to weakest:

  • Pass an idempotency key derived from the message ID to the external service, if it supports one.
  • Write the intent to an outbox table in the same transaction, and have a separate relay deliver it with its own dedupe. See Change Data Capture for relaying outbox rows.
  • Accept rare duplicates where they are harmless, and make the downstream receiver dedupe by ID.

What brokers offer. Some brokers reduce duplicates themselves, within limits:

  • Kafka's idempotent producer gives each producer an ID and numbers its messages per partition. The broker drops a resend with a sequence number it has already written, which removes duplicates caused by producer retries.
  • Kafka transactions go further. A consume-process-produce loop can write its output records and commit its input offsets atomically, giving exactly-once processing within Kafka.
  • Amazon SQS FIFO queues drop messages with the same deduplication ID within a five-minute window.

None of these covers writes to your own database or calls to other systems. Once processing touches the outside world, idempotent consumers are still required. See Delivery Semantics.

Ordering and idempotency together. Duplicates are one problem; out-of-order delivery is another. If "address changed to B" is redelivered after "address changed to C", a naive consumer that dedupes by ID will still apply B over C, because B's ID is new to it after the first attempt failed. Per-entity version numbers or sequence numbers, checked with the high-water-mark rule above, solve both at once.

A catalogue of idempotent designs#

Most non-idempotent operations can be reshaped so that repetition is harmless by design, before any key store is needed. These reshapings are worth knowing because they are often simpler and more robust than adding a key.

Counters become sets. A "like" button implemented as likes = likes + 1 double-counts on every retry. Store the fact instead: a row "user 42 likes post 9" with a unique constraint on the pair. A retried like inserts nothing new. The count is derived from the rows, or kept as a cached counter that is updated only when the insert actually created a row. The same reshaping works for votes, follows, RSVPs and "mark as read".

Balances become ledgers. balance = balance - 50 is dangerous to repeat. A ledger records each movement as its own entry, keyed by a transfer ID: "transfer t_88 debits account A 50 and credits account B 50". A unique constraint on the transfer ID means the transfer posts once, and the balance is the sum of entries, or a cached sum updated in the same transaction. This is also how accounting has worked for centuries. Double-entry bookkeeping is naturally auditable, and a duplicate shows up as a visible extra entry instead of a silently wrong number.

Uploads become content-addressed. If a file's storage key is the hash of its contents (for example SHA-256), uploading the same file twice writes the same object to the same place. The second write is a no-op, and duplicate copies across users are stored once. Large uploads use multipart sessions with an upload ID. Each part is numbered, re-sending a part simply overwrites it, and the final "complete" call names exactly which parts make up the file.

Jobs become keyed by their input. "Send the daily digest" is dangerous if a scheduler fires twice. "Send the digest for user 42 for 2026-12-01" can be recorded once with a unique key, so a second run finds it already done. The same applies to billing runs ("invoice account 9 for November"), report builds and data backfills. Writing output with overwrite semantics (replace the partition for that date) rather than append makes reruns safe too.

Events carry their own identity. Every event published should carry a stable ID assigned when the fact happened, not when the message was sent. If a producer retries, the event keeps the same ID, so consumers can dedupe. An ID minted at send time defeats this, because every resend looks new.

State machines reject repeats. If an order may only move pending to paid to shipped, then "mark paid" on an order that is already paid is a no-op, and on a cancelled order it is an error. Expressing operations as guarded transitions gives idempotency and correctness together.

Absolute values beat deltas. "Set quantity to 3" can be repeated. "Add 1 to quantity" cannot. When a client knows the desired end state, send that. When it only knows a delta, attach a key or a version.

Keys across a chain of services#

Real requests cross several services, and each hop can retry. Idempotency has to hold at every hop, not just at the edge.

Derive child keys from the parent. When checkout calls inventory, payments and shipping, it passes a key derived deterministically from the client's key, such as k1:charge. If the checkout is retried, every child call is retried with the same child key, so completed steps replay their results and only unfinished steps do new work. A random new key per downstream call would turn every retry into a fresh charge.

Decide which layer retries. If the client, the gateway, the checkout service and its HTTP library all retry three times, one user action can become dozens of downstream attempts. Pick one layer to own retries for each hop, usually the caller closest to the work that knows whether the call is idempotent, and turn the others off or limit them to connection failures before any bytes were sent.

Idempotency does not end at your boundary. Check whether each external dependency accepts an idempotency key: payment providers, email and SMS providers, cloud APIs. If one does not, wrap it. Record "about to call" and "called" states locally, and make the decision to call depend on them. Then reconcile with the provider's records for the rare case where the call happened but your record did not.

Use cases#

  • Payments: the classic case. Every charge, refund and payout request carries an idempotency key, and calls to card processors carry their own.
  • Orders and bookings: "place order" keyed by a checkout session ID; a unique constraint on seat plus event prevents double booking.
  • Messaging and notifications: a chat message gets a client-generated ID, so a resend after a reconnect does not appear twice; a notification service dedupes on (user_id, notification_id) so users do not get the same push three times. See Design a Notification System.
  • Webhooks: providers retry deliveries, so receivers dedupe on the event ID.
  • Infrastructure and jobs: "create VM" or "run nightly job for date D" keyed so a retried workflow does not create two VMs or two reports.

Use cases in depth#

Payments. The canonical case, because a duplicate costs real money and real trust. A robust payment flow layers several protections:

  • the client sends an idempotency key per payment attempt;
  • the payment service has a unique constraint on the order or invoice it is paying;
  • the call to the payment provider carries its own idempotency key, derived from the internal payment ID;
  • ledger entries are keyed so each money movement is recorded once.

Each layer catches what the others miss. A user who double-taps "Pay" is caught by the client key. A bug that creates a second payment for the same order is caught by the unique constraint. A retried provider call after a timeout is caught by the provider's key. Reconciliation jobs that compare internal records with the provider's settlement files catch anything left over. See Design a Payment System.

Orders and bookings. "Place order" is keyed by the checkout session, so pressing the button twice, or a retry after a timeout, returns the same order. Bookings add a business invariant: a unique constraint on (event_id, seat_id) among active bookings guarantees a seat cannot be sold twice, whether the duplicate came from a retry or from two different users racing. Note the difference: the idempotency key makes the same user's retry return the original booking, while the unique constraint makes a different user's attempt fail with "seat unavailable".

Messaging and chat. The client creates a message ID (often a UUID) when the user hits send and stores it with the outgoing message. If the connection drops and the app resends, the server sees a known ID and returns the stored message instead of posting it twice. The same ID lets recipients' devices dedupe messages that arrive by both push and sync. Here the "key" is permanent, since it is the message's own identity, so offline replays days later are still safe.

Notifications. Users notice duplicate push notifications, emails and texts immediately, and some, such as one-time passwords, are confusing when doubled. Notification pipelines dedupe on a notification ID, usually derived from the triggering event, such as order_shipped:ord_77, at the last step before calling the delivery provider. Some teams accept at-most-once for low-value notifications, because a rare missed "someone liked your photo" is better than a stream of duplicates.

Webhooks. Providers such as Stripe and GitHub deliver webhooks at least once and retry failures, so receivers must dedupe on the event ID the provider includes. Receivers should also acknowledge quickly and process asynchronously, because a slow handler causes timeouts, which cause retries, which cause more duplicates.

Infrastructure and jobs. Cloud APIs expose the same idea. Amazon EC2's RunInstances accepts a client token, so a retried call does not launch a second fleet of servers. Declarative tools are idempotent by design. Terraform and Kubernetes compare the desired state with the actual state and change only the difference, so running them twice is harmless. Batch jobs become idempotent when they are keyed by their input, such as "the report for account 9 on 2026-12-01", and write with overwrite or upsert semantics. A rerun then replaces the output instead of appending a second copy.

The Stripe-style idempotent API#

Stripe's API is the best-known public example. Clients send an Idempotency-Key header on POST requests. Stripe saves the status code and body of the first request made with that key and returns the same result for later requests with the same key, including stored errors. Reusing a key with different parameters returns an error. Keys can be pruned after 24 hours. GET and DELETE requests do not need keys because they are already idempotent. Stripe's client libraries generate keys automatically and retry safely with exponential backoff.

This pattern (header, stored response, fingerprint check, TTL) is now common wherever duplicates cost money. See Design a Payment System.

The Stripe-style API in depth#

From the client's side, using such an API correctly is short. The important parts are reusing the key and backing off between attempts:

async function createCharge(body: ChargeRequest): Promise<Charge> {
  const key = crypto.randomUUID();           // one key per user intention
  for (let attempt = 0; attempt < 5; attempt++) {
    try {
      const res = await fetch("/v1/charges", {
        method: "POST",
        headers: { "Idempotency-Key": key, "Content-Type": "application/json" },
        body: JSON.stringify(body),
      });
      if (res.status === 409 || res.status >= 500) throw new Error("retryable");
      return await res.json();               // success or a stored 4xx: do not retry
    } catch {
      const base = 2 ** attempt * 250;       // 250 ms, 500 ms, 1 s, 2 s ...
      await sleep(base / 2 + Math.random() * base / 2);   // jitter
    }
  }
  throw new Error("gave up; show the user a pending state, then reconcile");
}

Three details are worth noting. The key is created outside the loop. A 409 (the same key is still in progress) is retryable, but a stored 4xx such as "card declined" is not, because the replay will say the same thing. And after giving up, the honest client state is "unknown, checking". Re-reading the charge later, or querying by the same key, resolves it without risking a second charge.

Why the design choices matter. Replaying stored errors keeps the client's view consistent. Rejecting a reused key with different parameters catches client bugs before they cause silent damage. A 24-hour window covers ordinary retries while keeping storage bounded. Automatic keys in the official SDKs mean most developers get safe retries without thinking about it, which is the best kind of safety.

Idempotency for asynchronous and long-running operations#

Some operations take minutes: exporting a large report, transcoding a video, provisioning a database. These APIs usually return 202 Accepted with a job or operation resource that the client polls. Idempotency still matters, perhaps more, because duplicate jobs waste real compute and can produce conflicting outputs.

  • Key the job creation. POST /v1/exports with an idempotency key returns the same job ID on every retry, whether the job is queued, running or finished. The client then polls one job, not three.
  • Make the worker idempotent too. Queues redeliver jobs, and workers crash halfway. Workers should write output to a location derived from the job ID (for example exports/job_55/result.csv) and overwrite rather than append. They should also record progress checkpoints, so a restarted worker resumes instead of redoing everything.
  • Treat completion as a guarded transition. Moving the job from running to succeeded should be a conditional update. A slow duplicate worker that finishes later cannot then overwrite the result or send a second "your export is ready" email.
  • Deduplicate by intent when it helps. If two different requests ask for exactly the same export within a few minutes, some systems return the existing job instead of starting another. That is not strictly idempotency, since the keys differ, but it uses the same machinery: a fingerprint of the request mapped to a job.

The general rule: wherever work is retried, whether by a client, a queue, a scheduler or a person, ask what identifies "the same work". Then make that identity the thing your storage enforces.

When to Use It#

  • Any operation that moves money, creates orders or bookings, or sends messages to people.
  • Any endpoint that clients, SDKs or gateways may retry automatically.
  • Every message or event consumer on an at-least-once queue.
  • Webhook receivers.

When NOT to Use It#

  • Read-only endpoints: GET is already idempotent.
  • Writes where a duplicate is harmless and cheap (for example, a "last seen" timestamp that is simply overwritten).
  • Do not add a full idempotency-key store when a unique constraint on a natural key already makes duplicates impossible.

How to Implement It#

  1. Classify each endpoint: naturally idempotent (GET, PUT, DELETE, conditional updates) or needs a key (POST creates and payments).
  2. Accept an Idempotency-Key header on non-idempotent endpoints; require it for payments.
  3. Claim the key atomically with a unique insert, then do the work, then store the response; use one transaction when possible.
  4. Fingerprint requests and reject reuse with different parameters.
  5. Add unique constraints on natural business keys as the final guard.
  6. Make consumers idempotent with a processed-ID table updated in the same transaction as the effect.
  7. Retry with exponential backoff and jitter on the client, reusing the same key.
TechnologyFits when
PostgreSQL / MySQL unique keys + ON CONFLICTKeys stored with the business data, transactional
DynamoDB conditional writes (attribute_not_exists)Serverless or high-scale key-value storage
Redis SET NX EXFast claim with built-in TTL where loose coupling to the DB is acceptable
Kafka idempotent producer / transactionsAvoiding duplicate writes within Kafka pipelines

Trade-offs#

ChoiceGainCostPick when
Idempotency keys in main DBAtomic with the business writeExtra table and writes, cleanup jobPayments, orders
Keys in RedisFast, simple TTLNot atomic with DB writes; data loss on failoverHigh volume, lower stakes
Natural unique constraintsNo extra storage; enforced by DBNeeds a real business keyOne payment per order, one seat per booking
Dedupe table for consumersEffectively-once processingGrows over time; needs retentionQueue and stream consumers
Long key TTLCovers late retriesMore storageSlow batch clients, offline mobile
Client-chosen IDs with PUTNo separate key store; replays are natural overwritesClients control primary keys; needs validationClients can generate UUIDs, simple creates
Store transient errors vs notNot storing them lets retries recoverStoring them blocks recovery until the TTLStore only deterministic outcomes
Bloom-filter dedupeTiny memory for billions of IDsFalse positives drop real eventsAnalytics streams, never money

Common Pitfalls#

  • Generating a new key on every retry, so every retry looks like a new operation.
  • Checking "does the key exist?" and then inserting it in two steps, so two concurrent requests both pass the check.
  • Storing the key in a different database from the effect and crashing in between.
  • Returning a cached success for a request with the same key but different parameters.
  • Retrying non-idempotent calls at the gateway or service mesh without keys.
  • Treating idempotency as protection against reordering; a late retry of an old update still needs a version check.
  • Setting the in-progress lease shorter than slow requests, so a retry reclaims a key while the first attempt is still running.
  • Deduping by message ID but sending emails or partner calls outside the transaction without their own dedupe.

Real-World Examples#

Stripe documents idempotency keys for its API: the first result for a key is saved and replayed for retries, and keys can be pruned after 24 hours.

Apache Kafka added idempotent producers, which attach a producer ID and sequence numbers so brokers drop duplicate writes caused by producer retries.

  • Amazon EC2 accepts a client token on RunInstances, so a retried launch request does not start a second set of instances.
  • Amazon SQS FIFO queues drop messages that repeat a deduplication ID within a five-minute window.

In the Interview#

When to bring it up#

Idempotency is one of the highest-value, lowest-cost points in a design interview. Mention it the moment your design has a write that must not happen twice: a booking, a payment, an order, a message, a notification or a queue consumer. One applied sentence beats a lecture: "The booking POST takes an idempotency key, so a retry after a timeout can't double-book the seat, and there's a unique constraint on event and seat as a backstop." Then keep going. If the interviewer wants more, they will ask about concurrency, crashes or queues, and the depth sections above give you the answers.

A strong answer covers four layers in a few sentences:

  1. Client: one key per user action, reused on retries, with backoff.
  2. API: an atomic claim of the key, a fingerprint check, and the stored response replayed on retries.
  3. Data: unique constraints and conditional updates as the final guard.
  4. Async: consumers dedupe by event ID in the same transaction as the effect.

More follow-ups#

  • "Where do you store the keys?" In the same database as the effect, so they commit together. Redis is acceptable for low-stakes duplicates.
  • "How long do you keep them?" Longer than the longest retry window, typically 24 hours, longer for offline clients. Natural IDs stored on the row last forever.
  • "What if the same key arrives with a different body?" Reject it with a 4xx; never replay another request's result.
  • "What about the email you send after payment?" Outbox in the same transaction, and a sender that dedupes by notification ID.
Deep Dive: Idempotency across multi-step workflowsShow

Keys must flow downstream. A checkout calls inventory, payment and shipping. Each step needs its own idempotency, usually a key derived from the parent operation (checkout_123:payment). Then a retried workflow can safely repeat every step, and only incomplete ones take effect. Workflow engines such as Temporal rely on this: activities are retried automatically and must be idempotent.

Recovery points. For long operations, store progress in the key record (charged, receipt_sent) so a retry resumes from the last completed step instead of starting over. This is the "atomic phases" approach some payment teams use.

Ordering and stale retries. A retry can arrive after a newer request. For updates, combine idempotency with version checks (UPDATE ... WHERE version = 7) so an old retried update cannot overwrite newer data.

Key retention vs offline clients. Mobile apps may queue actions offline for days. If the server expires keys after 24 hours, a late replay looks new. Either extend the TTL for those endpoints or rely on natural unique keys (a client-generated message ID stored permanently on the message row).

Exactly-once is a property of the whole pipeline. Kafka transactions give exactly-once processing inside Kafka (read, process, write), but the moment you call an external system, you are back to at-least-once delivery plus idempotency at the boundary.

Idempotency in distributed systems theory and practiceShow

The end-to-end argument. In their 1984 paper "End-to-End Arguments in System Design", Saltzer, Reed and Clark argued that some guarantees can only be fully provided by the endpoints of a system, not by the layers in between. Duplicate suppression is their classic example. TCP removes duplicate packets within one connection, but if the connection breaks and the application reconnects and resends, TCP cannot know that the new bytes repeat the old ones. Only the application, which understands what "the same payment" means, can dedupe at that level. This is why idempotency keys exist even though every layer below already "handles retries".

Why exactly-once delivery is not on offer. A sender can only learn that a message was processed by receiving an acknowledgement, and the acknowledgement itself can be lost. So the sender must either resend (and risk a duplicate) or not (and risk a loss). No protocol escapes this over an unreliable network. What systems can offer is exactly-once effect: at-least-once delivery combined with idempotent processing, so duplicates arrive but change nothing. When a product says "exactly-once", read it as "exactly-once within this system's boundary, thanks to dedupe".

Consensus systems dedupe client commands too. Replicated state machines face the same problem. A client sends a command to a Raft leader, the leader commits it, and then crashes before replying. The client retries with the new leader, and the command could be applied twice. The Raft paper (Ongaro and Ousterhout, 2014) handles this by having clients attach unique serial numbers to commands. The state machine records the latest serial number and response per client, and answers a repeat from that record instead of executing it again. That is an idempotency-key table built into the replication layer.

CRDTs make merging idempotent by construction. Conflict-free replicated data types, used in collaborative editors and some multi-region databases, merge replica states with a function that is idempotent, commutative and associative. Merging the same update twice, in any order or grouping, gives the same result. A grow-only counter, for example, keeps one count per replica and merges by taking the maximum of each, and taking a maximum twice changes nothing. So these systems can resend state freely and never double-count, which is why they tolerate unreliable networks so well.

Idempotency versus concurrency control. These solve different problems, and production systems need both. Idempotency answers "is this the same request again?" Concurrency control answers "two different requests want the same thing; who wins?" A seat booking needs an idempotency key for the user's own retry, and a lock, a conditional update or a unique constraint for two users racing. Confusing the two leads to designs that dedupe retries but still oversell, or that serialise everything but still double-charge on a timeout.

Idempotent replays as a recovery tool. When every step of a pipeline is idempotent, recovery becomes simple: replay. After a bug fix, you can reprocess the last day of events from Kafka. After a crash, a workflow engine can rerun every activity that was not confirmed. After a failed migration, you can run the backfill again from the start. Teams that design for idempotency get this operational freedom almost for free, and teams that do not must write careful one-off scripts that track exactly what has already been applied.

Testing and operating idempotency in productionShow

Idempotency bugs hide well, because the happy path never exercises them. They need deliberate testing and monitoring.

Tests that inject duplicates.

  • Sequential replay: send the same request twice with the same key, and assert one effect and identical responses.
  • Concurrent replay: fire 10 identical requests at the same moment, and assert exactly one effect. The others should get the stored response or a 409. This catches check-then-insert races that sequential tests miss.
  • Crash injection: kill the process between the effect and the key update, or between the commit and the response, then retry and assert one effect.
  • Parameter mismatch: reuse a key with a different body and assert a 4xx.
  • Consumer redelivery: deliver the same message twice, and also deliver the same message to two consumers in parallel.

Property-based tests generalise this. Generate random sequences of requests with random duplicates and delays, and check that the final state equals the state from applying each distinct request once.

Metrics worth watching.

  • Replay rate: the share of keyed requests that hit an existing key. A sudden rise means clients are retrying more, which often points to a latency problem upstream.
  • In-progress conflicts (409s): a high rate suggests clients retry too fast, or requests run longer than the lease.
  • Fingerprint mismatches: these should be near zero. Any steady rate means a client is reusing keys incorrectly.
  • Stale started keys: keys stuck in started past their lease reveal crashes mid-operation that need recovery.
  • Consumer duplicate rate: how often the inbox insert conflicts. A spike often means consumer crashes or rebalances.

Reconciliation as the last line of defence. Even with every layer correct, systems that move money run reconciliation. Jobs compare internal records with external ones, such as provider settlements and bank statements, and flag mismatches for review. Idempotency makes duplicates rare, and reconciliation makes sure the rare ones are caught.

Lease length versus request duration. The in-progress lease must be longer than the slowest normal request, or a retry will reclaim a key whose first attempt is still running, and both will do the work. It must also be short enough that a genuinely crashed attempt is retried quickly. Measure the p99.9 duration of the keyed endpoint and set the lease comfortably above it, for example 30 seconds for an endpoint whose p99.9 is 3 seconds. Long-running work should move to an asynchronous job with its own idempotent state machine.

Key Takeaways#

  • Idempotent means repeating an operation has no extra effect; retries after lost responses make this essential.
  • GET, PUT and DELETE are idempotent by definition; POST needs an idempotency key.
  • Keys are client-generated per logical operation, claimed atomically, stored with the result and fingerprint, and expired after a TTL.
  • Unique constraints, upserts and conditional updates are the database's final guard against duplicates.
  • Queue consumers are at-least-once, so make them idempotent with processed-ID tracking in the same transaction as the effect.
  • Retries are unavoidable because a timeout cannot distinguish lost requests from lost responses; idempotency makes them safe.
  • Layer the defences: client keys, an atomic server claim with a fingerprint, unique constraints, and idempotent consumers.
  • Use versions or sequence numbers as well, because idempotency stops duplicates but not reordering.