Idempotent vs Safe HTTP Methods Explained
On this page
Why retries make idempotency matter
A mobile client sends a payment request on a train. The connection drops before the response arrives. Did the payment happen? The client can't know, so it retries. Whether that retry is harmless or charges the customer twice depends on the API's design.
Safe vs idempotent HTTP methods
- Safe: the request doesn't change server state. Reading is safe.
- Idempotent: making the same request once or ten times leaves the server in the same state.
An everyday picture: pressing an elevator's call button five times still brings one elevator. That's idempotent. Pressing a vending machine's buy button five times can buy five drinks. That's not, and POST behaves like the vending machine unless you design it otherwise.
| Method | Safe | Idempotent | Why |
|---|---|---|---|
| GET, HEAD, OPTIONS | Yes | Yes | Only read |
| PUT | No | Yes | "Set the resource to this"; repeating sets the same thing |
| DELETE | No | Yes | After the first delete it's gone; repeating doesn't change that (the status may differ) |
| PATCH | No | Not guaranteed | {"name": "Ana"} is idempotent; "increment count" isn't |
| POST | No | No | Each call can create something new |
Clients, proxies and libraries rely on this table: they may retry GET, PUT and DELETE automatically after network errors, but not POST. Keep the promises: a GET that changes data (GET /emails/send) will be triggered by prefetching browsers, crawlers and retries.
Making POST safe to retry with idempotency keys
The client generates a unique key per logical operation (a UUID) and sends it with every attempt. The server stores the key with the result and replays that result for repeats. Tested against a small Express API:
POST /payments Idempotency-Key: 6b1f3a2e-7c41-4d7e-9a8f-0c2d5e1b9f44
{"amount":4200,"currency":"USD","customerId":"cus_482"}
HTTP/1.1 201 Created
{"id":"pay_1","amount":4200,"status":"succeeded"}
# same request again, e.g. after a timeout
HTTP/1.1 201 Created
Idempotent-Replayed: true
{"id":"pay_1","amount":4200,"status":"succeeded"}
# same key, different body
{"type":"https://api.example.com/errors/idempotency-key-reused",
"title":"Key was used with a different request","status":422}
GET /debug/charges
{"charges":1}One charge, however many retries. The server logic:
const seen = idem.get(key);
if (seen) {
if (seen.fingerprint !== fingerprint) // a hash of the request body
return problem(res, 422, 'idempotency-key-reused', 'Key was used with a different request');
return res.status(seen.status).set('Idempotent-Replayed', 'true').json(seen.body);
}
// ... perform the charge, then store { fingerprint, status, body } under the keyThe client side matters just as much: the key is created once per payment, before the first attempt, and reused on every retry. Tested against the same kind of server, with the first response deliberately slower than the client's timeout:
async function createPayment(payment) {
const key = crypto.randomUUID(); // once per logical payment
for (let attempt = 1; attempt <= 4; attempt++) {
try {
const res = await fetch('/payments', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Idempotency-Key': key },
body: JSON.stringify(payment),
signal: AbortSignal.timeout(1000),
});
if (res.status < 500 && res.status !== 429) return res.json();
} catch { /* timeout or network error: retry with the same key */ }
await new Promise(r => setTimeout(r, 200 * 2 ** attempt * Math.random())); // backoff with jitter
}
throw new Error('payment status unknown, check before retrying');
}{"attempt":2,"replayed":"true","body":{"id":"pay_1","status":"succeeded"}} charges: 1The first attempt timed out on the client even though the server had charged the card. The second attempt, with the same key, got the stored result back. A key generated inside the loop would have charged twice.
Production details:
- Store the key and result in the same database transaction as the charge, so a crash can't leave one without the other (see the distributed systems course).
- Handle concurrent duplicates: a unique constraint on the key lets one request win; the other waits or gets a
409while it's in progress. - Expire keys after a window longer than any client's retry period (Stripe keeps them at least 24 hours).
- The IETF is standardizing the
Idempotency-Keyheader in an HTTP working group draft; Stripe, PayPal and Adyen already use it.
Check yourself
Yes. Idempotency is about server state: after the first call the resource is gone, and repeating it doesn't change that, even if the status code differs.
The server recognizes repeats by the key; a new key looks like a new operation and would be processed again.
It almost certainly means a client bug, such as reusing a key across different payments. Replaying the stored result would silently ignore the new request's intent, so return an error, often 422, that the developer will notice.
Each attempt looks like a new payment to the server, so a retry after a timeout can charge twice. Generate the key once per logical operation and reuse it.