Tech Verse Logo
Enable dark mode
Building Reliable LLM Fallback Chains with Python

Building Reliable LLM Fallback Chains with Python

•Updated •11 min read

Classify every failure first. Retry the same provider on 429 rate limits, 5xx errors and timeouts, using Retry-After or jittered backoff. Fall back to the next provider on quota exhaustion, 401, 403, 404 or an empty completion, and fail immediately on 400, 413 or 422. Bound the whole chain with asyncio.timeout() and put failing providers on a cooldown.

The naive fallback is a try around the primary call and a second call in the except. It works in the demo and misbehaves in production. It falls back on a malformed request, which the second provider rejects too, so you pay for two failures. It retries a quota error that won't clear until next month. It ignores Retry-After, so a burst of traffic hammers a provider that's already throttling you. And with no time budget, a request that should fail in two seconds hangs for two minutes while timeouts stack up across providers.

A reliable chain is mostly about one decision, made for every failure: should we retry the same provider, fall back to the next one, or fail immediately? Get that classification right and the loop around it is short. The code below talks to any API that speaks the OpenAI chat completions format, which covers OpenAI itself, OpenRouter, and many hosted and local servers. It uses httpx directly, so there's no SDK-specific exception tree to learn. Every snippet is typechecked with mypy in strict mode and tested offline with httpx's mock transport.

Classify every failure: retry, fall back or fail

Status codes carry most of the signal, but not all of it. The OpenAI error codes guide is a good reference even for other providers, because it spells out a distinction most code misses. A 429 can mean "you're sending too fast", which clears in seconds, or insufficient_quota, meaning credit is exhausted or a spend limit was hit. The guide says not to retry the second kind, because retrying won't restore access. They share a status code and need opposite handling.

The rules I'd start with:

  • Retry the same provider on 429 rate limits, 500, 502, 503, 504, timeouts and connection errors. These are usually transient.
  • Fall back on quota exhaustion, 401 and 403 (bad key, region block), 404 (this provider doesn't serve that model), and on a 200 that came back empty. None of these get better by waiting.
  • Fail on 400, 413 and 422. The request is wrong: too many tokens, an invalid parameter, a malformed message. Another provider will reject it as well, and you'd just add latency and cost.

Rate-limit responses often include a Retry-After header, which per MDN's reference is either a number of seconds or an HTTP date. Parse both, because when it's present it's better information than any backoff formula you'll write:

from dataclasses import dataclass
from email.utils import parsedate_to_datetime
from datetime import datetime, timezone
from enum import Enum

import httpx


class Action(Enum):
    RETRY = "retry"        # transient: try the same provider again after a pause
    FALL_BACK = "fallback" # this provider can't serve us right now: move on
    FAIL = "fail"          # our request is wrong: no provider will accept it


@dataclass
class ProviderError(Exception):
    provider: str
    action: Action
    detail: str
    retry_after: float | None = None

    def __str__(self) -> str:
        return f"{self.provider}: {self.action.value}: {self.detail}"


def parse_retry_after(value: str | None) -> float | None:
    """Retry-After is either a number of seconds or an HTTP date."""
    if not value:
        return None
    try:
        return max(0.0, float(value))
    except ValueError:
        pass
    try:
        when = parsedate_to_datetime(value)
    except (TypeError, ValueError):
        return None
    return max(0.0, (when - datetime.now(timezone.utc)).total_seconds())


def classify(provider: str, response: httpx.Response) -> ProviderError:
    status = response.status_code
    retry_after = parse_retry_after(response.headers.get("retry-after"))
    try:
        error = response.json().get("error") or {}
    except ValueError:
        error = {}
    code = str(error.get("code") or error.get("type") or "")
    detail = f"HTTP {status} {code}".strip()

    if status == 429 and code == "insufficient_quota":
        # Out of credit or over a spend limit: waiting won't fix it today.
        return ProviderError(provider, Action.FALL_BACK, detail)
    if status == 429 or status in (500, 502, 503, 504):
        return ProviderError(provider, Action.RETRY, detail, retry_after)
    if status in (401, 403, 404):
        # Bad key, region block, or a model this provider doesn't serve.
        return ProviderError(provider, Action.FALL_BACK, detail)
    # 400, 413, 422: the request itself is invalid.
    return ProviderError(provider, Action.FAIL, detail)

Some providers return the quota case under a different code, or put the useful part only in the message text. Log the raw error body for the first few weeks and extend classify() with what you actually see. That function is the part of the system you'll tune, so keep it in one place.

One provider, one call

Each provider is a base URL, a key and a model. The call turns transport problems into ProviderError too, and it treats an empty completion as a failure. A 200 whose content is empty, often with finish_reason set to content_filter or length, is a real failure mode, and code that only checks the status code passes an empty string to your users.

from dataclasses import dataclass, field

import httpx

from errors import Action, ProviderError, classify


@dataclass
class Completion:
    text: str
    provider: str
    model: str


@dataclass
class ChatProvider:
    """Any API that speaks the OpenAI chat completions format."""

    name: str
    base_url: str
    api_key: str
    model: str
    timeout: httpx.Timeout = field(default_factory=lambda: httpx.Timeout(60.0, connect=5.0))

    async def complete(self, client: httpx.AsyncClient, messages: list[dict[str, str]]) -> Completion:
        try:
            response = await client.post(
                f"{self.base_url}/chat/completions",
                headers={"Authorization": f"Bearer {self.api_key}"},
                json={"model": self.model, "messages": messages},
                timeout=self.timeout,
            )
        except httpx.TimeoutException as exc:
            raise ProviderError(self.name, Action.RETRY, f"timeout: {type(exc).__name__}") from exc
        except httpx.TransportError as exc:
            raise ProviderError(self.name, Action.RETRY, f"network: {type(exc).__name__}") from exc

        if response.status_code != 200:
            raise classify(self.name, response)

        body = response.json()
        choice = (body.get("choices") or [{}])[0]
        text = (choice.get("message") or {}).get("content") or ""
        if not text.strip():
            # A 200 with nothing in it is still a failure for the caller.
            raise ProviderError(self.name, Action.FALL_BACK, f"empty output, finish_reason={choice.get('finish_reason')}")
        return Completion(text=text, provider=self.name, model=str(body.get("model", self.model)))

The order of the two except clauses matters: httpx.TimeoutException is a subclass of httpx.TransportError, so catching the broader one first would swallow the distinction. The timeout is per provider on purpose. A big reasoning model may legitimately need a minute, while a small fallback model should answer in seconds.

The chain: retries, backoff, cooldown and a deadline

The chain walks providers in order. Within a provider it retries transient errors with a pause: the server's Retry-After when there is one, otherwise exponential backoff with full jitter, a random delay between zero and a doubling cap. Jitter matters more than people expect. Without it, every worker that hit the same 429 retries at the same instant and causes the next 429.

Two more pieces separate this from the naive version. A deadline bounds the whole call across every provider and every retry, enforced with asyncio.timeout(), so no combination of timeouts can exceed it. If the next pause wouldn't fit in the remaining budget, the chain skips straight to the next provider instead of sleeping. And a cooldown remembers that a provider just failed hard, so the next hundred requests don't each spend their first attempt discovering that the primary is out of quota.

import asyncio
import logging
import random
import time
from collections.abc import Awaitable, Callable
from dataclasses import dataclass, field

import httpx

from errors import Action, ProviderError
from providers import ChatProvider, Completion

log = logging.getLogger("llm.fallback")


class AllProvidersFailed(Exception):
    def __init__(self, errors: list[ProviderError]) -> None:
        super().__init__("; ".join(str(e) for e in errors) or "no provider available")
        self.errors = errors


@dataclass
class FallbackChain:
    providers: list[ChatProvider]
    attempts_per_provider: int = 3
    base_delay: float = 0.5
    max_delay: float = 8.0
    deadline: float = 90.0  # seconds for the whole call, across every provider
    cooldown: float = 300.0  # how long to skip a provider that fell over
    sleep: Callable[[float], Awaitable[None]] = asyncio.sleep
    _cooling_until: dict[str, float] = field(default_factory=dict)

    async def complete(self, client: httpx.AsyncClient, messages: list[dict[str, str]]) -> Completion:
        started = time.monotonic()
        errors: list[ProviderError] = []

        for provider in self.providers:
            if self._cooling_until.get(provider.name, 0.0) > time.monotonic():
                log.info("skipping %s: cooling down", provider.name)
                continue

            for attempt in range(1, self.attempts_per_provider + 1):
                remaining = self.deadline - (time.monotonic() - started)
                if remaining <= 0:
                    raise AllProvidersFailed(errors)
                try:
                    async with asyncio.timeout(remaining):
                        result = await provider.complete(client, messages)
                except TimeoutError as exc:
                    errors.append(ProviderError(provider.name, Action.FAIL, "overall deadline reached"))
                    raise AllProvidersFailed(errors) from exc
                except ProviderError as err:
                    errors.append(err)
                    log.warning("attempt %d on %s failed: %s", attempt, provider.name, err)
                    if err.action is Action.FAIL:
                        raise AllProvidersFailed(errors) from err
                    if err.action is Action.FALL_BACK or attempt == self.attempts_per_provider:
                        self._cooling_until[provider.name] = time.monotonic() + (err.retry_after or self.cooldown)
                        break

                    delay = err.retry_after
                    if delay is None:
                        # Full jitter: a random pause up to the exponential cap.
                        delay = random.uniform(0, min(self.max_delay, self.base_delay * 2 ** (attempt - 1)))
                    remaining = self.deadline - (time.monotonic() - started)
                    if delay >= remaining:
                        # Waiting would blow the budget, so try the next provider now.
                        break
                    await self.sleep(delay)
                else:
                    if errors:
                        log.info("served by fallback %s (%s) after %d errors", result.provider, result.model, len(errors))
                    self._cooling_until.pop(provider.name, None)
                    return result

        raise AllProvidersFailed(errors)

The sleep field exists so tests can run without waiting. Wiring it up is a few lines. Model names come from the environment, because they change far more often than this code does:

import asyncio
import os

import httpx

from chain import FallbackChain
from providers import ChatProvider

chain = FallbackChain(
    providers=[
        ChatProvider("openai", "https://api.openai.com/v1", os.environ["OPENAI_API_KEY"], os.environ["PRIMARY_MODEL"]),
        ChatProvider("openrouter", "https://openrouter.ai/api/v1", os.environ["OPENROUTER_API_KEY"], os.environ["FALLBACK_MODEL"]),
    ],
)


async def main() -> None:
    async with httpx.AsyncClient() as client:
        result = await chain.complete(client, [{"role": "user", "content": "Explain HTTP 429 in one sentence."}])
        print(f"[{result.provider}/{result.model}] {result.text}")


if __name__ == "__main__":
    asyncio.run(main())

Share one httpx.AsyncClient across calls, as here, so connections to each provider are reused. Creating a client per call leaks sockets under load, which is covered in detail in unclosed httpx and aiohttp sessions.

Test the chain without calling anyone

A fallback path that only runs during an outage is a fallback path that's never been tested. httpx.MockTransport takes a function from request to response, so you can script any sequence of failures and assert what the chain did. This suite needs pytest-asyncio in auto mode:

import json
from collections.abc import Callable

import httpx
from chain import AllProvidersFailed, FallbackChain
from errors import Action, parse_retry_after
from providers import ChatProvider, Completion

MESSAGES = [{"role": "user", "content": "hi"}]
Handler = Callable[[httpx.Request], httpx.Response]


def ok(text: str, model: str) -> httpx.Response:
    return httpx.Response(200, json={"model": model, "choices": [{"message": {"content": text}, "finish_reason": "stop"}]})


def router(primary: list[httpx.Response], fallback: list[httpx.Response], calls: list[str]) -> Handler:
    def handle(request: httpx.Request) -> httpx.Response:
        host = request.url.host
        calls.append(host)
        queue = primary if host == "primary.test" else fallback
        return queue.pop(0)
    return handle


def make_chain(slept: list[float] | None = None) -> FallbackChain:
    async def fake_sleep(delay: float) -> None:
        if slept is not None:
            slept.append(delay)

    return FallbackChain(
        providers=[
            ChatProvider("primary", "https://primary.test/v1", "k1", "big-model"),
            ChatProvider("fallback", "https://fallback.test/v1", "k2", "small-model"),
        ],
        sleep=fake_sleep,
    )


async def run(handler: Handler, chain: FallbackChain | None = None) -> tuple[FallbackChain, Completion | AllProvidersFailed]:
    chain = chain or make_chain()
    async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
        try:
            return chain, await chain.complete(client, MESSAGES)
        except AllProvidersFailed as exc:
            return chain, exc


async def test_retries_a_503_on_the_same_provider() -> None:
    calls: list[str] = []
    slept: list[float] = []
    responses = [httpx.Response(503, headers={"retry-after": "2"}), ok("hello", "big-model")]
    _, result = await run(router(responses, [], calls), make_chain(slept))
    assert isinstance(result, Completion) and result.provider == "primary"
    assert calls == ["primary.test", "primary.test"]
    assert slept == [2.0]  # Retry-After wins over our own backoff


async def test_quota_exhausted_falls_back_without_retrying() -> None:
    calls: list[str] = []
    quota = httpx.Response(429, json={"error": {"type": "insufficient_quota", "code": "insufficient_quota"}})
    chain, result = await run(router([quota], [ok("from fallback", "small-model")], calls))
    assert isinstance(result, Completion) and result.provider == "fallback"
    assert calls == ["primary.test", "fallback.test"]

    # The next call skips the primary entirely while it cools down.
    calls.clear()
    _, result = await run(router([], [ok("again", "small-model")], calls), chain)
    assert calls == ["fallback.test"]


async def test_bad_request_fails_fast_everywhere() -> None:
    calls: list[str] = []
    bad = httpx.Response(400, json={"error": {"code": "context_length_exceeded"}})
    _, result = await run(router([bad], [], calls))
    assert isinstance(result, AllProvidersFailed)
    assert result.errors[0].action is Action.FAIL
    assert calls == ["primary.test"]


async def test_empty_completion_counts_as_failure() -> None:
    calls: list[str] = []
    empty = httpx.Response(200, json={"choices": [{"message": {"content": ""}, "finish_reason": "content_filter"}]})
    _, result = await run(router([empty], [ok("filled", "small-model")], calls))
    assert isinstance(result, Completion) and result.text == "filled"


async def test_gives_up_after_every_provider_fails() -> None:
    calls: list[str] = []
    down = [httpx.Response(502) for _ in range(3)]
    _, result = await run(router(list(down), list(down), calls))
    assert isinstance(result, AllProvidersFailed)
    assert len(calls) == 6


def test_retry_after_parses_both_forms() -> None:
    assert parse_retry_after("7") == 7.0
    assert parse_retry_after("Wed, 21 Oct 2015 07:28:00 GMT") == 0.0
    assert parse_retry_after("soon") is None


async def test_request_body_is_openai_shaped() -> None:
    seen: list[dict[str, object]] = []

    def handler(request: httpx.Request) -> httpx.Response:
        seen.append(json.loads(request.content))
        return ok("x", "big-model")

    await run(handler)
    assert seen[0] == {"model": "big-model", "messages": MESSAGES}

Each test pins one behaviour: a 503 is retried on the same provider and the Retry-After value is used as the delay, a quota error moves on without retrying and puts the primary in cooldown for the next call, a 400 fails without touching the fallback, an empty completion falls through, and a provider that's down everywhere gives up after a fixed number of calls. That last number is worth asserting, because a bug in retry logic usually shows up as a call count. More patterns for keeping these tests deterministic in CI are in testing LLM integrations without flaky runs.

What fallbacks don't fix

Different models give different answers. A fallback model may ignore part of your system prompt, format JSON differently, or be noticeably weaker at the task. If you parse structured output, validate it, and treat a validation failure as FALL_BACK just like an empty response. Run your evaluation set against every model in the chain, not just the primary. Recording result.provider and result.model with every stored output, as the chain returns them, lets you trace a bad answer back to the model that wrote it.

Streaming complicates everything. You can only fall back before the first token reaches the user. Once text is on screen, switching providers means either starting the answer over or stitching two models' output together. The practical rule: apply the chain to the request that opens the stream, and if the stream breaks midway, report an error rather than silently continuing with another model.

Cooldown state is per process. With ten workers, each discovers the outage on its own. That's acceptable for most traffic. If it isn't, keep the cooldown timestamps in Redis or your cache with a TTL, which is the circuit breaker pattern. The LLM circuit breaker write-up covers the half-open state and thresholds this simple cooldown skips.

Cost can jump. Falling back from a cheap model to an expensive one during an outage multiplies your bill for the duration. Put a spending guard in front of the chain, or order the providers so the fallback is the same price tier.

Router-side fallbacks as an alternative

If you already go through a router, it may do this for you. OpenRouter accepts a models array in priority order and moves to the next one when a model errors, including on rate limits, downtime and context-length errors. The model field of the response tells you which one answered, and the model fallbacks docs note that you pay the price of the model that served the request. That's less code, but it puts the routing decision and its failure modes in someone else's service, and it doesn't help when the router itself is what's down. Many teams end up with both: the router's list for model-level failover, and a client-side chain with a direct provider as the last resort.

WRITTEN BY

Full Stack Software Engineer | Laravel · Next.js · AWS

Full Stack Software Engineer with 7+ years of experience building scalable, secure web applications with Laravel, PHP, React, Next.js, and AWS for SaaS, CRM, telecom, and e-commerce companies. Specialized in cloud telephony (FreeSWITCH, SMPP, WebRTC): increased concurrent call capacity by 40% and cut report queries to under 500 ms. Author of open-source Laravel packages with 10K+ downloads on Packagist. Led a team of 4 engineers and shipped production systems for clients in the UAE, USA, India, Saudi Arabia, and Bangladesh.

How we research, write and check articles

    Latest Posts

    View All

    Next.js Middleware Authentication and Token Refresh Flows

    Next.js Middleware Authentication and Token Refresh Flows

    Livewire Performance Optimization Under High Load

    Livewire Performance Optimization Under High Load

    Configuring Nginx Upstream Keepalive for Node Backends

    Configuring Nginx Upstream Keepalive for Node Backends

    Enforcing Immutable State Patterns in React

    Enforcing Immutable State Patterns in React

    FastAPI Dependency Overrides for Integration Testing

    FastAPI Dependency Overrides for Integration Testing

    Stopping Layout Shifts in Next.js Dynamic Imports

    Stopping Layout Shifts in Next.js Dynamic Imports

    Optimizing Agentic Tool Calling Latency

    Optimizing Agentic Tool Calling Latency

    Fixing React Server Component Serialization Errors

    Fixing React Server Component Serialization Errors

    Next.js Route Handler Streaming with ReadableStream

    Next.js Route Handler Streaming with ReadableStream

    React Form Performance: Uncontrolled Inputs and FormData

    React Form Performance: Uncontrolled Inputs and FormData