Fallback Model Chains: Cascading from Primary to Secondary LLM
Design a primary→secondary→tertiary model chain with the right triggers, a wrapper you can put in front of an ADK agent, circuit breakers and health scoring, prompt compatibility across tiers, and the latency and cost trade-offs.
Published on • November 27, 2026
AI Assistant

One model is a dependency; a chain is a system. When the primary endpoint returns 429, times out mid-stream, or starts emitting malformed JSON, the question is not whether you retry — it’s whether the user’s turn completes at all. A fallback chain answers that by cascading to a secondary model on defined triggers, so a provider hiccup degrades into slower responses instead of an error page.
This tutorial covers designing that chain: what should trigger a fallback, how to implement one cleanly around an ADK agent, how to keep prompts and schemas compatible across tiers, and when a chain costs you more than it saves.
Triggers: what earns a fallback
Not every failure deserves a second model. Classify first:
| Trigger | Fallback? | Why |
|---|---|---|
429 / RESOURCE_EXHAUSTED (short horizon) | After 1–2 local retries | The primary may recover instantly, but the user is waiting |
| 503 / unavailable, connection refused | Yes, immediately | Endpoint-level failure |
| Timeout with no first token | Yes | Bounded wait already spent |
| Malformed structured output after a repair attempt | Yes | A different model may simply behave better |
| 400 validation / bad request | No | Same request will fail everywhere — it’s a bug |
| 401/403 auth | No | Fix credentials; cascading hides it |
| Quality below threshold (optional) | Maybe | Needs a judge; adds cost and latency |
The discipline: the fallback list excludes anything request-shaped. If the payload is wrong, every model in the chain rejects it, and you have just multiplied the latency of a bug.
Implementing the chain
The clean seam is a wrapper that owns model selection, so the agent stays declarative:
import time
CHAIN = [
{'model': 'gemini-3.8-flash', 'tier': 'fast'},
{'model': 'gemini-3.8-pro', 'tier': 'deep'},
{'model': 'local-qwen-32b', 'tier': 'last-resort'},
]
FALLBACKABLE = {'429', '500', '502', '503', '504', 'RESOURCE_EXHAUSTED', 'UNAVAILABLE', 'DEADLINE_EXCEEDED'}
async def run_with_fallback(runner_kwargs, chain=CHAIN, attempt_stats=None):
last_error = None
for hop, spec in enumerate(chain):
started = time.perf_counter()
try:
events = await _invoke(spec['model'], **runner_kwargs)
if attempt_stats is not None:
attempt_stats.observe(spec['model'], hop=hop, ok=True,
seconds=time.perf_counter() - started)
return events
except Exception as exc:
code = str(getattr(exc, 'code', '') or getattr(exc, 'status_code', '')).upper()
if code not in FALLBACKABLE:
raise # request-shaped or auth failure: don't cascade
last_error = exc
if attempt_stats is not None:
attempt_stats.observe(spec['model'], hop=hop, ok=False, code=code)
raise last_error
Two properties make this production-safe:
- The chain is ordered by capability and cost. You fall down (cheaper/faster) for transient errors and up (deeper) only for quality triggers — never sideways out of a cost-controlled budget without an explicit rule.
- Every hop is measured. Fallback rate per model per hour is your health signal; without it, a permanently broken primary looks like “we just use two models sometimes”.
Circuit breakers and health scoring
A chain without a breaker sends every request into a dead endpoint first, paying the timeout on each one. Add a breaker:
class Breaker:
def __init__(self, failure_threshold=5, reset_seconds=30):
self.failures = 0
self.open_until = 0.0
self.threshold = failure_threshold
self.reset = reset_seconds
def allow(self) -> bool:
return time.time() >= self.open_until
def record(self, ok: bool):
if ok:
self.failures = 0
return
self.failures += 1
if self.failures >= self.threshold:
self.open_until = time.time() + self.reset
When a breaker is open, skip that hop entirely — the chain degrades to the remaining members while the primary recovers. Half-open probes (one trial request per cooldown) restore it without a stampede.
Keeping the chain prompt-compatible
The secondary model reads the same system instruction, so it must honour the same contract:
- Shared instruction and schema. The same
response_schema, the same output format, the same tool names. If only the primary supports a proprietary feature, gate that feature by model capability, not by hop position. - Test the whole chain. A chain that works only while the primary is healthy has never been tested. Run your eval set against each hop with failover forced.
- Watch tool-calling differences. Models differ in argument fidelity and multi-call behaviour; validate tool selection per hop, as in deterministic tool calling — and note that re-running a turn (rather than a single model call) re-executes tools, so make mutations idempotent first.
- Declare degraded mode. If the last-resort model can’t do grounding or has a smaller context, drop features explicitly instead of truncating silently.
Latency and cost trade-offs
Every fallback multiplies worst-case latency:
primary timeout (5 s) + secondary first token (0.8 s) ≈ 6 s before the user sees anything
Mitigations:
- Bound the primary wait tightly. A 5-second no-TTFT budget, not a 30-second default.
- Fail fast on breaker-open hops. Zero milliseconds, not a timeout.
- Failover only what the user is waiting for. Background/ambient tasks can queue behind a healthy-model wait; interactive turns should move immediately.
- Budget the chain. Cap total hops (2 is usually right) and total wall-clock time; after the cap, return a structured “temporarily degraded” answer.
Cost-wise, cascading to a more expensive tier on every transient 429 turns a hiccup into a bill spike. Prefer falling to an equally-capable cheaper path first, and reserve the deep tier for explicit quality triggers.
Takeaways
- Cascade on transport- and availability-class failures only; never on validation, auth, or request-shaped errors.
- Wrap model invocation so the agent stays declarative, measure every hop, and add circuit breakers so a dead endpoint costs zero milliseconds.
- Keep instruction, schema, and tool contracts identical across hops, and test each hop with failover forced.
- Bound worst-case latency with a short no-TTFT budget and a cap on total hops.
- Track fallback rate per model — it’s your earliest warning that a provider or a prompt change is degrading.