Backend and APIs · Question 16 of 50
What is idempotency, and why do payment APIs need idempotency keys?
Retries, safety, and thinking about failures between systems.
The answer
An operation is idempotent if doing it twice has the same effect as doing it once. GET, PUT and DELETE are meant to be; POST is not. It matters because networks fail at the worst moment: the server charged the card, the response was lost, the client retries and charges again.
The fix is an idempotency key. The client sends a unique key with the request; the server stores the key with the result, and a retry with the same key gets the stored result instead of a second charge. Save the key in the same transaction as the work (a unique constraint), and expire keys after a sensible window.
The picture
client ── POST /pay key=K1 ──▶ server: K1 is new → charge → save (K1, result)
✗ the response is lost
client ── POST /pay key=K1 ──▶ server: K1 seen → return the saved result
(no second charge)What if two retries arrive at the same moment?
Show the answer
A unique constraint on the key, or a lock, lets only one through; the other waits, or gets a 409 and retries.