Idempotency Key

A client-supplied identifier that lets a server recognise a retried request as the same request, so a payment or order is created once even when the network says otherwise.

Definition#

An idempotency key is a unique value the client generates for one logical operation and sends with the request, conventionally in an Idempotency-Key header. The server stores the outcome against that key. If the same key arrives again, the server returns the stored outcome instead of performing the work a second time.

It exists because a failed response is ambiguous. A timeout tells the client nothing about whether the charge went through, and retrying is the only way to find out — safely only if the server can tell a retry from a new request.

Why it matters#

Networks fail after the server has already committed. Without idempotency keys the client must choose between two bad options: retry and risk charging a customer twice, or give up and risk losing a completed order. With them, retrying is always safe, which means clients can retry automatically, and an ordinary connection blip stops being a money-losing event.

How it works#

On arrival the server tries to claim the key by inserting a row in a unique index, inside the same transaction as the work itself. A successful claim means this is the first attempt: do the work, store the response, return it. A conflicting claim means a duplicate: return the stored response, or 409 if the first attempt is still in flight.

Claim and result in one transaction
BEGIN;
  INSERT INTO idempotency (key, endpoint, request_hash, state)
  VALUES (?, ?, ?, 'in_progress');   -- unique on (key, endpoint)

  -- ... perform the charge ...

  UPDATE idempotency
     SET state = 'done', status_code = 201, response = ?
   WHERE key = ? AND endpoint = ?;
COMMIT;

What it does and does not guarantee#

PropertyGuaranteed?
The same key never does the work twiceYes, if the claim and the work share one transaction
Two different keys for the same intentNo — that is two operations, and the client must reuse the key on retry
Safe concurrent retriesYes: the second caller sees the in-progress claim and waits or gets 409
Protection foreverNo: keys expire, typically after 24 hours to 7 days

Design patterns#

Common pitfalls#

  • Generating the key on the server, which makes every retry a new operation and defeats the entire mechanism.
  • Writing the key outside the transaction that does the work, leaving a window where the work commits and the claim does not.
  • Treating a duplicate as an error, when the client's retry deserves the original success response.
  • Reusing one key for a whole session rather than one per operation, which quietly suppresses legitimate second orders.
  • Keeping keys forever, which turns a small helper table into the largest one in the database.