StackPractices
intermediate By Mathias Paulenko

LLM Fallback Pattern

Fall back to alternative LLM providers or models when the primary fails. Handle rate limits, timeouts, and errors gracefully with a provider chain.

Topics: ai

Overview

LLM APIs fail in ways your retry button can’t fix: rate limits during your traffic peak, a provider-side outage that lasts an hour, a model deprecation that ships on a Tuesday. The LLM Fallback Pattern chains several providers so that when the primary fails, the request automatically retries on the next one — and if every provider fails, the user still gets a controlled response instead of a stack trace.

The pattern is a specialization of retry with backoff applied across providers instead of within one. Each provider in the chain gets its own error budget: transient failures (rate limits, timeouts, 5xx) retry with exponential backoff, permanent failures (authentication, invalid request) skip straight to the next provider because retrying them only wastes latency.

There’s a caveat the diagram versions skip: a fallback chain can hide bugs. If your primary fails on every request because of a malformed header, the chain silently routes everything to the expensive backup and you find out on the invoice. Log every fallback event and alert on its rate: the chain is a safety net, not a monitoring strategy.

When to Use

Use the LLM Fallback Pattern when:

  • Your application can’t tolerate LLM downtime: a customer-facing chatbot, a real-time assistant, an API whose SLA doesn’t include “OpenAI was having a bad day.”
  • You hit rate limits on your primary provider during peak usage and upgrading the tier costs more than a second provider.
  • You want a hedge against vendor lock-in: keeping a second provider wired in means a pricing change or deprecation is a config edit, not an incident.
  • Providers have different strengths: a frontier model for hard reasoning, a cheaper or local model as the last-resort answer.
  • A degraded response is acceptable. If a fallback model produces a worse answer, decide up front whether your users prefer a weaker answer or an honest error.

Skip it when:

  • The request is idempotent batch work that can simply wait: queue it and retry later instead of paying two providers.
  • Your fallback provider can’t actually serve the request (different context window, missing tool-calling support). A chain is only as good as its weakest link’s ability to do the job.
  • You’ve got a single provider and no budget for a second; a circuit breaker alone gives you fail-fast behavior without a chain.

Solution

Fallback chain — the request tries the primary provider with backoff on retryable errors; on a non-retryable error or exhausted retries it falls to the next provider, and if all fail it returns a static response.

Python

The implementation below encodes the whole contract: an error taxonomy, per-provider retry budgets, and a chain that stops at the first success. The mock_provider_call simulates failures so the demo runs without API keys:

from dataclasses import dataclass
from typing import List
from enum import Enum
import time
import random

class ErrorType(Enum):
    RATE_LIMIT = "rate_limit"      # retryable: quota exceeded, back off
    TIMEOUT = "timeout"            # retryable: no response in time
    SERVER_ERROR = "server_error"  # retryable: provider-side 5xx
    AUTH = "auth"                  # NOT retryable: bad key, won't fix itself
    INVALID_REQUEST = "invalid_request"  # NOT retryable: malformed input
    UNKNOWN = "unknown"

@dataclass
class LLMError(Exception):
    error_type: ErrorType
    message: str
    provider: str

@dataclass
class ProviderConfig:
    name: str
    model: str
    max_retries: int = 3        # attempts within THIS provider
    base_delay: float = 1.0
    max_delay: float = 30.0
    timeout_s: float = 10.0     # per-attempt budget, not per-chain

@dataclass
class LLMResponse:
    provider: str
    model: str
    content: str
    latency_ms: float
    from_fallback: bool = False

RETRYABLE_ERRORS = {ErrorType.RATE_LIMIT, ErrorType.TIMEOUT, ErrorType.SERVER_ERROR}

def exponential_backoff(attempt: int, base: float, max_delay: float) -> float:
    delay = min(base * (2 ** attempt), max_delay)
    return delay + random.uniform(0, 0.1 * delay)  # jitter avoids thundering herd

def mock_provider_call(provider: str, model: str, prompt: str) -> str:
    """Simulate provider calls with configurable failures."""
    if provider == "openai" and "rate limit" in prompt.lower():
        raise LLMError(ErrorType.RATE_LIMIT, "Rate limit exceeded", provider)
    if provider == "anthropic" and "timeout" in prompt.lower():
        raise LLMError(ErrorType.TIMEOUT, "Request timed out", provider)
    if provider == "local" and "auth" in prompt.lower():
        raise LLMError(ErrorType.AUTH, "Invalid API key", provider)
    return f"[{provider}/{model}] Response to: {prompt[:40]}..."

class LLMFallbackChain:
    def __init__(self, providers: List[ProviderConfig],
                 static_fallback: str = "I'm unable to respond right now. Please try again later."):
        self.providers = providers
        self.static_fallback = static_fallback

    def _call_with_retry(self, provider: ProviderConfig, prompt: str) -> str:
        for attempt in range(provider.max_retries + 1):
            try:
                return mock_provider_call(provider.name, provider.model, prompt)
            except LLMError as e:
                if e.error_type not in RETRYABLE_ERRORS:
                    raise
                if attempt < provider.max_retries:
                    delay = exponential_backoff(attempt, provider.base_delay, provider.max_delay)
                    print(f"  [{provider.name}] {e.error_type.value}, retrying in {delay:.1f}s...")
                    time.sleep(min(delay, 0.5))  # capped for the demo
                else:
                    raise

    def complete(self, prompt: str) -> LLMResponse:
        for i, provider in enumerate(self.providers):
            try:
                start = time.time()
                content = self._call_with_retry(provider, prompt)
                latency = (time.time() - start) * 1000
                return LLMResponse(provider.name, provider.model, content,
                                   latency, from_fallback=i > 0)
            except LLMError as e:
                # Log every fallthrough — a silent chain hides provider outages
                print(f"  [{provider.name}] Failed: {e.error_type.value} - {e.message}")
                continue
            except Exception as e:
                print(f"  [{provider.name}] Unexpected error: {e}")
                continue

        return LLMResponse("static", "none", self.static_fallback, 0, True)

# Usage
chain = LLMFallbackChain([
    ProviderConfig("openai", "gpt-4o", max_retries=2, base_delay=1.0),
    ProviderConfig("anthropic", "claude-3.5-sonnet", max_retries=1, base_delay=2.0),
    ProviderConfig("local", "llama-3-70b", max_retries=1, base_delay=0.5),
])

test_prompts = [
    "What is machine learning?",
    "This prompt will trigger rate limit on OpenAI",
    "This prompt will trigger timeout on Anthropic too",
    "This prompt will trigger auth error on local provider",
]

for prompt in test_prompts:
    print(f"\nPrompt: {prompt}")
    response = chain.complete(prompt)
    print(f"  Provider: {response.provider}/{response.model}")
    print(f"  Fallback: {response.from_fallback}")
    print(f"  Content: {response.content[:60]}...")

JavaScript

Same contract, async version — note the retry budget lives per provider, not per chain:

class LLMError extends Error {
  constructor(errorType, message, provider) {
    super(message);
    this.errorType = errorType;
    this.provider = provider;
  }
}

const RETRYABLE_ERRORS = new Set(["rate_limit", "timeout", "server_error"]);

function exponentialBackoff(attempt, base, maxDelay) {
  const delay = Math.min(base * Math.pow(2, attempt), maxDelay);
  return delay + Math.random() * 0.1 * delay;
}

function mockProviderCall(provider, model, prompt) {
  if (provider === "openai" && prompt.toLowerCase().includes("rate limit"))
    throw new LLMError("rate_limit", "Rate limit exceeded", provider);
  if (provider === "anthropic" && prompt.toLowerCase().includes("timeout"))
    throw new LLMError("timeout", "Request timed out", provider);
  if (provider === "local" && prompt.toLowerCase().includes("auth"))
    throw new LLMError("auth", "Invalid API key", provider);
  return `[${provider}/${model}] Response to: ${prompt.slice(0, 40)}...`;
}

class LLMFallbackChain {
  constructor(providers, staticFallback = "I'm unable to respond right now.") {
    this.providers = providers;       // [{name, model, maxRetries, baseDelay, maxDelay}]
    this.staticFallback = staticFallback;
  }

  async _callWithRetry(provider, prompt) {
    for (let attempt = 0; attempt <= provider.maxRetries; attempt++) {
      try {
        return mockProviderCall(provider.name, provider.model, prompt);
      } catch (e) {
        if (!(e instanceof LLMError) || !RETRYABLE_ERRORS.has(e.errorType)) throw e;
        if (attempt >= provider.maxRetries) throw e;
        const delay = exponentialBackoff(attempt, provider.baseDelay, provider.maxDelay);
        console.log(`  [${provider.name}] ${e.errorType}, retrying in ${delay.toFixed(1)}s...`);
        await new Promise(r => setTimeout(r, Math.min(delay * 1000, 500)));
      }
    }
  }

  async complete(prompt) {
    for (let i = 0; i < this.providers.length; i++) {
      const provider = this.providers[i];
      try {
        const start = Date.now();
        const content = await this._callWithRetry(provider, prompt);
        return {
          provider: provider.name, model: provider.model, content,
          latencyMs: Date.now() - start, fromFallback: i > 0,
        };
      } catch (e) {
        console.log(`  [${provider.name}] Failed: ${e.errorType ?? e.message}`);
        continue;
      }
    }
    return { provider: "static", model: "none", content: this.staticFallback,
             latencyMs: 0, fromFallback: true };
  }
}

// Usage
const chain = new LLMFallbackChain([
  { name: "openai", model: "gpt-4o", maxRetries: 2, baseDelay: 1.0, maxDelay: 30 },
  { name: "anthropic", model: "claude-3.5-sonnet", maxRetries: 1, baseDelay: 2.0, maxDelay: 30 },
  { name: "local", model: "llama-3-70b", maxRetries: 1, baseDelay: 0.5, maxDelay: 30 },
]);

const testPrompts = [
  "What is machine learning?",
  "This prompt will trigger rate limit on OpenAI",
  "This prompt will trigger timeout on Anthropic too",
  "This prompt will trigger auth error on local provider",
];

(async () => {
  for (const prompt of testPrompts) {
    const response = await chain.complete(prompt);
    console.log(`Prompt: ${prompt} -> ${response.provider}/${response.model} (fallback: ${response.fromFallback})`);
  }
})();

A Java version of the same chain, plus a runnable demo harness, lives in the companion repository.

Explanation

The chain resolves each request in order:

  1. Primary call. The request goes to the first provider. Success returns immediately — zero fallback overhead on the happy path.
  2. Retry with backoff inside the provider. Transient errors (rate limit, timeout, 5xx) retry with exponential backoff and jitter. The retry budget belongs to the provider, so one flapping provider can’t burn the whole chain’s latency.
  3. Fall through on permanent error or exhausted retries. Auth failures and invalid requests skip retries entirely. Retrying a 401 just delays the inevitable. The request moves to the next provider with the error logged.
  4. Static fallback. If every provider fails, return a controlled response. The user sees a graceful message; your error tracker sees five failed attempts to alert on.

Three decisions define whether your chain helps or hurts:

Retryable vs. non-retryable is the load-bearing distinction. Map provider SDK errors into a shared taxonomy before writing the loop. A 429 deserves backoff; a 401 deserves an immediate move to the next provider (and a pager, since your key is broken). Treating them the same either wastes seconds or hammers a dead credential. Provider docs like Anthropic’s error reference show the raw statuses you’re mapping.

Budget latency across the whole chain. If the primary gets 3 retries at 10s timeout plus two providers behind it, worst case is ~90 seconds to an answer. For interactive UIs that’s an abandoned tab. Set a total chain deadline (say 15s) and let it shrink retries for later providers: the last provider should get one shot, fast.

Decide what “fallback” means: provider or capability. Falling back to a weaker model changes the answer, not just the transport. If your primary supports tool-calling and the fallback doesn’t, the chain needs a per-provider capability check, or requests with tools should degrade differently. Pairing this with LLM guardrails keeps the degraded response from also being an unvalidated one.

Variants

VariantDescriptionUse Case
Circuit breaker per providerSkip providers that have failed recently without retrying at allPrevents the chain from adding latency during a known outage
Weighted routing + fallbackDistribute load across providers when healthy, fall back on errorCost optimization: cheap model serves most traffic, premium catches overflow
Quality-ordered chainHighest-quality provider first, faster/cheaper ones behindBest answer when it works, good-enough answer when it doesn’t
Parallel raceCall two providers at once, take the first valid responseLowest latency for latency-critical endpoints; doubles cost per request
Degraded-mode fallbackStatic or cached response instead of an API callLast resort when every provider is down or the request is read-only

The circuit-breaker variant deserves a paragraph, not a row: tracking per-provider failure rates means a provider that’s been down for five minutes stops receiving retries at all — the chain shortens to healthy providers automatically. That’s the Circuit Breaker Pattern composed with fallback, and it fixes the “one dead provider adds 30s to every request” failure mode the naive chain has. It’s the composition Fowler described for service calls, moved up to the provider boundary.

The parallel race is the opposite trade: you pay for two completions per request in exchange for p50 latency equal to the faster provider. Use it only on endpoints where latency directly costs you users — and where the two providers’ outputs are close enough that “whichever arrives first” is a real answer.

What Works

  • Order the chain by what you’re optimizing. Cost-first, quality-first, or latency-first — the order is the policy. If you want routing by query complexity instead of failure, that’s the LLM Router Pattern.
  • Budget the whole chain, not just each provider. A chain of three providers at 3 retries × 10s each is a 90-second worst case. Cap total elapsed time.
  • Log every fallthrough with the error type. Fallback rate is your provider health dashboard; an alert on from_fallback > 5% catches outages before your users do.
  • Normalize responses at the boundary. Map each provider’s payload to your internal format inside the chain: leaked provider schemas into app code couple you to whichever provider happened to answer.
  • Make the static fallback useful. A cached answer, a “we’re degraded” notice that still lets the user act, or a reduced feature — not just “error.” See provider rate-limit docs like OpenAI’s for what the retryable errors actually look like.

Common Mistakes

  • Retrying non-retryable errors. Auth and invalid-request errors can’t heal with time; retrying them burns the latency budget that the next provider needs.
  • No total deadline. Per-provider timeouts without a chain-level cap turn a degraded response into a hung request.
  • Treating fallback output as equivalent. A smaller model’s answer served silently as if it were the frontier model’s is a quality regression users notice before you do. Tag from_fallback and consider showing degraded status in the UI.
  • Same failure domain across the chain. Two SDKs pointed at the same provider under different names isn’t resilience. Pick providers with independent infrastructure, and remember the local model only helps if the outage isn’t your own network.
  • Silent chains. No metrics on fallback events means your “resilient” system has been routing 100% of traffic to the backup for a week and nobody noticed until the bill arrived.

Advanced Solutions

The base chain handles single requests. Production adds three layers:

Per-provider circuit breakers. A provider in OPEN state doesn’t even get attempted — the chain consults breakers before dialing:

class BreakerChain(LLMFallbackChain):
    def __init__(self, providers, breakers, **kw):
        super().__init__(providers, **kw)
        self.breakers = breakers  # name -> CircuitBreaker

    def complete(self, prompt):
        candidates = [p for p in self.providers
                      if self.breakers[p.name].allow_request()]
        if not candidates:
            return LLMResponse("static", "none", self.static_fallback, 0, True)
        return super().complete(prompt)  # uses filtered list

Response normalization. Each provider wraps its SDK call in an adapter that returns your LLMResponse directly, so from_fallback and latency_ms stay comparable across vendors: the field names differ per provider, the metric shouldn’t.

A retry budget across the chain. Track elapsed time in complete() and pass remaining budget into each _call_with_retry: provider 1 might get 8s, provider 2 gets 4s, provider 3 gets one shot with what’s left. Without it, your worst case is the sum of every provider’s worst case.

Runnable versions of these implementations (including the Java chain) live in the companion repository.

Frequently Asked Questions

How many providers should the chain have?

Two is the meaningful step (one backup buys real resilience), three covers most failure modes (premium → cheap → local/static). Beyond that you're managing a fleet, not a fallback.

Should the fallback use the same model tier?

If the answer quality must hold, yes: match capability, not price. If a degraded answer beats an error, drop a tier for the fallback and say so in the UI. What you can't do is mix them silently.

How do I normalize different response formats across providers?

Put an adapter per provider inside the chain: provider SDK → your LLMResponse. Each adapter maps usage counts, finish reasons, and content blocks to your schema, so app code never sees provider-specific shapes.

When does a fallback make things worse?

When the error is yours, not theirs. A malformed request or a broken prompt template fails identically on every provider — the chain retries N times instead of once and multiplies cost while hiding the bug. Fall through on 5xx and rate limits; fail fast on 4xx.

Fallback chain or circuit breaker — which first?

Breaker first if you've got one provider (it stops you hammering a dead API); chain when you add a second. In production they compose: the breaker decides whether to try a provider, the chain decides which one.

Should the static fallback answer the actual question?

Better than it sounds: a cached response for read-heavy endpoints or a reduced-feature answer preserves the flow. A bare "try again later" is the honest minimum. Just make sure your alerting treats every static response as an outage, because it's one.