← Lessons

quiz vs the machine

Gold1400

Concurrency

Idempotency Keys For Retries

A client supplied key that makes a repeated request take effect once.

5 min read · core · beat Gold to climb

Idempotency Keys For Retries

Networks lose responses. A client sends a payment request, the server charges the card, but the reply never arrives. The client cannot tell whether the charge happened, so it retries, and a naive server charges twice.

An idempotency key fixes this. The client generates a unique key, often a random identifier, and attaches it to the request. The server stores the result keyed by that value. If a second request arrives with the same key, the server skips the work and returns the saved result instead of acting again.

The key insight is that the client owns the key, so a retry of the same logical operation carries the same key, while a genuinely new operation carries a fresh one. The server can therefore tell a duplicate from a new request.

  • Generate once per operation A retry reuses the original key, never a new one.
  • Store the outcome The server records both the key and the response it produced.
  • Bound the lifetime Keys are kept long enough to cover realistic retries, then expired.

There is a subtlety. The server must record the key and perform the effect atomically, otherwise two concurrent retries could both see no key yet and both execute. A unique constraint on the key column or a transaction provides that atomicity.

Key idea

An idempotency key lets a client safely retry a request because the server records the key with its result and replays that result instead of acting twice.

Check yourself

Answer to earn rating on the learn ladder.

1. Why must a retry reuse the original idempotency key?

2. What must be atomic to make idempotency keys safe under concurrency?

3. Who generates the idempotency key?