Web and APIs
What is Idempotency?
Definition
An operation is idempotent when performing it many times leaves the system in the same state as performing it once.
Also known as: Idempotent operation
Idempotency in more detail
Idempotency is what makes retrying safe. A network can fail after your request arrived but before the response got back, and you cannot tell that case apart from the request never arriving. If the operation is idempotent you simply send it again; if it is not, retrying might charge a card twice. Setting a value to 5 is idempotent. Adding 1 to it is not.
HTTP builds this into its method definitions. GET, HEAD, PUT and DELETE are idempotent by specification; POST and PATCH are not. That is not a claim about your code — it is a promise you are expected to keep, and clients, proxies and retry libraries rely on it. Note that idempotent is not the same as safe: DELETE is idempotent because deleting an already-deleted thing changes nothing further, but it certainly modifies state, whereas GET is safe because it modifies nothing at all.
When an operation genuinely cannot be idempotent, the standard fix is an idempotency key. The client generates a unique key per logical operation and sends it as a header; the server stores the key with the result of the first request and, on seeing the key again, returns the stored result instead of doing the work twice. This is how payment APIs let you retry a charge without fear, and it is the same pattern webhook consumers use with the provider's event id.
Idempotency example
POST /v1/charges
Idempotency-Key: a3f1c9e2-7b6d-4c11-9f01-2d4e5a6b7c8d
{ "amount": 4900, "currency": "usd", "source": "tok_visa" }
# First request -> charge created, result stored against the key
# Retry same key -> the SAME charge is returned, no second charge
# New key -> a second, separate charge
# Idempotent by definition: PUT /users/12 {"name":"Ada"}
# Not idempotent: POST /users {"name":"Ada"}Idempotency — common questions
- Is DELETE idempotent if the second call returns 404?
- Yes. Idempotency is about the resulting state, not the status code. After the first DELETE the resource is gone, and every later DELETE leaves it gone; returning 404 the second time is a description of that unchanged state.
- Why is POST not idempotent?
- Because POST means 'process this data', and the usual result is creating a new subordinate resource. Two identical POSTs are supposed to create two resources, which is exactly why creation endpoints need idempotency keys if clients may retry.
- What is the difference between idempotent and safe?
- A safe method does not change state at all (GET, HEAD, OPTIONS). An idempotent method may change state, but repeating it causes no further change. Every safe method is idempotent; the reverse is not true.
Keep reading
Every definition in the set is indexed A-Z in the developer glossary, and the cheat sheets cover the syntax once you know what you are looking for.
Browse the A-Z glossary