Idempotency Keys: Making Retries Safe
Networks fail and clients retry. Idempotency keys make sure a retry never charges twice or creates a duplicate.

A client sends a request to create a payment. The server processes it, but the response is lost to a timeout. The client, doing the sensible thing, retries. Without protection, the customer is charged twice. Idempotency keys solve this class of problems by making repeated requests produce the same result as a single request.
The client generates a unique key per logical operation, usually a UUID, and sends it in a header. The server stores the key with the result of the first execution. When the same key arrives again, the server returns the stored result instead of performing the action a second time.
Details matter. Store the key and the response atomically with the operation itself, so a crash between "charge the card" and "save the key" cannot cause a duplicate. Include a fingerprint of the request body so the same key with different data is rejected rather than silently accepted. Expire keys after a reasonable window such as 24 hours.
Idempotency extends beyond payments. Webhook handlers should treat event IDs as keys, because providers redeliver events. Background jobs should be safe to run twice. Email sending, record creation and external API calls all benefit from the same discipline.
Design for retries from the beginning. Adding idempotency to a system after duplicates have appeared means also cleaning up the duplicates, which is far more work than a header and a table.



