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.
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#
- appAttempt 1: POST /payments (no key)
- serverCharge ₹499
- netReply lost on the way back (lift, tunnel, weak 4G)
- appAttempt 2: timed out waiting, so retry
- serverCharge ₹499
- app200 OK received. Show "Order placed".