Most backend developers treat LLM API failures like network blips, wrapping calls in simple retry loops. This approach is fundamentally flawed for large language models. When a provider like OpenAI returns a 429 Too Many Requests or a persistent 500 Internal Server Error, hammering the endpoint with immediate retries exacerbates the problem. It burns execution quotas, inflates user latency, and contributes to the 'thundering herd' problem when the upstream service attempts to recover.

The Critical Distinction: Retry vs. Fallback

Production-grade AI systems must decouple retries from fallbacks. A retry is an attempt to send the exact same request to the same provider, suitable only for transient failures like dropped TCP connections or sporadic 503 errors. A fallback, however, routes the request to a completely different provider or model family, such as switching from OpenAI’s gpt-4o to Anthropic’s claude-3-5-sonnet. Mixing these concepts creates fragile systems; for instance, retrying a 429 status code ignores the provider’s explicit signal to pause traffic.

Smart Retries: Exponential Backoff and Jitter

When encountering transient errors, avoid tight loops. Instead, implement exponential backoff combined with jitter. Exponential backoff increases the delay between attempts (e.g., 1s, 2s, 4s), while jitter adds a randomized offset. This prevents thousands of concurrent clients from hitting the recovering server at the exact same millisecond. The source code example demonstrates this using Python’s time.sleep with a calculated base_delay * (2 ** attempt) plus random.uniform(0, 0.5). Crucially, rate limit errors should bypass the retry loop entirely to trigger the fallback layer immediately.

Circuit Breakers: Protecting Your Infrastructure

If a primary provider goes down, executing retries and fallbacks for every single request adds seconds of latency. Circuit breakers solve this by tracking failure rates over a rolling window. If failures exceed a threshold, such as 50% over 10 requests, the circuit 'opens,' bypassing the primary provider entirely. After a cooldown period, the circuit enters a 'half-open' state, sending a single test request to verify recovery. This architecture prevents your application from wasting resources on a known dead endpoint.

Key Takeaways

  • Never retry 429s blindly: Treat rate limits as a trigger to back off or immediately execute a provider fallback.
  • Limit retries: Two to three attempts with jittered backoff are sufficient for network blips.
  • Decouple business logic: Normalize prompts and responses so switching between OpenAI, Anthropic, or Google Gemini requires zero changes in upstream code.

The Bottom Line

Blind retry loops are technical debt. If you aren't implementing circuit breakers and multi-provider fallback chains, you aren't building for production; you're building for outages.