Course contentsShow
← System Design
Lesson 1018 of 1,91926. Idempotency and RetriesFree lesson

Error Handling in Idempotent APIs

Return consistent error responses for duplicate requests and distinguish between retriable and non-retriable failures.

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 format
  • 409 Conflict: Business rule violation
  • 422 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 issues
  • 503 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:

  1. Check if the key exists in storage
  2. If found, return the stored response (success or error)
  3. If not found, process the request
  4. Store both success and non-retriable error responses
  5. 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).