Skip to content

Design API Error Handling and Backoff

Goal

Implement a request policy that neither retries forever nor hides authentication failures.

Prerequisites

Be able to record HTTP status, API error code, request ID, and attempt count.

Steps

  1. Treat 400, 401, 403, and model_not_found as terminal errors requiring corrected input or configuration.
  2. Retry only 429 responses, timeouts, and explicitly temporary service errors.
  3. Use exponential backoff with jitter, such as 1, 2, and 4 seconds, with a maximum of three retries.
  4. Prefer a Retry-After value when the response provides one.
  5. Log request ID, status, error code, and delay without logging tokens or sensitive bodies.
  6. Verify branches with simulated 401, 429, and repeated timeout responses.

Expected result

Terminal errors return immediately, retryable errors recover within the limit, and exhausted retries leave a useful diagnostic record.

Troubleshooting

  • Simultaneous retries create a spike: add random jitter.
  • Work is duplicated: use idempotency keys for side effects or disable automatic retries.
  • Logs expose secrets: centrally redact authorization headers and sensitive fields.

OpenAI-compatible · Multimodal AI gateway