
The one-sentence version
Pressing the button for a lift is idempotent: press it five times and one lift comes. Placing an order is not, unless someone designed it to be.
Why it comes up
A client sends a payment request and the connection drops before the answer arrives. Did the charge happen? The client cannot know. If it does nothing, a customer may not be charged. If it tries again and the first attempt did go through, the customer is charged twice. Idempotency is what makes trying again safe.
How an idempotency key works
- The client creates a unique key for the thing it wants done, for example one key per order, and sends it with the request.
- The first time the server sees the key, it does the work and stores the key together with the result.
- When the same key arrives again, the server does not repeat the work. It returns the stored result.
POST /charges
Idempotency-Key: order-8841
{ "order": 8841, "amount": 4900 }The key belongs to the intent, not to the attempt. Every retry for the same order sends the same key. A new order gets a new key.
What is idempotent already
- Reading something.
- Setting a value to a fixed number. Setting the stock to 5 twice still gives 5.
- Deleting by id. Deleted twice is still deleted.
Not idempotent without help: adding 1 to a counter, creating a record, sending an email, charging a card.
Questions you will hear in a meeting
- What happens if this job runs twice?
- Who creates the key, the client or the server?
- Where is the key stored, and for how long?
- What do we return on the second attempt: the first result, or an error?
In an interview
It appears in system design whenever a queue, a retry or a payment does. A strong answer names the failure, which is the lost reply, says where the key is stored, and adds that checking the key and writing the result must happen together. Otherwise two requests arriving at the same moment can both pass the check.