A single free provider is a single point of failure: the quota runs out at the worst possible moment, the model rotates under the hood, the platform goes down for maintenance. Practitioners solve the problem not by hunting for a “reliable” service but with a fallback chain — an ordered list of backup routes along which a request moves from layer to layer until it gets an answer. The same pattern lives in three incarnations: twenty lines of Python, branching by error code in n8n, and a fallbacks block in a LiteLLM config. Let’s go through the order of layers, the definition of failure, and the typical assembly mistakes.
The three layers of the chain
A minimal working chain is three layers. Primary: a fast, cheap provider for the task’s role — routine on Groq or Cerebras, code on GLM Flash, large documents and media on Gemini. Backup: a provider with a different quota and a different company — for example, the free OpenRouter pool, where hundreds of models live under one key. Emergency: a slow but alive route — a paid model with pocket-change cost on short prompts, or a gateway with a signup bonus set aside for rare escalations.
The main rule: the layers must not fail for one and the same reason. Two providers with daily quotas reset at midnight UTC will go down together at the evening peak. A primary and a backup from different companies, with different types of limits (requests per day, tokens per day, monthly volume) and different reset cycles fail simultaneously extremely rarely — that is the whole point of the layout.
A chain in Python: twenty lines
The core of the pattern — walking the list of layers with a result check and a label of who answered:
from openai import OpenAI
CHAIN = [
("fast", "https://api.groq.com/openai/v1", "GROQ_KEY", "openai/gpt-oss-20b"),
("code", "https://api.z.ai/api/paas/v4", "ZAI_KEY", "glm-4.7-flash"),
("router", "https://openrouter.ai/api/v1", "OR_KEY", "nvidia/nemotron-3.5-lightning:free"),
]
def ask(prompt: str) -> str:
last = None
for name, base, key, model in CHAIN:
try:
client = OpenAI(base_url=base, api_key=key)
r = client.chat.completions.create(
model=model,
messages=[{"role": "user", "content": prompt}],
timeout=30,
)
text = r.choices[0].message.content
if text:
return f"[{name}] {text}"
last = "empty content"
except Exception as e:
last = repr(e)
raise RuntimeError(f"все провайдеры упали: {last}")The layer label in the answer is minimal observability: it shows right away who answered and how often the transitions fired. Empty content is treated as a failure — otherwise an empty answer will quietly reach the consumer as a result. Keys are read from environment variables: only names remain in the code.
What counts as a failure
A chain is useful exactly as far as the failure is honestly defined. A 429 with a Retry-After header is not a failure but a pause: waiting out the delay and repeating on the same layer is cheaper than burning the next one. 5xx, a dropped connection and a timeout (30 seconds in the example) — move to the next layer. An empty answer is always a failure. An exhausted daily quota — switch away for the whole period until the reset: repeating the request is pointless, the limit will not come back in a second.
Where the chain does not save you
A fallback solves availability, not privacy: most free tiers log prompts, and switching between layers does not change that — for business tasks with client data the scheme does not fit. The second limitation is a different answer on every request: the layers answer with different models, and quality floats together with the route. Where reproducibility matters, the chain works as an escalation, not as the main road.
The failure and reaction matrix
The rules from the previous section are collected into a table — it is convenient to keep next to the chain config as a specification of behavior, shared by Python, n8n and LiteLLM.
| Event | Sign | Chain reaction |
|---|---|---|
| Rate limit | 429 with a Retry-After header | Pause from the header, repeat on the same layer |
| Server failure | 5xx or a dropped connection | Next layer immediately |
| Silence | Timeout, 30 seconds in the example | Next layer; do not accumulate long timeouts |
| Empty answer | content missing or empty | Treat as a failure, next layer |
| Quota exhausted | 429 on every request until the reset | The layer is excluded until the end of the daily cycle |
| All layers down | RuntimeError from the wrapper | Notification and a postponed retry of the task |
The row about the exhausted quota is the most frequent configuration mistake: the chain keeps knocking on a layer whose daily quota is gone instead of excluding it until midnight UTC. The cure is simple — a counter of consecutive 429s without Retry-After: three in a row, and the layer is switched off until the end of the cycle. The row about the notification is about honesty with yourself: if the RuntimeError has become a regular occurrence, the chain is not rubber, and it is time to rethink the order of the layers.
Frequently asked questions
How many layers to make? Three is enough for personal pipelines: more layers — a longer worst case. A request that passed all three layers through timeouts will spend up to a minute and a half and may still come back with nothing — better three healthy layers than five formal ones.
The chain in code or in a proxy? For a single script — the twenty lines above. When there are many clients (a bot, n8n, harnesses), move it into LiteLLM: a fallbacks block in router_settings does the same thing once for everyone, and a provider change is a one-line edit in the config.
Isn’t the emergency layer expensive? It fires only on failures, and their share with healthy layers is percent-level. The share is visible from the layer labels in the usage journal: if the emergency layer answers more often than the primary one, the problem is in the order of the layers, not in the price.
How to test the chain? Disable the primary layer (an invalid key) and run a real task: the transition should go to the backup, and the layer label should appear in the answer. Once a week — together with the regular provider check; once a month — a full pass of all the layers.
In what order to place the models by price? The cheaper ones first, but adjusted for the role: a code task on a weak fast model turns into a repeated request to the next layer and double quota spending. The order is optimized for the pair “price × probability of an answer from the first layer”, not for the price alone.
Keep the layer keys in the code? No: in environment variables, as in the example — os.environ reads the values at startup, and only names remain in the code. The rule is the same as for the proxy: clients and the repository must not see the provider keys.
What if the backup layer is slower? Expected: the backup is chosen for a different quota, not for speed. The layer label in the answer lets you measure the share of slow routes; if it grows, swap the layers after checking them on real tasks.
How often to revisit the chain? Segment conditions live for weeks: models rotate, limits change, domains move. Once a week reconcile the layers against the live provider panels, once a month — against the transition journal: a growing share of the emergency layer is a signal to rebuild the order.
Fallback chains are a discipline of order: who is primary, who is backup, who is emergency, and what counts as a failure. The layout of roles across providers, the quota reset cycles and a one-command check of each layer — in the material on the limits pie; the pairing with the proxy and the config — in the material on LiteLLM on a VPS. The figures are current as of autumn 2026.
