Idempotency Keys For Retries
Networks lose responses. A client sends a payment request, the server charges the card, but the reply never arrives. The client cannot tell whether the charge happened, so it retries, and a naive server charges twice.
An idempotency key fixes this. The client generates a unique key, often a random identifier, and attaches it to the request. The server stores the result keyed by that value. If a second request arrives with the same key, the server skips the work and returns the saved result instead of acting again.
The key insight is that the client owns the key, so a retry of the same logical operation carries the same key, while a genuinely new operation carries a fresh one. The server can therefore tell a duplicate from a new request.
- Generate once per operation A retry reuses the original key, never a new one.
- Store the outcome The server records both the key and the response it produced.
- Bound the lifetime Keys are kept long enough to cover realistic retries, then expired.
There is a subtlety. The server must record the key and perform the effect atomically, otherwise two concurrent retries could both see no key yet and both execute. A unique constraint on the key column or a transaction provides that atomicity.
Key idea
An idempotency key lets a client safely retry a request because the server records the key with its result and replays that result instead of acting twice.