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".
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.
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 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()
);
- 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. - 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.
- Store the response and set
status = 'done'. - On a duplicate: if
done, return the stored response exactly; ifin_progress, return409so the client retries later; if the request body’s hash differs, return422— the client reused a key for a different operation, which is a bug.
“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.
UPDATE account SET status = 'closed'is idempotent.UPDATE counter SET n = n + 1is not.- “Set the shipping address to X” is idempotent. “Add 1 to the cart quantity” is not.
- Kafka consumers that upsert by primary key are idempotent. Consumers that insert a new row per message are not.
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.
- Record intent before acting. Write “send welcome email to user 42” as a row, keyed so it can exist once, in the same transaction as the business change. A separate worker sends it and marks it sent. This is the outbox pattern, and it turns “maybe sent twice” into “sent at least once, and the worker can check before sending again”.
- Pass the key downstream. When you call a payment provider, send your own idempotency key — derived from your order id, so a retry of your operation sends the same key. Razorpay, Stripe and most payment APIs honour one.
- Accept that some effects are at-least-once. A duplicate push notification is annoying; a duplicate charge is a refund and an apology. Spend the effort where the duplicate costs most.
Saying it in an interview
“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
- “Can’t you just get exactly-once delivery?” No; at-least-once delivery plus idempotent handling gives exactly-once effect.
- “Who generates the idempotency key?” The client, once per logical operation, reused on every retry.
- “Two retries arrive at the same moment?” The unique constraint on the key makes one insert
win; the other gets
409and retries. - “How long do you keep keys?” Longer than the longest client retry window — a day is typical — then expire.
- “How do you make a Kafka consumer idempotent?” Upsert by key, or record the event id in the same transaction as the effect.
- “What about the email?” Outbox: record the intent transactionally, send from a worker that marks it sent.