All writing
2 min read

Idempotency is a product feature, not a database detail

Why retries are normal, duplicate side effects are not, and how to design an idempotency boundary that clients can actually use.

  • API design
  • reliability

A client sends a payment request. The connection drops after the server commits. The client retries. Did it charge once or twice?

The database did its job. The API contract did not.

Retries are normal

Timeouts, mobile networks, load balancer resets, and process restarts all produce retries. A backend that treats every retry as a new intent will eventually duplicate work. The fix is not "make the network reliable". The fix is an idempotency boundary.

What an idempotency key must guarantee

An idempotency key binds one client intent to one server outcome for a defined window.

sequenceDiagram; participant C as Client; participant A as API; participant S as Store; C->>A: POST /payments + key; A->>S: reserve key; alt first request; A->>A: process; A->>S: store response; else duplicate; S-->>A: existing response; end; A-->>C: same response
Reserve, process, persist, replay

Three properties matter:

  1. One owner. The first request to reserve the key owns processing. Concurrent duplicates wait or receive a conflict; they do not run the side effect.
  2. One stored outcome. The response is persisted with the key, not recomputed. A replay returns the same body and status.
  3. A finite window. Keys expire. An infinite idempotency store becomes an unbounded history of every request.

Where teams get it wrong

Hashing the body as the key. Two intentional payments with the same amount and recipient are not duplicates. The client must choose the key.

Storing the key after the side effect. A crash between the side effect and the key write creates a duplicate on retry. Reserve first, then process, then persist the outcome.

Returning only success. A failed request can be retried too. Store the terminal failure, or explicitly document that the key is released on failure.

Hiding the key from clients. If clients cannot generate a key per intent, they will retry with no boundary. Make it part of the public contract.

A practical contract

  • Accept Idempotency-Key on mutating endpoints.
  • Reject keys that are too short, too long, or reused with a different body.
  • Return the stored response on replay, including the original request ID.
  • Expire keys after a documented window.
  • Expose the key in logs so support can trace a duplicate report.

The test that matters

Send the same key twice, concurrently, with the same body. Assert one side effect and two identical responses. Then send the same key with a different body and assert a conflict.

If that test is not in your suite, idempotency is a hope, not a guarantee.