Library
9 min read

Idempotency keys

You pay for a Zomato order in a lift. The spinner spins, the screen says "Something went wrong", and you are left with the worst question in distributed systems: did it happen? Maybe the request never reached the server. Maybe the server charged you and the reply got lost on the way back. From your phone, those two look identical.

The only safe thing a client can do after a timeout is try again. So the server must make trying again safe. An operation is idempotent if doing it twice has the same effect as doing it once. An idempotency key is how you make a non idempotent operation, like "charge ₹499", behave that way.

Your answer

A payment request times out. The app retries automatically. How does the server know the second request is a retry of the first and not a genuine second purchase of the same thing?

Try it#

Pay ₹499 for an order, on a bad connection
1
  1. appAttempt 1: POST /payments (no key)
  2. serverCharge ₹499
  3. netReply lost on the way back (lift, tunnel, weak 4G)
  4. appAttempt 2: timed out waiting, so retry
  5. serverCharge ₹499
  6. app200 OK received. Show "Order placed".
Customer charged₹998 (2 times)
The customer pressed Pay once (or the app retried on its own) and was charged ₹998. Every retry was a perfectly reasonable thing for the app to do, because a timeout does not tell you whether the server acted. Turn the key on.