Doing the same request twice should not charge the customer twice.
An operation is idempotent if doing it once or many times gives the same final result.
Idempotent comes from maths: f(f(x)) = f(x). In APIs it means: sending the same request again does not change the result any further.
A safe method does not change anything at all (GET). Every safe method is idempotent. But some idempotent methods (PUT, DELETE) do change data, so they are not safe.
Networks fail. Timeouts happen. The client often cannot know whether its request worked. The only safe move is to retry. Idempotency makes that retry safe.
| Method | Meaning | Safe? | Idempotent? |
|---|---|---|---|
| GET | Read | Yes | Yes |
| HEAD / OPTIONS | Read info only | Yes | Yes |
| PUT | Replace with this value | No | Yes |
| DELETE | Remove | No | Yes |
| PATCH | Change a part | No | Depends (“set x=5” yes, “add 5” no) |
| POST | Create / run an action | No | No (add a key to make it so) |
POST /payments
Idempotency-Key: 7f3c9a2e-1d4b-4a8e-9c11-5b0e6a3d2f10
Content-Type: application/json
{ "orderId": "A-1001", "amount": 100, "currency": "INR" }
--- 1st call: 201 Created { "paymentId": "p_55", "status": "paid" }
--- retry: 201 Created { "paymentId": "p_55", "status": "paid" } (same, no new charge)def pay(key, body):
saved = store.get(key)
if saved:
if saved.request_hash != hash(body):
return 422 # key reused with a different request
return saved.response # repeat: no new charge
with transaction():
result = charge_card(body)
store.put(key, hash(body), result)
return result| Term | Meaning in easy words |
|---|---|
| Idempotent | Doing it many times has the same final effect as doing it once |
| Safe method | A method that changes nothing (like GET) |
| Retry | Sending the same request again after a failure or timeout |
| Idempotency key | A unique id sent with a request so the server can spot repeats |
| At-least-once | A message will arrive once or more, so duplicates are possible |
| Exactly-once effect | Duplicates may arrive, but the result happens only once (done with idempotency) |
| Deduplication | Finding and ignoring repeats |
| UUID | A long random id that is unique in practice |
| TTL | How long a stored key is kept before it is deleted |
| Backoff | Waiting longer between each retry, so a struggling server can recover |
| Choice | We gain | We lose |
|---|---|---|
| Natural idempotency (PUT, set) | No extra storage, simple | Not always possible (“add to balance”) |
| Idempotency key | Works for any POST | Storage, lookup, expiry rules |
| Unique database rule | Strong guarantee | Only blocks duplicate rows; the error must be handled |
| No idempotency | Least work | Duplicates and angry users |
Idempotency-Key that the client makes once per action.