Error Handling in Idempotent APIs
What you'll learn: How to return consistent error responses for duplicate requests and distinguish between retriable and non-retriable failures in idempotent API design.
The Challenge of Consistent Error Responses
When a client retries a request using the same idempotency key, your API must return exactly the same response as the original request—including errors. If the first attempt failed with a validation error, the retry should return that same validation error, not process the request or return a different error.
Think of it like filing the same insurance claim twice. If it was rejected for "missing signature" the first time, resubmitting the identical claim should return the same rejection reason, not suddenly process it or give a different error.
Retriable vs Non-Retriable Failures
Not all errors should be retried:
Non-retriable errors (4xx range):
400 Bad Request: Invalid data format409 Conflict: Business rule violation422 Unprocessable Entity: Validation failure
These indicate client mistakes. The stored idempotency response should preserve these errors, and retries should return the same error without reprocessing.
Retriable errors (5xx range, timeouts):
500 Internal Server Error: Temporary service issues503 Service Unavailable: Overload or dependency down- Network timeouts
For retriable errors, the idempotency key might not have a stored result yet (if processing never completed). The client can safely retry, potentially getting a successful response.
Implementation Strategy
When handling a request with an idempotency key:
- Check if the key exists in storage
- If found, return the stored response (success or error)
- If not found, process the request
- Store both success and non-retriable error responses
- Don't store retriable errors—let the client retry
Key Takeaway: Idempotent APIs must cache error responses for duplicate requests and clearly distinguish between client errors (non-retriable, must be cached) and transient failures (retriable, allow fresh attempts).