Idempotency

Make an operation safe to repeat, so retries and duplicate messages can't charge a card twice.

Idempotency in 30 seconds

  • What: doing an operation twice has the same effect as doing it once — so retries and duplicates are safe.
  • Why you need it: networks lose responses and clients retry; queues deliver at-least-once. Unprotected, that double-charges a card.
  • The pattern: client sends a unique idempotency key per action; server records it and replays the original result on a repeat.
  • The race: two retries can both see 'no key yet' and both run — the check-and-record must be atomic (unique constraint or set-if-absent).
  • HTTP: GET, PUT, DELETE are idempotent by design; POST is not — which is exactly why POST actions need a key.
  • Big win: it's what lets queues use simple at-least-once delivery instead of chasing true exactly-once.

The elevator button you press twice

You walk up to an elevator and press the call button. Nothing seems to happen, so you press it again. And maybe a third time. The elevator still comes exactly once — pressing the button five times doesn't summon five elevators. The button is idempotent: repeating the action has the same effect as doing it once.

Now imagine a button that wasn't like that — where every impatient press queued up another elevator ride. That's what most 'do something' operations in software are like by default: press 'Pay' twice because the page hung, and you might get charged twice. Idempotency is how we make the important buttons behave like the elevator.

The problem it solves

Networks are unreliable. A client sends a request, the response gets lost, and the client — not knowing if it worked — retries. Queues redeliver messages 'at least once'. Without protection, that second attempt runs the operation again: a double charge, a duplicate order, a doubled balance. Idempotency is the property that doing something twice has the same effect as doing it once, which makes all those retries safe.

Why retries are unavoidable (so you can't just 'not retry')

A tempting dodge: 'if duplicates are the problem, just don't retry.' But retries aren't a bug you can turn off — they're a direct consequence of how networks and distributed systems work. The duplicate you fear is baked in:

  • The lost-response problem. The server did the work, but the reply vanished on the way back. The client has to retry — it can't tell success from failure.
  • Timeouts are ambiguous. When a call times out, you genuinely don't know if it succeeded. Retrying is the only safe-looking option.
  • Queues guarantee at-least-once. To never lose a message, a queue will redeliver when unsure — which means sometimes delivering twice.
  • Load balancers and clients retry automatically. Much retry behavior is built into libraries and infrastructure you don't control.

So the duplicate request is coming whether you like it or not. The only real question is whether your operation is safe when it arrives — and that's exactly what idempotency guarantees.

Same key twice: the server does the work once, then replays the recorded result.

The core idea, plainly

Some operations are naturally idempotent — 'set the balance to 100' gives the same result however many times you run it. Others are not — 'add 100 to the balance' doubles up if repeated. The design job is to turn risky, non-idempotent operations into safe ones by giving each logical action a unique idempotency key and remembering which keys you've already processed.

OperationIdempotent?Why
SET balance = 100YesRunning it again lands in the same state.
balance = balance + 100NoEach repeat adds again — duplicates compound.
DELETE /orders/42YesAlready-deleted stays deleted.
POST /charges (new charge)NoEach call creates another charge — needs a key.

The idempotency key pattern

The client generates a unique key per logical operation (e.g. a UUID for 'this specific checkout') and sends it with the request. The server records the key the first time it processes it. If a retry arrives with the same key, the server recognizes it and returns the original result instead of doing the work again. This is exactly how payment APIs make 'charge this card' safe to retry.

The client attaches a stable key to the action (http)
POST /charges HTTP/1.1
Host: api.example.com
Idempotency-Key: 9b2c-checkout-7f41a   # one key per logical checkout
Content-Type: application/json

{ "amount": 4200, "card": "tok_visa" }

# A retry after a lost response sends the EXACT same key ->
# the server recognizes it and replays the first result instead of charging again.
Server-side idempotency (python)
def charge(idempotency_key, amount, card):
    existing = store.get(idempotency_key)
    if existing is not None:
        return existing            # replay the original result; do NOT charge again
    result = payment_provider.charge(amount, card)
    store.set(idempotency_key, result, ttl="24h")
    return result

The gap a naive check leaves — the race

Look again at that server code: it reads the key, then writes it. Between those two lines there's a dangerous gap. If two retries land at almost the same instant, both can read 'no key yet' before either has written — and both go on to charge the card. The simple version is safe against sequential retries but wide open to simultaneous ones.

Why read-then-write loses under concurrency (pseudocode)
# Two retries arrive together. Time flows downward:
Retry A: store.get(key) -> None      # 'no key yet'
Retry B: store.get(key) -> None      # 'no key yet' (A hasn't written!)
Retry A: payment_provider.charge()   # CHARGE #1
Retry B: payment_provider.charge()   # CHARGE #2  <-- the double charge
Retry A: store.set(key, result)
Retry B: store.set(key, result)      # overwrites, damage already done

Closing the race with one atomic step

The fix is to collapse 'check' and 'record' into a single atomic operation that the datastore guarantees only one caller can win. Instead of reading first, you try to claim the key — and let the loser be rejected cleanly:

Let the database enforce uniqueness atomically (sql)
-- A UNIQUE constraint makes the key the referee, not your code:
CREATE TABLE idempotency (
  key        TEXT PRIMARY KEY,   -- only ONE row per key can ever exist
  result     JSONB,
  created_at TIMESTAMPTZ DEFAULT now()
);

-- First retry wins the insert; the second gets a conflict, not a second charge:
INSERT INTO idempotency (key) VALUES ('9b2c-checkout-7f41a')
ON CONFLICT (key) DO NOTHING
RETURNING key;   -- returns a row only for the winner -> only it proceeds to charge

Now the datastore, not your application logic, is the single arbiter. The winner inserts the row and does the work; the loser's insert conflicts, so it knows to wait for and replay the winner's result. The same idea works with an atomic 'set if absent' (SET key val NX in Redis) when you want a fast store instead of the database.

HTTP verbs and idempotency

By design, GET, PUT, and DELETE are idempotent — fetching, replacing, or deleting the same resource repeatedly lands in the same state. POST is not, because it typically creates something new each time. That's why POST endpoints for actions like payments or orders are exactly the ones that need an explicit idempotency key.

VerbIdempotent by design?Why / what to do
GETYesReads never change state.
PUTYesReplaces the resource with the same body each time.
DELETEYesDeleting an already-gone resource is still 'gone'.
POSTNoCreates something new each call — attach an idempotency key.

Idempotency sounds like a narrow API detail, but it's really the quiet contract that lets an unreliable, retrying, at-least-once world stay correct — it's what makes 'just retry' a safe default.

Why it matters

  • It converts scary retries into harmless ones, so clients and queues can retry freely without corrupting data.
  • It's the practical path to exactly-once effects without the cost and fragility of exactly-once delivery.
  • It protects the moments that cost money or trust — payments, orders, balance changes — from silent duplication.

If ignored

  • Double charges, duplicate orders, and doubled balances the first time a response gets lost on the wire.
  • A non-atomic check-then-write that still lets two simultaneous retries both slip through under load.
  • Queue consumers that quietly reprocess redelivered messages and multiply every side effect.

Where it fits

  • Lives in the write path, on any operation with side effects — especially POST-style actions.
  • Pairs with message queues, where at-least-once delivery assumes an idempotent consumer on the other end.
  • Sits close to distributed locking as the lighter-weight way to make an action safe to run once.

Related topics

  • Message queues: at-least-once delivery only works because consumers are idempotent
  • API styles: which HTTP verbs are idempotent, and why POST actions need a key
  • Distributed locking: the heavier alternative — idempotency often removes the need for a lock
  • Pub/Sub & CDC: events can redeliver, so subscribers must be idempotent too

Interview lens

Questions it unlocks

  • How do you prevent double charges when a payment request is retried?
  • A message queue delivers at-least-once — how do you avoid duplicate processing?
  • Which HTTP methods are idempotent?

60-second answer

I make side-effecting operations safe to repeat with an idempotency key: the client sends a unique key per logical action, the server records it on first processing, and any retry with the same key replays the original result instead of redoing the work. The check-and-record must be atomic to beat the race where two retries both slip through. This is how payment APIs make 'charge card' retry-safe, and it's why queues can use at-least-once delivery with idempotent consumers instead of chasing true exactly-once.

Common traps

  • Assuming retries are harmless without making the operation idempotent.
  • Doing a non-atomic check-then-write and still allowing duplicates under a race.
  • Forgetting POST is not idempotent and is exactly what needs a key.

Search topics

↑↓ to move · Enter to open · Esc to close