Blog · · By Dhrumil Barot, Founder
How to Set Up LLM Fallback (Python and LiteLLM)
Set up LLM fallback by failing over only on timeouts, 429, 5xx and 529, capping SDK retries and logging the serving model. Python and LiteLLM code.
TL;DR: An LLM fallback sends a request to the next model in an ordered chain when the current one fails with a transient error: a timeout, connection error, 408, 409, 429, 500, 502, 503, 504 or Anthropic's 529. Never fail over on 400, 401, 403 or 404, because those are bugs the next provider will hide. Cap the SDK's built-in retries first: both official SDKs retry twice by default, so a three-model chain can make 9 attempts before your user sees an error.
To set up LLM fallback, you need three things: an ordered chain of models on at least two providers, a function that decides which errors are worth failing over on, and a log line that records which model actually served each request. In plain Python that is about 40 lines with the official openai and anthropic SDKs. In LiteLLM it is a fallbacks entry in config.yaml. Both are below, with list prices checked on 2026-11-12, and the cost of each fallback worked out per 1,000 requests.

What you need before you start
You need these pieces in place before the first step:
- Python 3.9 or later, with
pip install openai anthropic(current releases). Theopenaipackage now uses HTTPX2 as its default HTTP client; nothing below depends on that. - API keys in
OPENAI_API_KEYandANTHROPIC_API_KEY. A second provider matters: a fallback to another model on the same provider does not help when that provider's whole API is overloaded or your organisation hit its spend limit. - For the gateway version: LiteLLM (
pip install 'litellm[proxy]'). - Your current request shape. We use 3,000 input tokens and 600 output tokens per request for the cost math.
The chain in this guide, with list prices per 1M tokens from the OpenAI pricing page and the Anthropic pricing page on 2026-11-12:
| Position | Model ID | Input / 1M | Output / 1M | Why it is here |
|---|---|---|---|---|
| Primary | gpt-6.1-sol | $2.00 | $10.00 | Quality model for normal traffic |
| Fallback 1 | claude-sonnet-5-5 | $2.00 | $10.00 | Same tier, different provider, 1M context |
| Fallback 2 | claude-haiku-5-5 | $0.10 | $0.50 | Cheap last resort (prompts up to 100,000 tokens) |
Which errors should trigger a fallback?
Fail over on errors that say "the provider cannot serve this right now", and raise on errors that say "this request is wrong". The table maps the documented codes from the OpenAI error codes guide and the Anthropic errors page to an action.

| Error | Provider wording | Fail over? | Why |
|---|---|---|---|
| Timeout / connection error | APITimeoutError, APIConnectionError | Yes | The provider never answered |
| 429 rate limit | OpenAI "Rate limit reached for requests", "Slow down"; Anthropic rate_limit_error | Yes, after at most one retry | Another provider has its own limits |
| 429 spend or quota | OpenAI organization_spend_limit_exceeded, "Credit balance exhausted"; Anthropic tier spend cap | Yes, skip retries | OpenAI: retrying these "won't restore API access" |
| 500 / 502 / 504 | OpenAI "The server had an error"; Anthropic api_error, timeout_error | Yes | Transient provider fault |
| 503 | OpenAI server_is_overloaded | Yes | Model capacity, not your request |
| 529 | Anthropic overloaded_error | Yes | Anthropic-specific overload code |
| 400 | invalid_request_error | No (one exception below) | The next model gets the same bad request |
| 401 / 403 / 404 | auth, permission, not found | No | A broken key or model ID should page you, not hide |
Three details most fallback tutorials miss:
- OpenAI moved some overload errors from 429 to 503. Its docs say Python raises
RateLimitErrorfor 429 andInternalServerErrorfor 503, and that video overload "now returns 503 where it previously returned 429". Handle both. - Anthropic returns 400, not 429, when you hit a spend limit you set yourself. Its errors page says the API "also returns a 400 when usage reaches an organization or workspace spend limit you set". If you want that to fail over, check the message, not only the status.
- A spend-cap 429 never recovers by waiting. Anthropic notes that a tier spend-cap 429 "has no retry-after header and keeps failing until access resumes". Retrying it just adds latency.
The one 400 worth rerouting is a context-length error: send it to a model with a bigger window, not to a sibling with the same limit. Claude Sonnet 5.5 includes a 1M-token context window at standard pricing, which makes it a natural target.
Step 1: Cap the SDK retries and set a real timeout
Both official SDKs retry for you. The openai package retries "2 times by default" on connection errors, 408, 409, 429 and 500+, and waits up to 10 minutes per request before timing out (openai-python README). The Anthropic SDK also retries twice by default and honours retry-after. Left alone, those defaults sit underneath your chain and multiply it.
import logging
import anthropic
import openai
log = logging.getLogger("llm")
# One quick retry per provider, then let the chain take over.
oa = openai.OpenAI(max_retries=1, timeout=30.0)
an = anthropic.Anthropic(max_retries=1, timeout=30.0)Set the timeout from your primary model's p99 latency, not its median. Too tight and you fail over on healthy requests; we priced that trap in model fallback chains and outage cost.
Step 2: Write the fail-over rule
Put the table above into one function. APITimeoutError is a subclass of APIConnectionError in both SDKs, so one check covers both.
FAILOVER_STATUS = {408, 409, 429, 500, 502, 503, 504, 529}
SPEND_HINTS = ("spend limit", "spend_limit", "credit balance", "usage limit", "quota")
def should_fail_over(err: Exception) -> bool:
if isinstance(err, (openai.APIConnectionError, anthropic.APIConnectionError)):
return True # network errors and timeouts
status = getattr(err, "status_code", None)
if status in FAILOVER_STATUS:
return True
# Anthropic returns 400 for a spend limit you configured yourself
return status == 400 and any(h in str(err).lower() for h in SPEND_HINTS)Step 3: Call each provider with its native SDK
How do I fall back from OpenAI to Anthropic in code? Use each provider's own SDK and translate the message list. Anthropic does offer an OpenAI-compatible endpoint at https://api.anthropic.com/v1/, but its own docs call it "primarily intended to test and compare model capabilities" and "not considered a long-term or production-ready solution"; it silently ignores fields such as seed and the strict flag on tools (Anthropic OpenAI SDK compatibility). Your fallback is the path that runs during an incident, so make it the well-tested one.
def call_openai(model, messages, max_tokens):
r = oa.chat.completions.create(
model=model, messages=messages, max_completion_tokens=max_tokens
)
return r.choices[0].message.content, r.usage.prompt_tokens, r.usage.completion_tokens
def call_anthropic(model, messages, max_tokens):
system = "\n".join(m["content"] for m in messages if m["role"] == "system")
chat = [m for m in messages if m["role"] != "system"]
extra = {"system": system} if system else {}
r = an.messages.create(model=model, max_tokens=max_tokens, messages=chat, **extra)
text = "".join(b.text for b in r.content if b.type == "text")
return text, r.usage.input_tokens, r.usage.output_tokensStep 4: Walk the chain and log who answered
The loop tries each link in order, raises immediately on a non-transient error, and records the serving model plus token counts. That log line is what lets you see when fallback quietly becomes your normal traffic.
CHAIN = [
("openai", "gpt-6.1-sol"),
("anthropic", "claude-sonnet-5-5"),
("anthropic", "claude-haiku-5-5"),
]
CALLERS = {"openai": call_openai, "anthropic": call_anthropic}
def complete(messages, max_tokens=1024):
errors = []
for provider, model in CHAIN:
try:
text, tokens_in, tokens_out = CALLERS[provider](model, messages, max_tokens)
log.info("served_by=%s/%s in=%d out=%d failovers=%d",
provider, model, tokens_in, tokens_out, len(errors))
return text
except Exception as err:
if not should_fail_over(err):
raise
log.warning("failover from %s/%s: %s", provider, model, err)
errors.append(f"{provider}/{model}: {err}")
raise RuntimeError("all models in the chain failed: " + " | ".join(errors))Streaming needs one more rule. The openai README states that stream consumption "is not automatically retried, because replaying a request could duplicate output already delivered", and Anthropic warns that a streaming error can arrive after a 200. Fail over only if no tokens have reached the user yet; after that, return an error rather than splice two models' answers together.
Step 5: Or do the same in LiteLLM
If several services call models, put the chain in a gateway instead of copying complete() into each one. In LiteLLM, fallbacks run "if a call fails after num_retries", in list order, and there are three kinds: fallbacks for general errors, context_window_fallbacks and content_policy_fallbacks (LiteLLM reliability docs).
model_list:
- model_name: primary
litellm_params:
model: openai/gpt-6.1-sol
api_key: os.environ/OPENAI_API_KEY
- model_name: backup
litellm_params:
model: anthropic/claude-sonnet-5-5
api_key: os.environ/ANTHROPIC_API_KEY
- model_name: last-resort
litellm_params:
model: anthropic/claude-haiku-5-5
api_key: os.environ/ANTHROPIC_API_KEY
litellm_settings:
num_retries: 1 # per model group, before falling back
request_timeout: 30 # seconds
fallbacks: [{"primary": ["backup", "last-resort"]}]
context_window_fallbacks: [{"primary": ["backup"]}]
router_settings:
allowed_fails: 3 # cool a deployment down after 3 failures
cooldown_time: 30 # seconds out of rotationStart it with litellm --config config.yaml and point any OpenAI client at http://0.0.0.0:4000. The cooldown is the circuit breaker: after allowed_fails, LiteLLM stops sending traffic to that deployment for cooldown_time seconds instead of paying a timeout on every request. For the trade-offs between running this yourself and paying a hosted gateway, see LiteLLM vs OpenRouter vs managed gateways.
LangChain LLM fallback | Make your AI app unbreakable (DigitalOcean)
DigitalOcean walks through a sequential fallback class in a LangChain app: a list of models tried in order, a warning logged on each failure, an exception when all fail, and a mock subclass that forces the first model to fail so you can watch the fallback happen.
Step 6: Prove it fails over before production needs it
Test with a real transport failure, not a bad model name. A wrong model ID returns 404, and the rule above correctly refuses to fail over on it.
# Point the primary at a closed port: connection refused triggers failover.
oa = openai.OpenAI(base_url="http://127.0.0.1:9/v1", max_retries=0, timeout=2.0)
print(complete([{"role": "user", "content": "Reply with the word ok."}]))
# Expect: a "failover from openai/gpt-6.1-sol" warning, then served_by=anthropic/claude-sonnet-5-5For LiteLLM, note that since Proxy v1.85.0 the mock_testing_fallbacks flag is stripped from proxy requests; it only works on direct litellm.Router calls. To test the proxy, break the primary's api_base in a staging config, send a normal request and check the x-litellm-model-id response header to see which deployment answered.
curl -s -D - http://0.0.0.0:4000/chat/completions \
-H "Authorization: Bearer $LITELLM_API_KEY" -H "Content-Type: application/json" \
-d '{"model": "primary", "messages": [{"role": "user", "content": "ping"}]}' \
| grep -i x-litellm-model-idHow do retries and fallbacks interact?
Retries repeat the same model; fallbacks move to the next one, and the attempts multiply. Worst-case attempts for a chain are links x (1 + retries per link).
| Setup | Attempts before final error | Worst-case wait at 20 s timeout |
|---|---|---|
| 3 links, SDK defaults (2 retries) | 3 x 3 = 9 | 180 s |
| 3 links, max_retries=1 | 3 x 2 = 6 | 120 s |
| 3 links, max_retries=0 | 3 | 60 s |
| LiteLLM num_retries: 3 + SDK default 2 inside your app | 3 x 4 = 12 at the proxy, times your client's retries | minutes |
Pick one layer to own retries. If you run LiteLLM, set your application client to max_retries=0 so the proxy's count is the real count.
Does a fallback model change cost per request?
Yes: the request is billed at the fallback model's price, plus whatever the failed attempt consumed. A 429, 503 or 529 is returned before generation, so it carries no token usage; a timeout mid-stream can still bill the input and any streamed output. Using our 3,000-in, 600-out shape:
| Served by | Derivation | Cost per 1,000 requests |
|---|---|---|
| gpt-6.1-sol | 3,000 x $2/1M + 600 x $10/1M = $0.0120 | $12.00 |
| claude-sonnet-5-5 | Same list price; Anthropic says its newer tokenizer produces about 30% more tokens, so $12.00 x 1.3 | about $15.60 |
| claude-haiku-5-5 | 3,000 x $0.10/1M + 600 x $0.50/1M = $0.0006, x 1.3 | about $0.78 |
At a 2% fast-failure rate, falling back to Sonnet 5.5 costs $12.00 + 0.02 x $15.60 = $12.31 per 1,000 requests, 2.6% more than primary-only. Falling back to Haiku 5.5 costs $12.00 + 0.02 x $0.78 = $12.02, 0.13% more. Equal list prices do not mean equal bills: the tokenizer difference makes the "same-price" fallback the expensive one. Run your own token counts through the LLM cost calculator before choosing the order, and see LLM routing examples for chains that also route on cost.
Common errors and their fixes
- Every request "fails over" and the last model always answers. Your rule treats 404 as transient, or the primary's model ID is wrong. Log
err.status_code; anot_found_errorshould raise. - `"thinking.type.enabled" is not supported for this model` after failing over to a newer Claude model. Anthropic returns this 400 for Claude 4.7 and later; translate request options per provider instead of passing one dict to every model.
- A fallback request takes minutes. SDK retries are stacked under your chain or under LiteLLM. Recount attempts with the table above.
- 429s continue after waiting. Check
error.code: a spend, credit or usage limit needs a billing change, not backoff. - Answers change format during an incident. The fallback model formats output differently. Validate structured output after every call, whichever model served it.
If you would rather not maintain the chain, the price tables and the retry settings in every service, Vynaris is an OpenAI-compatible endpoint (https://api.vynaris.com/v1) that bills provider list price plus 3% on the first $500 a month and 1% after, and shows the model that actually served each request in the response headers. The DIY code above works without it. For the concept behind both, read what an LLM gateway is.
FAQ
What is the difference between LLM fallback and LLM failover?
They are used interchangeably. Some teams say failover for switching providers (OpenAI to Anthropic) and fallback for switching models (Sonnet to Haiku); the code and configuration are the same ordered chain.
Should I retry before falling back?
Retry once on 429 and 5xx, because many are momentary, then fall back. Skip the retry for spend, credit and quota errors: OpenAI states that retrying them "won't restore API access".
Can I fall back to a different model on the same provider?
Yes, and it helps for a model-specific overload such as an OpenAI 503 server_is_overloaded. It does not help when your organisation hit a provider-wide rate or spend limit, so keep at least one link on a second provider.
How do I fall back when the prompt is too long?
Treat a context-length 400 as its own case and route it to a model with a larger window, such as Claude Sonnet 5.5 with its 1M-token context. In LiteLLM that is context_window_fallbacks.
Does a fallback break prompt caching?
Yes. The fallback provider has never seen your cached prefix, so the first requests pay full input price. We priced that effect in model fallback chains and outage cost.