Skip to content
LLM Failover in Python: Survive a Model Going Dark — ContentBuffer guide

LLM Failover in Python: Survive a Model Going Dark

K
Kodetra Technologies··9 min read Intermediate

Summary

Build a provider-agnostic LLM failover client in Python that survives outages and model removals.

On June 12, 2026 a US export-control directive forced Anthropic to pull Claude Fable 5 and Mythos 5 offline worldwide. Nine days later the endpoint still returns errors. Teams that had wired their product to that one model string woke up to a wall of failed requests and no switch to flip.

The lesson the whole developer community drew from it is blunt: a model can vanish overnight, and hard-coding a single provider is no longer acceptable engineering. Rate limits, regional outages, deprecations, and policy removals are all the same failure from your app's point of view — the call you depend on stops returning text.

This guide builds a small, production-shaped failover client in Python that handles three distinct failure modes correctly: retry a transient blip on the same provider, fail over to the next provider in an ordered chain when a model is gone, and trip a circuit breaker so you stop hammering a dead endpoint. It works with the official anthropic and openai SDKs, and you will see real, reproducible output from a simulated model removal.

Prerequisites

  • Python 3.9+ and basic familiarity with try/except and classes.
  • pip install anthropic openai (the failover core itself has zero dependencies).
  • API keys for at least two providers if you want to run against live models. The worked example runs with no keys at all.
  • A mental model of HTTP status codes: 429 (rate limit), 4xx (client), 5xx (server).

Three failure modes, three responses

Most people reach for a retry loop and stop there. Retries fix transient faults, but they make a removed model worse — you wait through backoff after backoff for a 404 that will never succeed. Good failover separates the cases:

  • Transient (network blip, 429 rate limit, 500/503): same provider can still work. Retry with exponential backoff and jitter.
  • Provider-level (404 model not found, 401/403 auth or permission): this provider cannot serve you right now. Fail over to the next provider immediately — retrying is wasted time.
  • Fatal (400 bad request, 422 unprocessable): your request is malformed. Failing over sends the same broken payload elsewhere. Raise and fix the bug.

The Fable 5 removal is the classic provider-level case: the model id stops resolving and the SDK raises a 404. You do not want to retry that — you want to be serving from your backup before your users notice.

Step 1 — Classify the error

Both the anthropic and openai Python SDKs share the same error shape: status-code subclasses of APIStatusError (NotFoundError=404, RateLimitError=429, InternalServerError≥500, BadRequestError=400) plus APIConnectionError/APITimeoutError for network faults. That means one classifier handles both vendors — we key off status_code and the exception class name.

RETRY, FAILOVER, FATAL = "retry", "failover", "fatal"

def classify(exc):
    name = type(exc).__name__
    status = getattr(exc, "status_code", None)
    if name in ("APIConnectionError", "APITimeoutError"):
        return RETRY                # network blip: try the same provider again
    if status == 429:
        return RETRY                # rate limited: back off and retry
    if status is not None and status >= 500:
        return RETRY                # provider hiccup (500/503): retry
    if status in (401, 403, 404):
        return FAILOVER             # auth/permission/MODEL GONE: next provider
    if status in (400, 422):
        return FATAL                # malformed request: failover won't help
    return FAILOVER                 # unknown: be safe, try the next provider

This is the heart of the design. anthropic.NotFoundError and openai.NotFoundError both carry status_code == 404, so a removed model is classified identically no matter which vendor it came from.

Step 2 — Wrap each provider behind one interface

A provider is anything with a name and a complete(prompt) method that returns a string. Normalizing the two SDKs behind this tiny interface is what lets the failover loop stay vendor-agnostic.

import anthropic, openai

class AnthropicProvider:
    def __init__(self, model, client=None):
        self.name = f"anthropic:{model}"
        self.model = model
        self._client = client or anthropic.Anthropic()
    def complete(self, prompt, max_tokens=512):
        resp = self._client.messages.create(
            model=self.model, max_tokens=max_tokens,
            messages=[{"role": "user", "content": prompt}],
        )
        return resp.content[0].text

class OpenAIProvider:
    def __init__(self, model, client=None):
        self.name = f"openai:{model}"
        self.model = model
        self._client = client or openai.OpenAI()
    def complete(self, prompt, max_tokens=512):
        resp = self._client.chat.completions.create(
            model=self.model, max_tokens=max_tokens,
            messages=[{"role": "user", "content": prompt}],
        )
        return resp.choices[0].message.content

Note the response shapes differ — Anthropic returns resp.content[0].text, OpenAI returns resp.choices[0].message.content. Hiding that difference here means the rest of the system never has to care which model answered.

Step 3 — Add a circuit breaker

If the primary model is gone, every request pays the cost of trying it, failing, and falling over. A circuit breaker remembers recent failures: after N consecutive failures it opens and the client skips that provider entirely for a cool-down window, then allows one trial request (half-open) to test recovery.

import time

class CircuitBreaker:
    def __init__(self, fail_threshold=3, reset_after=30.0):
        self.fail_threshold, self.reset_after = fail_threshold, reset_after
        self.fails, self.opened_at = 0, None
    def allow(self):
        if self.opened_at is None:
            return True
        if time.monotonic() - self.opened_at >= self.reset_after:
            return True            # half-open: allow one trial request
        return False
    def record_success(self):
        self.fails, self.opened_at = 0, None
    def record_failure(self):
        self.fails += 1
        if self.fails >= self.fail_threshold:
            self.opened_at = time.monotonic()

Step 4 — The failover loop

Now wire it together. Walk the ordered provider list; skip any whose breaker is open; retry transient errors with backoff and jitter; break to the next provider on a failover-class error; raise immediately on fatal errors. If everything fails, raise with the last exception attached so you can debug.

import random, logging
log = logging.getLogger("failover")

class FailoverClient:
    def __init__(self, providers, max_attempts=3, base_delay=0.5,
                 breaker_threshold=3, breaker_reset=30.0):
        self.providers = providers
        self.max_attempts, self.base_delay = max_attempts, base_delay
        self.breakers = {p.name: CircuitBreaker(breaker_threshold, breaker_reset)
                         for p in providers}

    def complete(self, prompt, **kw):
        last_exc = None
        for p in self.providers:
            br = self.breakers[p.name]
            if not br.allow():
                log.warning("skip %s (circuit OPEN)", p.name)
                continue
            for attempt in range(1, self.max_attempts + 1):
                try:
                    out = p.complete(prompt, **kw)
                    br.record_success()
                    log.info("OK served by %s (attempt %d)", p.name, attempt)
                    return {"provider": p.name, "text": out}
                except Exception as e:
                    cat, last_exc = classify(e), e
                    log.warning("%s attempt %d failed: %s -> %s",
                                p.name, attempt, type(e).__name__, cat)
                    br.record_failure()
                    if cat == FATAL:
                        raise
                    if cat == FAILOVER:
                        break                      # stop retrying; next provider
                    if attempt < self.max_attempts: # RETRY: backoff + jitter
                        delay = self.base_delay * (2 ** (attempt - 1)) * (1 + random.random() * 0.25)
                        time.sleep(delay)
        raise RuntimeError(f"all providers failed; last error: {last_exc!r}") from last_exc

Wiring it for production looks like this — primary, a same-vendor backup, then a cross-vendor backup so a single company's outage cannot take you down:

client = FailoverClient([
    AnthropicProvider("claude-opus-4-8"),     # primary
    AnthropicProvider("claude-sonnet-4-6"),   # cheaper same-vendor backup
    OpenAIProvider("gpt-4o"),                  # cross-vendor backup
])
answer = client.complete("Summarize the CAP theorem in two sentences.")
print(answer["provider"], "->", answer["text"])

Worked example — a model vanishes overnight

To prove the behavior without live keys, we replay scripted errors that have the same class names and status_code values the real SDKs raise. The primary model returns 404 on every call (it was pulled); the fallback is rate-limited twice, then answers.

import logging
logging.basicConfig(level=logging.INFO, format="%(levelname)-7s %(message)s")

class NotFoundError(Exception):  status_code = 404   # model removed
class RateLimitError(Exception): status_code = 429

class ScriptedProvider:
    def __init__(self, name, script):
        self.name, self._script, self._i = name, list(script), 0
    def complete(self, prompt, **kw):
        b = self._script[min(self._i, len(self._script) - 1)]; self._i += 1
        if isinstance(b, Exception): raise b
        return b

primary  = ScriptedProvider("anthropic:claude-fable-5",
                            [NotFoundError("model claude-fable-5 not found")])
fallback = ScriptedProvider("openai:gpt-4o",
                            [RateLimitError("slow down"),
                             RateLimitError("slow down"),
                             "Failover works: 9 + 10 = 19."])

client = FailoverClient([primary, fallback], max_attempts=3, base_delay=0.01)
print("FINAL:", client.complete("What is 9 + 10?"))

Running it produces exactly this — the 404 triggers an immediate failover, the 429s are retried with backoff, and the fallback answers on its third attempt:

WARNING anthropic:claude-fable-5 attempt 1 failed: NotFoundError -> failover
WARNING openai:gpt-4o attempt 1 failed: RateLimitError -> retry
WARNING openai:gpt-4o attempt 2 failed: RateLimitError -> retry
INFO    OK served by openai:gpt-4o (attempt 3)
FINAL: {'provider': 'openai:gpt-4o', 'text': 'Failover works: 9 + 10 = 19.'}

Now watch the circuit breaker earn its keep. With the primary dead and breaker_threshold=3, the first three requests each try the primary, fail, and fail over. By the fourth request the breaker is open and the primary is skipped outright — no wasted call:

WARNING anthropic:claude-fable-5 attempt 1 failed: NotFoundError -> failover
INFO    OK served by anthropic:claude-sonnet-4-6 (attempt 1)
WARNING anthropic:claude-fable-5 attempt 1 failed: NotFoundError -> failover
INFO    OK served by anthropic:claude-sonnet-4-6 (attempt 1)
WARNING anthropic:claude-fable-5 attempt 1 failed: NotFoundError -> failover
INFO    OK served by anthropic:claude-sonnet-4-6 (attempt 1)
WARNING skip anthropic:claude-fable-5 (circuit OPEN)
INFO    OK served by anthropic:claude-sonnet-4-6 (attempt 1)
WARNING skip anthropic:claude-fable-5 (circuit OPEN)
INFO    OK served by anthropic:claude-sonnet-4-6 (attempt 1)

That is the whole point: after the breaker opens, your users stop paying the latency of a doomed primary call on every request.

Common pitfalls and gotchas

  • Retrying what you should fail over. A blanket except: retry loop will burn three backoffs on a 404 before giving up. Classify first; only 429/5xx/connection errors deserve a retry.
  • Failing over a malformed request. A 400 means your prompt or parameters are broken. Sending the same broken payload to a second provider just produces a second 400. Raise fast on fatal errors.
  • Silent prompt and parameter drift. max_tokens is required by Anthropic and the response field names differ between vendors. If your provider wrappers do not normalize these, failover "works" but returns subtly wrong or truncated output. Test each provider in isolation.
  • Cost blowups on failover. If your backup is a pricier model, an outage can silently multiply your bill. Log which provider served each request and alert when fallback share spikes.
  • Breaker tuned too tight or too loose. A threshold of 1 opens on a single rate-limit blip; a 5-minute reset keeps you off a recovered provider for too long. Start around 3 failures and a 30-60s reset, then tune against real traffic.
  • Streaming needs its own handling. If a stream dies mid-response you have already sent partial tokens to the user. Decide up front whether to restart on the fallback or surface a graceful error; do not blindly retry a half-emitted stream.
  • No active health signal. The breaker only reacts after failures. For critical paths, add a cheap periodic health ping per provider so you can pre-emptively reorder the chain before users hit the dead one.
  • Losing the original error. When all providers fail, raising a bare RuntimeError hides what actually happened. Chain the last exception (raise ... from last_exc) so logs keep the root cause.

Quick reference: error to action

SDK error (status)CategoryWhat the client does
APIConnectionError / APITimeoutErrorretryBackoff + jitter, same provider
RateLimitError (429)retryBackoff + jitter, same provider
InternalServerError (>=500)retryBackoff + jitter, same provider
NotFoundError (404 - model gone)failoverSkip to next provider, count toward breaker
AuthenticationError (401)failoverSkip to next provider
PermissionDeniedError (403)failoverSkip to next provider
BadRequestError (400)fatalRaise immediately - fix the request
UnprocessableEntityError (422)fatalRaise immediately - fix the request

Next steps

  • Add an async version with asyncio and the SDKs' async clients for high-throughput services.
  • Persist breaker state in Redis so all your workers share one view of a dead provider.
  • Emit metrics (per-provider success rate, fallback share, p95 latency) and alert when fallback share crosses a threshold.
  • Layer in semantic equivalence checks if two models must produce interchangeable structured output.
  • If you would rather not maintain this yourself, gateways like LiteLLM implement provider-agnostic routing and fallbacks with a similar model.

The Fable 5 episode will fade, but the takeaway holds: treat your model provider like any other dependency that can fail, and give your app a path that does not end at a single point of failure.

Comments

Subscribe to join the conversation...

Be the first to comment

Found this useful?

Get new AI guides for builders by email. Free.

Join 3,604 newsletter subscribers.

Also get