Safe retries for writes
GET requests are naturally safe to retry, but a POST that creates an order or charges a card is not. If the response is lost, the client cannot tell whether the write happened, and retrying might do it twice. The idempotency key header solves this.
How it works
- The client generates a unique key, often a UUID, and sends it in an Idempotency Key header with the request.
- On first receipt, the server processes the request, stores the result keyed by that idempotency key, and returns the result.
- If the same key arrives again, the server skips the work and replays the stored result. The client gets the same answer it would have gotten, with no duplicate side effect.
Design details
- The server must record the key atomically with the side effect, or a crash between the two reopens the duplicate window. A common approach writes the key and the result in the same transaction.
- Keys are stored with a TTL so the table does not grow forever; choose a window longer than the client retry horizon.
- If a request with the same key but a different body arrives, return an error rather than silently serving the old result.
Key idea
An idempotency key lets the server store and replay the result of a write so a retried request produces the same answer without a duplicate effect.