SysDesignAtlas

Idempotency & Delivery Semantics

Why duplicates are guaranteed, why "exactly-once delivery" doesn't exist, and the concrete patterns that make repeated operations safe.

HLDMedium10 min readidempotencyexactly-onceretriescorrectness
Confidence

#Why this is unavoidable

A client sends a payment request and the connection times out. Did the charge happen?

   client ──── POST /charge ────► server
          ◄──── ??? timeout ────

   Possibility 1: request never arrived        → safe to retry
   Possibility 2: arrived, server died first   → safe to retry
   Possibility 3: processed, response lost     → retry = DOUBLE CHARGE
   Possibility 4: still processing slowly      → retry = DOUBLE CHARGE

The client cannot distinguish these. Ever. This is not an implementation gap — it's the two generals problem, and it's provably unsolvable. Two parties talking over a channel that can lose messages can never be certain the other side got the last message: every confirmation could itself be lost, so you'd need a confirmation of the confirmation, forever.

So you have exactly two options: never retry (and lose operations), or retry and make duplicates harmless. Since losing payments is worse than the alternative, essentially every real system retries — and therefore every real system must handle duplicates.

#Definition

An operation is idempotent if performing it multiple times has the same effect as performing it once.

   IDEMPOTENT                    NOT IDEMPOTENT
   SET balance = 100             balance = balance - 50
   DELETE user 42                INSERT INTO orders ...
   PUT /users/42 {...}           POST /orders {...}
   status = 'shipped'            counter++
   add 42 to a set               append to a list
   upsert by primary key         send an email

Note the pattern: assignment is idempotent, mutation relative to current state is not. "Set to X" survives repetition; "change by X" doesn't.

HTTP semantics reflect this: GET, PUT, DELETE, and HEAD are defined as idempotent; POST and PATCH are not. That's why PUT /users/42 with a full representation is safer than POST /users — but note this is only a convention; your implementation has to actually honor it.

#Delivery semantics, precisely

The difference comes down to when the consumer acks — tells the queue "I've got this message, don't send it again".

At-most-once — ack before processing. If the consumer crashes after acking but before finishing, the queue thinks the message is done and never resends it. Messages may be lost, never duplicated. Only acceptable for disposable data (sampled metrics, presence pings).

At-least-once — ack after processing. If the consumer crashes after doing the work but before acking, the queue resends the message and it gets processed again. Nothing is lost; duplicates will occur. The practical default.

Exactly-once — the phrase to be careful with.

#The patterns

#1. Idempotency keys (the standard for APIs)

The client generates a unique key per logical operation and sends it with every attempt, including retries.

   POST /charges
   Idempotency-Key: 7f3a-...-9b2c
   { "amount": 4999, "account": 42 }

   SERVER:
     1. Try to INSERT the key into idempotency_records.
        Unique constraint → this is the atomic gate.
     2. Insert succeeded → first attempt. Process it,
        store the response body against the key.
     3. Insert failed (duplicate key) →
          - if the stored record has a response: return it verbatim
          - if it's still in progress: return 409 / ask to retry

Critical details that separate a working implementation from a broken one:

  • The uniqueness check and the work must be in one transaction — or the key insert must commit first, so two concurrent retries can't both pass the check. A SELECT then INSERT races: both retries run the SELECT at the same moment, both see "no key yet", and both go on to charge the card.
  • Store the response, not just the key. A retry must return the same result (same order ID, same charge ID), not a fresh 200 with no body.
  • Handle in-flight duplicates. If the first request is still processing, the second must not proceed. Returning 409 and letting the client retry is the simplest correct behaviour.
  • Scope the key to the account and endpoint, so keys can't collide or leak across tenants (customers). Otherwise, if two customers happen to send the same key, the second would get the first customer's stored response.
  • Expire keys after ~24 hours. Retries don't arrive a week later, and the table would grow forever.

#2. Natural idempotency

Design the operation so repetition is inherently harmless — the cheapest option when available.

sql
-- not idempotent
UPDATE accounts SET balance = balance - 50 WHERE id = 42;

-- idempotent: conditional on a state that changes
UPDATE accounts SET balance = balance - 50, version = 8
WHERE id = 42 AND version = 7;      -- second run: 0 rows

The trick is that the second attempt finds nothing matching version = 7 and changes zero rows — a harmless no-op rather than a second deduction.

Others in the same family: INSERT ... ON CONFLICT DO NOTHING; an upsert (insert it, or update it if it's already there) keyed on something meaningful like an order number; and adding to a set, since adding an element that's already present changes nothing.

#3. Deduplication table

The consumer-side equivalent for message queues: keep a table of the message IDs you've already handled, and skip anything you've seen before. Deduplication — dedupe — is just that: recognising a repeat and doing nothing.

   BEGIN;
     INSERT INTO processed (msg_id) VALUES (?);  -- unique; fails on dupe
     ... do the work ...
   COMMIT;

Putting the dedupe insert in the same transaction as the work is what makes it correct. If they're separate, a crash between them either loses the work or loses the dedupe record.

Bound the table with a TTL (delete IDs older than, say, a day), so it doesn't grow forever. If the volume is very high, put a Bloom filter in front. A Bloom filter can say "definitely never seen" or "maybe seen". Most messages are new, so most checks get a definite "never seen" from memory and skip the database lookup entirely.

#4. State machines

Model the entity's lifecycle explicitly and make transitions conditional:

   pending → authorized → captured → settled
                    ↘ failed

   "capture" applied to an already-captured payment:
   the transition is invalid → no-op, return current state

The state machine makes idempotency a structural property rather than a bolt-on. It also makes the system easy to reason about during incidents — you can always ask "what state is this in?"

#The hard cases

Non-idempotent side effects you don't control. Sending an email, charging a third-party API, dispatching a physical package. You can't undo them, so you must not repeat them.

The pattern: record the intent transactionally, perform the effect once, record completion.

   BEGIN; INSERT INTO outbox(intent='send_email', id=X); COMMIT;

   worker:
     claim row X (conditional update: status pending → sending)
     call the email API with X as its idempotency key
     mark X sent

Push idempotency onto the external service where possible — good payment and email providers accept idempotency keys precisely for this. Where they don't, accept a small duplicate risk and design for detection rather than prevention (a duplicate email is recoverable; a duplicate charge needs reconciliation and refund).

Ordering plus retries. A retried message may arrive after later messages, so a retry can apply stale data. Example: "set address = Leeds" fails and is retried, but "set address = York" (sent later) lands first — then the retry overwrites York with the older Leeds. Fix with version checks (reject writes carrying an older version), or give every write a sequence number that only ever increases and keep whichever write has the highest number — see Clocks.

Partial failure across systems. The database write succeeded, but publishing the event to the queue failed. Retrying the whole operation re-does the database write; not retrying means the event is never sent. This is what the outbox pattern exists to solve: make the event part of the same transaction, so there's nothing to coordinate.

#The short answer

When any design involves retries, queues, or payments, say this early — it's a fast, high-value signal:

"This path has to be idempotent, because the queue is at-least-once and the client will retry on timeout. I'll take an idempotency key from the client, gate it with a unique constraint in the same transaction as the work, and store the response so a retry returns the identical result rather than creating a second order. Exactly-once delivery isn't something I can get from the transport, so I'm getting exactly-once effect from the consumer instead."

#Check yourself

Why must every real system handle duplicate requests?Show answer
After a timeout the client can't tell if the request was lost, crashed mid-way, succeeded with the reply lost, or is still running. Since losing operations is worse, systems retry — so duplicates will happen.
What makes an operation idempotent? Give an example of each kind.Show answer
Doing it twice has the same effect as once. Assignment is idempotent ("set status to shipped", upsert, add to a set); changes relative to current state aren't ("subtract 50", append, send an email).
What does Kafka's "exactly-once semantics" actually cover?Show answer
Reading from one Kafka topic and writing to another, where the output and the consumer's read position are committed in one Kafka transaction. Once a consumer writes to an external database or API, you're back to needing idempotency.
Describe a correct idempotency-key implementation.Show answer
The client sends a unique key with every attempt. The server inserts the key under a unique constraint as the atomic gate, does the work, stores the response against the key, and returns that stored response on any retry. Scope keys per account and expire them after about a day.
Why is "SELECT the key, then INSERT it" a broken idempotency check?Show answer
Two concurrent retries can both see no key and both proceed. The unique-constraint insert itself must be the gate.
How do you make a balance deduction naturally idempotent?Show answer
Make it conditional on a version that changes: UPDATE … SET balance = balance − 50, version = 8 WHERE id = 42 AND version = 7. A repeat matches zero rows.
How does a consumer-side dedupe table stay correct?Show answer
Insert the message ID under a unique constraint in the same transaction as the work, so a crash can't lose one without the other. Expire old IDs, and put a Bloom filter in front at high volume.
How do you handle a side effect you can't undo, like sending an email?Show answer
Record the intent transactionally (an outbox row), claim it with a conditional update, call the provider with the row ID as its idempotency key, then mark it done.

#What to carry forward

  • Timeouts make duplicates unavoidable, so retried paths must be idempotent.
  • Exactly-once delivery is impossible; exactly-once effect comes from at-least-once delivery plus idempotent consumers.
  • Idempotency keys: a unique-constraint gate, the stored response returned on retry, scoped and expiring.
  • Prefer natural idempotency — conditional updates, upserts, sets — and explicit state machines.
  • For irreversible side effects, record intent, perform once, and push idempotency onto the provider.
00:00
/ 10m