Module 5 · Distributed systemsLesson 52 of 887 minIntermediate

Idempotency

An idempotent operation has the same effect whether it runs once or many times. It's what makes retries safe.

Try it

Play "No key" and watch the retry charge the card twice. Then play "Idempotency key".

In a distributed system, you often can't know whether a request succeeded. The response may have been lost. The only safe move is to retry, but a retry of a request that did succeed runs it twice.

An operation is idempotent if running it twice has the same effect as running it once.

Naturally idempotent

  • SET balance = 100 (not balance + 10)
  • DELETE order 7 (deleting again changes nothing)
  • HTTP PUT and DELETE are meant to be idempotent; GET must have no side effects at all.

Not naturally idempotent

  • POST /payments (charge a card)
  • balance = balance + 10
  • "send an email", "create an order"

Idempotency keys

The standard fix, used by Stripe and most payment APIs:

  1. The client generates a unique key for each logical action, like a UUID, and sends it with the request (for example in an Idempotency-Key header).
  2. The server checks: have I seen this key?
    • No: do the work, then store the key with the result.
    • Yes: don't do it again; return the stored result.
  3. Retries reuse the same key.

Store keys for a sensible window (24 hours is common), and make "do the work and save the key" happen in one transaction, or two concurrent retries could both slip through.

Idempotent consumers

Queues deliver at least once, so consumers will see duplicates. Make them idempotent by:

  • recording processed message ids and skipping ones you've seen,
  • using natural keys with unique constraints (INSERT ... ON CONFLICT DO NOTHING),
  • designing state changes as "set to" rather than "add".

Idempotency is what turns "at least once" into "effectively exactly once". That's the next lesson.

Quick check

Which operation is naturally idempotent?