Tutorial
Generative AI
8 min reading

How to Add Automatic Fallbacks Between LLM Providers in Production?

Summarize this article with:

summary

Automatic fallbacks give each LLM request an ordered list of backup models, handled by a gateway such as Eden AI, OpenRouter, Vercel AI Gateway, Portkey or Cloudflare AI Gateway, by a self-hosted proxy like LiteLLM, or by your own code. Rate limits, outages and timeouts arrive as errors and trigger fallbacks. Refusals and malformed output usually arrive as HTTP 200 and need their own check. This guide maps each failure to a response, shows a tested fallback loop in Python, compares the main tools and explains how failed attempts are billed.

To add automatic fallbacks between LLM providers, give every request an ordered list of backup models and let a gateway, or a small piece of client code, move to the next one when an attempt fails. Hosted gateways such as Eden AI, OpenRouter, Vercel AI Gateway, Portkey and Cloudflare AI Gateway accept that list in the request or in a saved configuration. LiteLLM does the same as a proxy you host yourself, and LangChain wraps it around a model in your code.

Writing the list is the easy part. The harder decision is what counts as a failure. Rate limits, outages and timeouts arrive as errors, but a model that declines a request, or returns JSON your parser rejects, usually answers with HTTP 200, and a fallback that watches status codes never sees it. Billing differs too: some tools charge only for the attempt that succeeds, while others can bill a refused attempt as well as its replacement.

This guide maps each failure to the right response, shows a fallback loop you can build yourself, compares the main tools as of December 4, 2026, and ends with how to test the chain before an outage tests it for you.

Which failures should trigger a fallback?

Failures differ in how they reach your code and in what fixes them. Waiting a second fixes a brief rate limit, while no amount of waiting fixes a prompt that is too long for the model's context window. The table pairs each failure with the response that actually helps.

FailureWhat reaches your codeBest responseCaught by a status-code rule?
Rate limit429, often with a Retry-After headerRetry briefly with backoff, then move to another providerYes
Outage or overloadA 5xx status or a connection errorThe same model on another provider, then another modelYes
TimeoutNothing before your deadlineCancel and move on, with a deadline you set yourselfOnly if your client or gateway enforces one
Context window exceeded400 with a context-length errorA model with a larger window, or a shorter prompt, never a plain retryOnly in tools with a dedicated rule
Refusal or content filter200 with stop_reason: "refusal", a refusal field or finish_reason: "content_filter"Another model, if the request should be answeredNo
Malformed output200 with output that fails your validationA retry or another model, decided by your validatorNo
Region or data policy block451 on Eden AI's EU endpoint, or a policy errorFail clearly instead of sending data where it may not goIt shouldn't be

Sources: OpenAI, Anthropic and Eden AI API documentation. Checked December 4, 2026.

The two rows that return 200 are the ones most fallback setups miss. Claude models return a refusal as a normal response with stop_reason: "refusal", and OpenAI exposes it in a refusal field on the message, as its Structured Outputs guide shows, so a gateway set to react to errors passes it straight through. Anthropic offers a server-side fallback for this case, in beta, which retries a declined request on another Claude model within the same call. It reacts only to declines from its safety classifiers, though: a rate limit or server error on the requested model still comes back to you unchanged.

Keep refusals in their own category when you log. One model declining a legitimate request is a good reason to try another, but a steady stream of refusals from the same feature usually means a prompt needs fixing, and mixing them with outages hides both signals.

In what order should retries and fallbacks run?

Each layer fixes a different kind of failure, and each one changes more about the answer than the one before it, so a production chain climbs them in this order.

Where a failed request goes next

Retry the same target

For brief 429s and 5xx errors: one or two tries with backoff.

Same model, another provider

Identical behaviour, so nothing downstream changes.

A different model

Different output, so test it as carefully as the primary.

A clear error

Logged with every attempt and returned without a long hang.

The ladder only works if one layer owns the retries. The OpenAI Python SDK retries connection errors, 408, 409, 429 and 5xx responses twice by default, and waits up to 10 minutes before timing out. Put that client behind a gateway that also retries and a single call can turn into a long series of attempts, each spending its full timeout before the next one starts. Set max_retries and timeout deliberately, and decide whether the client or the gateway handles retries.

A good chain also remembers. LiteLLM puts a deployment into cooldown once it fails more than allowed_fails times within cooldown_time, and Eden AI ranks failing providers below healthy ones. Without that memory, every request pays the timeout of a provider the system already knows is down. Fallback is one routing decision among several: load balancing and LLM routing decide where the first attempt goes, while a fallback decides what happens after it fails.

How do you build fallbacks yourself?

If you call two or three providers through OpenAI-compatible APIs, a loop of about 50 lines covers the ladder above. Each target gets its own client with a short timeout and the SDK's retries turned off, so the loop alone decides what happens next.

Python

import time

from openai import (
    OpenAI,
    APIConnectionError,
    APITimeoutError,
    BadRequestError,
    InternalServerError,
    RateLimitError,
)

# One OpenAI-compatible client per target, tried in this order.
# max_retries=0 hands every retry decision to the loop below.
TARGETS = [
    (OpenAI(api_key="PRIMARY_KEY", timeout=20, max_retries=0), "PRIMARY_MODEL"),
    (
        OpenAI(
            api_key="BACKUP_KEY",
            base_url="https://BACKUP_PROVIDER/v1",
            timeout=20,
            max_retries=0,
        ),
        "BACKUP_MODEL",
    ),
]

TRANSIENT = (RateLimitError, InternalServerError, APITimeoutError, APIConnectionError)


def complete(messages, targets=TARGETS, tries_per_target=2):
    last_error = None
    for client, model in targets:
        for attempt in range(tries_per_target):
            try:
                response = client.chat.completions.create(
                    model=model, messages=messages
                )
            except TRANSIENT as error:
                last_error = error
                if attempt + 1 < tries_per_target:
                    time.sleep(2**attempt)  # back off before the next try
                continue
            except BadRequestError as error:
                last_error = error  # same request fails again: next target
                break
            choice = response.choices[0]
            refused = choice.finish_reason == "content_filter" or getattr(
                choice.message, "refusal", None
            )
            if refused:
                last_error = RuntimeError(f"{model} declined the request")
                break  # declined: retrying the same model won't help
            return model, choice.message.content
    raise RuntimeError("Every fallback target failed") from last_error

The loop treats a 400 as final for that target, because the same request would fail again there, and treats a refusal the same way. Authentication errors are deliberately not caught: a wrong key is a configuration bug you want to see immediately, not something to route around. Because the targets are passed in as data, the same function is easy to test with fake clients.

What it leaves out is where most of the production work sits. Streaming comes first: once tokens reach the user, switching models means restarting the answer, which is why LiteLLM only falls back when a stream fails before its first chunk. Providers behind OpenAI-compatible endpoints also differ in tool calling and structured output support, the loop forgets which target failed a second ago, and nothing records which attempt served. For sustained rate limits, a queue in front of the loop does more than retries, as covered in how to handle rate limits for LLMs and AI APIs.

Which tools add automatic fallbacks?

Three kinds of tools take this work off your hands: hosted gateways that read the fallback list from the request, proxies you deploy yourself, and libraries that wrap the call in your code. They differ most in what they react to by default and in how they tell you which model answered.

ToolTypeHow you set fallbacksDefault triggersWhich model served
Eden AIHosted gatewayfallbacks array, plus same-model provider failoverProvider outage, rate limit, errorattempts in edenai_metadata
OpenRouterHosted gatewaymodels arrayContext length, moderation flags, rate limits, downtimemodel field in the response
Vercel AI GatewayHosted gatewayproviderOptions.gateway.models, with order for providersEvery provider of a model failsmodelAttempts in provider metadata
PortkeyHosted gatewayConfig with strategy.mode: "fallback"Any non-2xx status, narrowed with on_status_codesLogs, filtered by trace ID
Cloudflare AI GatewayHosted gatewayArray of steps on the Universal endpointErrors and request timeoutscf-aig-step response header
LiteLLMSelf-hosted proxy or SDKfallbacks, context_window_fallbacks, content_policy_fallbacksEach error type to its own list, after num_retriesYour proxy's logs
LangChainLibrary.with_fallbacks() on a model or chainAny ExceptionYour own code

Sources: each vendor's documentation, linked in the first column. Checked December 4, 2026.

Defaults matter more than they look. Portkey's any-non-2xx rule also fires on a malformed request that will fail on every target, so narrowing on_status_codes to 429 and 5xx is usually worth it, and LangChain's default catches bugs in your own code along with provider errors. OpenRouter reacts to context-length and moderation errors that a plain status rule misses, and LiteLLM gives each of those its own list plus cooldowns, at the cost of running and upgrading the proxy yourself, a trade-off covered in LiteLLM vs a hosted AI gateway.

A refusal that arrives as a successful response is the hard case for all of them, so check how your tool treats it or keep the check from the loop above. For a wider comparison of routing features, cost and latency, see the best LLM routers.

How do you add fallbacks with Eden AI?

Eden AI applies two layers to one request. When you don't name a provider, it first tries the same model on other providers that sell it, then moves through the models in your fallbacks list. The fallback documentation allows up to 11 entries for LLMs and 3 for expert models, with at most 12 attempts per LLM request, and your listed fallbacks always keep their slots. Adding the x-edenai-metadata: enabled header returns every attempt with the response.

Python

import requests

response = requests.post(
    "https://api.edenai.run/v3/chat/completions",
    headers={
        "Authorization": "Bearer YOUR_API_KEY",
        "x-edenai-metadata": "enabled",  # report every attempt
    },
    json={
        "model": "gpt-5.6-sol",
        "fallbacks": ["~gemini-pro-latest", "mistral/mistral-large-latest"],
        "messages": [{"role": "user", "content": "Summarize this incident report."}],
    },
    timeout=60,
)

data = response.json()
print(data["edenai_metadata"]["attempts"])
print(data["choices"][0]["message"]["content"])

If the first provider serving gpt-5.6-sol, say Azure, returns a 429 and OpenAI then answers, attempts lists both with their status codes and attempt is 2. On a stream, the request metadata rides the first chunk and is corrected in the error frame if the stream fails partway. It is left out when the response comes from cache, since no provider was called.

Provider routing shapes the provider layer: you can order or exclude providers, cap the price per million tokens, and keep a conversation on the provider that holds its prompt cache. Setting routing.allow_fallbacks: false turns off provider failover without touching your fallbacks list. To share one chain across services, save it as a routing policy with a management key and call it with "model": "policy/prod-chat". A policy can retry each target up to 3 times, balance traffic by weight, or order targets by cost or time to first token, and a request's own fallbacks run after the policy's chain.

Residency rules hold through a fallback. On the EU endpoint, every entry in the fallback list must be EU-eligible, or the request fails with HTTP 451 and region_not_allowed before any provider is contacted. Zero data retention works the same way: a fallback that doesn't qualify fails the request instead of quietly sending your data elsewhere. Eden AI's documentation names provider outages, rate limits and errors as fallback triggers, so for answers that complete but decline, keep the finish_reason check from the loop above.

How are fallback requests billed?

A fallback can cost money in three places: the attempts that failed, the price gap between the primary and the backup, and the prompt cache you lose by switching. Who pays for the first depends on the setup.

SetupFailed attemptsWorth knowing
Eden AINot billed: you pay for the attempt that answeredRequests sent with your own provider keys are billed by that provider
OpenRouterBilled at the price of the model that answeredA free model followed by a paid fallback costs the paid price
Anthropic server-side fallbackThe refusal is billed when it arrived mid-stream or falls in a billed categoryFallback credit offsets the fallback model's prompt-cache miss
Your own loop, LiteLLM, or your own keys behind a gatewayEach provider bills its own attemptsCheck how each one treats requests that fail partway

Sources: Eden AI, OpenRouter and Anthropic documentation. Checked December 4, 2026.

The other two costs apply even when failed attempts are free. A cheap primary that falls back to a premium model can multiply the bill during an outage, so price the fallback list as carefully as the primary, or cap it with a ceiling such as Eden AI's max_price. A provider switch also starts with a cold prompt cache, so the first fallback request in a long conversation pays for the whole prompt again, without a cache discount. That is the cost Anthropic's fallback credit compensates for, and the reason sticky routing keeps a conversation on the provider that holds its cache.

How do you test fallbacks before a real outage?

Test the decision logic and the live path separately. Unit tests can hand the loop fake clients that raise a 429, time out or return a refusal, then assert which target answered. In staging, send real requests through your gateway and read the attempt record it returns, listed in the last column of the comparison table, to confirm the order you configured is the order that runs.

In production, watch the share of requests served by a fallback instead of waiting for errors. A primary that degrades slowly shows up there well before it fails outright, and the same number tells you how much latency and cost the chain adds. With Eden AI, you can log the attempt record per request and review past calls in the request logs.

Re-check the chain whenever a model in it is retired or changes. An entry you never reach can still break every request: Anthropic validates every named fallback entry before the primary runs, so when Claude Opus 4.8 lost fast mode, an entry that still asked for it could reject the whole request. A model ID that starts returning 404, as Claude Sonnet 4.5 did, leaves a silent gap in the list until someone looks.

FAQ

A retry sends the same request to the same model and provider again, which fixes brief rate limits and transient server errors. A fallback sends it to another provider or another model, which fixes outages and errors that would repeat. Most production setups retry once or twice, then fall back.
Usually not. Refusals arrive as successful HTTP 200 responses: Claude returns stop_reason "refusal", and OpenAI-compatible APIs use a refusal field or finish_reason "content_filter". A fallback that reacts to status codes passes them through, so check for them in your code, or use Anthropic's server-side fallback, in beta, for Claude models.
Two or three cover most applications: the same model on another provider, then a model from a different family. Each extra entry adds its timeout to the worst-case response time. Eden AI accepts up to 11 fallbacks for LLMs and 3 for expert models.
It depends on the setup. Eden AI bills only the attempt that produced the response, and OpenRouter bills at the price of the model that answered. Anthropic bills some refusals in addition to the fallback request. With your own provider keys, each provider bills its own attempts.
Before the first token, yes: a stream that fails early can move to the next target, as LiteLLM documents. Once tokens have reached the user, switching models means restarting the answer, so many applications show an error and let the user retry instead.
No. Load balancing spreads healthy traffic across targets to manage capacity and cost, while a fallback reacts after an attempt fails. Many gateways combine both: Eden AI routing policies offer fallback and load_balance strategies, and Portkey can nest a load balancer inside a fallback.
Yes, if the fallback list includes providers outside the EU. On Eden AI's EU endpoint, every fallback must be EU-eligible, otherwise the request is rejected with HTTP 451 before any provider is contacted.

Further reading

Similar articles

A stream of tokens splits into three channels for misses, reads and writes that together drive one input cost gauge, beside a disconnected request counter.
Tutorial
Generative AI
How to Calculate Cached LLM Input Cost From API Usage Fields
12/4/2026
·
Written byClément Moreau
A key inside a glass project vault secured by two identity badges, with a side path leading to a backup model tower.
Tutorial
Generative AI
Which Google Account Should Own Your Gemini API Key?
12/1/2026
·
Written byClément Moreau
An approved package pipe bypasses an agent sandbox wall before an external policy gate blocks its route to other systems.
Tutorial
Generative AI
How OpenAI's Test Agents Got Out, and How to Contain Yours
11/30/2026
·
Written byClément Moreau
let’s start

Start building with Eden AI

A single interface to integrate the best AI technologies into your products.