DEV Community

tanmay kuamr chaurasia
tanmay kuamr chaurasia

Posted on

Resilience Patterns for LLMs: Retries, Fallbacks, and Circuit Breakers

When an LLM provider experiences an outage, rate limit spike, or degraded performance, most backend developers default to a simple solution: wrap the API call in a retry loop.

Relying solely on retries often makes outages worse. If an API returns a 429 Too Many Requests or a prolonged 500 Internal Server Error, hitting the endpoint repeatedly burns your execution quota, inflates user latency, and contributes to the "thundering herd" problem when the upstream service attempts to recover.

To build production-grade AI applications, you must separate retries from fallbacks and protect your system architecture accordingly.

Understanding Retry vs. Fallback

A retry means attempting the exact same request against the same provider. This is designed for transient failures: a dropped TCP connection, a temporary network hiccup, or a sporadic 503 error.

A fallback means routing the request to a completely different provider or a secondary model family. Fallbacks are required when the primary provider is facing a hard outage, severe throttling, or persistent API degradation.

Mixing these two concepts leads to fragile systems. Retrying a 429 status code, for instance, ignores the provider's explicit request to pause traffic.

1. Smart Retries with Exponential Backoff and Jitter

If you encounter a transient error (like a 502 or 503), do not retry immediately in a tight loop. Instead, use exponential backoff combined with jitter.

Exponential backoff increases the delay between each attempt exponentially (e.g., 1s, 2s, 4s). Jitter adds a randomized offset to prevent thousands of concurrent clients from hitting the recovering server at the exact same millisecond.

Here is a practical Python implementation using explicit backoff and error handling:

import random
import time
import openai

def call_llm_with_retry(prompt: str, max_retries: int = 3) -> str:
    base_delay = 1.0
    for attempt in range(max_retries):
        try:
            response = openai.chat.completions.create(
                model="gpt-4o",
                messages=[{"role": "user", "content": prompt}]
            )
            return response.choices[0].message.content
        except (openai.APIConnectionError, openai.InternalServerError) as e:
            if attempt == max_retries - 1:
                raise e
            # Calculate exponential backoff + jitter
            sleep_time = (base_delay * (2 ** attempt)) + random.uniform(0, 0.5)
            time.sleep(sleep_time)
        except openai.RateLimitError:
            # Pass rate limit errors immediately to trigger the fallback layer
            raise
Enter fullscreen mode Exit fullscreen mode

2. Multi-Provider Fallback Chains

When retries are exhausted—or when a rate limit error occurs—your execution path should immediately switch to a backup provider. For example, if your primary model is OpenAI's gpt-4o, your secondary fallback could be Anthropic's claude-3-5-sonnet.

Here is how to structure a fallback chain across different SDKs:

import os
from anthropic import Anthropic
import openai

anthropic_client = Anthropic(api_key=os.environ.get("ANTHROPIC_API_KEY"))

def generate_completion(prompt: str) -> str:
    # Step 1: Try Primary Provider (OpenAI) with retries
    try:
        return call_llm_with_retry(prompt, max_retries=2)
    except Exception as e:
        print(f"Primary provider failed or rate limited: {e}. Executing fallback...")

    # Step 2: Fallback to Secondary Provider (Anthropic)
    try:
        response = anthropic_client.messages.create(
            model="claude-3-5-sonnet-20241022",
            max_tokens=1000,
            messages=[{"role": "user", "content": prompt}]
        )
        return response.content[0].text
    except Exception as e:
        print(f"Fallback provider failed: {e}")
        raise RuntimeError("All configured LLM providers are unavailable.")
Enter fullscreen mode Exit fullscreen mode

3. Protecting Infrastructure with Circuit Breakers

If an LLM provider goes down completely, executing two retries and a fallback for every single incoming request adds seconds of latency to your application.

A circuit breaker tracks the failure rate of a provider over a rolling window. If the failure rate exceeds a specified threshold (e.g., 50% failures over 10 requests), the circuit "opens."

When open, the system bypasses the primary provider entirely and routes requests straight to the fallback provider. After a set cooldown period, the circuit enters a "half-open" state, sending a test request to verify if the primary provider has recovered.

Key Takeaways

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

About me

Tanmay builds AI agents and automation for businesses and is open to freelance projects. Feel free to connect with me on LinkedIn to discuss backend engineering, LLM infrastructure, or custom automation solutions.

Top comments (0)