← All lessons

Core concepts

Idempotency

Networks retry, users double-click and message brokers redeliver. Idempotency is how a system makes "it happened twice" mean the same as "it happened once".

16 min readUpdated November 2026Free

A client sends “place this order”. The server places it, and the response is lost on the way back — a timeout, a dropped mobile connection, a load balancer restart. From the client’s side the request might have worked. It has two choices: give up and maybe lose the order, or retry and maybe place it twice.

Every distributed system faces this, and you cannot make it go away. You cannot tell “the request failed” apart from “the response failed”. What you can do is make the retry harmless. That is all idempotency means: doing it twice has the same effect as doing it once.

Why “exactly once” is the wrong goal

Delivery over a network comes in two honest flavours: at most once (never retry; sometimes lose it) and at least once (retry until acknowledged; sometimes duplicate it). True exactly-once delivery doesn’t exist between independent machines.

What you build instead is exactly-once effect: at-least-once delivery, plus an operation that ignores duplicates. Kafka’s “exactly-once semantics” is exactly this — idempotent producers and transactions inside Kafka — and it stops at Kafka’s boundary. The moment your consumer writes to a database or calls an API, idempotency is your job again. The Kafka lesson covers that boundary.

The point

Retries are not optional. Clients retry, SDKs retry, load balancers retry, Kubernetes restarts pods mid-request, and brokers redeliver after a rebalance. A design that is only correct if nothing ever runs twice is a design that is incorrect in production.

Which operations are already idempotent

HTTP gives you a head start, by definition if not always by implementation:

Method Idempotent? Why
GET, HEAD Yes Reads change nothing
PUT Yes “Set the resource to this” — twice leaves the same state
DELETE Yes Deleting twice leaves it deleted (the second may return 404; the state is the same)
POST No “Create a new one” — twice creates two
PATCH Depends {"name": "Priya"} is; {"op": "increment"} isn’t

The rest of this lesson is four techniques for making the non-idempotent ones safe.

1. Idempotency keys for writes

The client generates a unique key (a UUID) once per logical operation and sends it with the request — and with every retry of it. The server remembers which keys it has processed and what it answered.

POST /payments
Idempotency-Key: 6c0b2a7e-1d4f-4f3a-9a52-2f0f8c3e9b11

{"amount": 4900, "currency": "INR", "order_id": "ord_812"}
The client sends a payment with idempotency key K. The server stores K, charges once and records the response, but the response is lost on the way back. The client retries with the same key K. The server finds K already done and returns the stored response without charging again. ClientServerDatabasePOST /payments · Key: KINSERT key K (in_progress)charge ₹49 · mark K done + response✗201 lost (timeout)retry · same Key: KK exists, status donestored 201 replayed — charged once
The work succeeded; only the answer was lost. The key turns the retry into a lookup.

The server side is where the subtlety is:

CREATE TABLE idempotency_key (
  key          text PRIMARY KEY,
  request_hash text NOT NULL,           -- reject a reused key with a different body
  status       text NOT NULL,           -- 'in_progress' | 'done'
  response     jsonb,
  created_at   timestamptz DEFAULT now()
);
  1. Insert the key first, with status = 'in_progress', in its own statement. The primary key makes the insert itself the lock: a concurrent duplicate fails the insert instead of racing.
  2. Do the work. Ideally in the same database transaction as marking the key done, so “did the work” and “remembered doing it” can’t disagree.
  3. Store the response and set status = 'done'.
  4. On a duplicate: if done, return the stored response exactly; if in_progress, return 409 so the client retries later; if the request body’s hash differs, return 422 — the client reused a key for a different operation, which is a bug.
Where candidates lose it

“Check if the key exists, and if not, process” is a race: two retries arriving together both see no key and both process. The check and the claim have to be one atomic step — a unique constraint on insert, or SET NX in Redis. The same shape as the version check in the locking lesson.

Keep keys for longer than any client will retry — Stripe keeps them for 24 hours — then expire them. And the key must come from the client: a key generated by the server on each request is unique per retry, which is exactly what you don’t want.

2. Set state, don’t just change it

The cheapest idempotency is an operation that is naturally safe to repeat.

When you can, redesign the message so it carries the resulting state rather than the delta: not “user gained 10 points”, but “user’s points are now 340 as of event 9,182”. Replaying it twice changes nothing.

3. Conditional database updates

When the operation is inherently a change, make it conditional on the state it expects:

-- Mark an order paid exactly once, however many times the webhook arrives.
UPDATE orders
   SET status = 'paid', paid_at = now()
 WHERE id = 'ord_812' AND status = 'pending';

The first delivery updates one row; every duplicate updates zero and does nothing. The same idea works with a version column, or with a processed-events table for consumers:

BEGIN;
INSERT INTO processed_event (event_id) VALUES ('evt_9182');   -- fails on a duplicate
UPDATE wallet SET points = points + 10 WHERE user_id = 42;
COMMIT;

The insert and the effect commit together, so a duplicate fails the insert and rolls back the effect. This is the standard pattern for an idempotent consumer, and it only works when the dedupe record and the effect live in the same database.

4. Track side effects

The database part is the easy part. Emails, push notifications, webhooks and calls to other companies’ APIs cannot be rolled back, and they are where duplicates reach real people.

Saying it in an interview

Say it like this

“The client sends an idempotency key with every payment request, and the same key on retries. The server inserts the key with a unique constraint before doing anything, processes the payment in the same transaction as marking the key done, and replays the stored response for duplicates. The provider gets our order id as its idempotency key, and the payment-captured webhook does a conditional UPDATE ... WHERE status = 'pending', so a second webhook is a no-op.”

The follow-ups, and the one-line answers

  1. “Can’t you just get exactly-once delivery?” No; at-least-once delivery plus idempotent handling gives exactly-once effect.
  2. “Who generates the idempotency key?” The client, once per logical operation, reused on every retry.
  3. “Two retries arrive at the same moment?” The unique constraint on the key makes one insert win; the other gets 409 and retries.
  4. “How long do you keep keys?” Longer than the longest client retry window — a day is typical — then expire.
  5. “How do you make a Kafka consumer idempotent?” Upsert by key, or record the event id in the same transaction as the effect.
  6. “What about the email?” Outbox: record the intent transactionally, send from a worker that marks it sent.