Track 06 · Lesson 4 of 8APIs and servers

Track 06 · APIs and servers

Idempotency and retries

Lesson 4 of 8· 6 min

Networks fail in a nasty way: the request can succeed while the response gets lost. The client can’t tell, so it retries. If the server does the work again, a customer pays twice.

Pay over a flaky network

Lose the response, then send a key

  1. Press “Pay €30”.
MethodSafe to repeat?Why
GETYesReads only
PUTYesSets the same final state every time
DELETEYesGone is gone; a second delete changes nothing
POSTNoCreates something new each time, unless you send a key
PATCHDependsDepends: “size = large” yes, “add one topping” no

Idempotent means “safe to repeat”#

An operation is idempotent if doing it twice leaves things the same as doing it once. GET, PUT and DELETE are idempotent by design; POST is not, because each one creates something new.

Idempotency keys#

For operations that must not happen twice (payments, orders, emails), the client generates a unique key per action and sends it in a header such as Idempotency-Key. The server stores the key with the result; when the same key arrives again, it returns the saved result instead of redoing the work. Payment providers like Stripe work exactly this way.

The key belongs to the action, not the attempt: generate it when the person presses “Pay”, and reuse it for every retry of that press.

Retry politely#

Retry only on failures that might be temporary (timeouts, 429, 503), wait longer each time (exponential backoff with a little randomness), and give up after a few attempts. Thousands of clients retrying instantly in lockstep can knock over a recovering server.

Check yourself

When should the client generate a new idempotency key?