15. Idempotency
15. Idempotency
Network requests can fail for reasons entirely outside your control — a timeout, a dropped connection, a proxy that swallows the response. Idempotency ensures that retrying a failed request does not produce duplicate side effects.
Which Methods Are Idempotent by Default?
The HTTP specification defines the following methods as idempotent:
- GET, HEAD, OPTIONS — these do not modify state, so repeating them is always safe.
- PUT — replaces the entire resource with the provided payload. Sending the same PUT twice produces the same end state.
- DELETE — removes the resource. A second DELETE to the same URL returns
404(the resource is already gone), but no duplicate action occurs.
PATCH is not guaranteed to be idempotent unless your implementation ensures it. Applying the same partial update twice should produce the same result as applying it once — design your patch logic with this in mind.
Making POST Idempotent with Idempotency Keys
POST is inherently non-idempotent because it creates a new resource each time. In situations where duplicate creation is dangerous — payment processing, order placement, account creation — use an Idempotency-Key header:
POST /payments
Idempotency-Key: 550e8400-e29b-41d4-a716-446655440000
Content-Type: application/json
{
"amount": 2500,
"currency": "GBP",
"customer_id": 42
}
The server stores the key alongside the result of the first successful request. If an identical key arrives again, the server returns the same response without executing the operation a second time.
Guidelines
- Let the client generate the key. Use a UUID or another globally unique value. The server must not generate it, because the client needs to know the key before the request completes so it can retry with the same value.
- Set a reasonable TTL. Idempotency keys do not need to live forever. A window of 24 hours covers the vast majority of retry scenarios.
- Document which endpoints support idempotency keys and what behaviour the client should expect on a duplicate submission.