Celmir

Insights · 5 min read

Idempotent APIs: the simplest way to make retries safe

Networks fail, clients retry, and a request that runs twice can create two orders. Idempotency keys turn that risk into a non-event.

Every distributed system eventually sends the same request twice. A mobile app loses signal after tapping a button, a load balancer times out, a background job restarts halfway through. If the server treats each copy as new work, the user gets two orders, two emails or two charges.

What idempotency means

An operation is idempotent when running it several times has the same effect as running it once. Reads are naturally idempotent. Creating things is not, unless you design for it.

The idempotency key pattern

  1. The client generates a unique key for each logical action, for example when the user opens the checkout form, and sends it with every attempt.
  2. The server stores the key together with the result of the first successful attempt.
  3. When the same key arrives again, the server returns the stored result instead of doing the work again.

Details that matter

  • Store the key and the work in one transaction. Otherwise a crash between the two leaves you guessing.
  • Handle concurrent duplicates. Two copies can arrive at the same moment. A unique constraint in the database is the simplest guard.
  • Check that the request matches. The same key with a different body is a client bug and should be rejected, not silently accepted.
  • Expire keys deliberately. Keep them at least as long as clients may retry.

Designing an API that other systems depend on? Talk to our engineers.