●2.5 ROUTE — From today, 12/1, calls to gemini-2.5-pro and 2.5-flash are rerouted to newer models automatically●CLI 0.71.1 — Gemini CLI stable is still v0.71.1, with a 0.73 nightly published on 11/30●INTRO END — Introductory pricing for 3.8, 3.7 and 3.6 Flash ends on 12/31. 30 days left●VERTEX — Developers are asking how to run Gemini CLI with Vertex AI credentials●NEON — Gemini 4 Neon became generally available on 11/18 (paid tier only)●IMAGE TEXT — A new test shows text inside an image can sway Gemini's answer●2.5 ROUTE — From today, 12/1, calls to gemini-2.5-pro and 2.5-flash are rerouted to newer models automatically●CLI 0.71.1 — Gemini CLI stable is still v0.71.1, with a 0.73 nightly published on 11/30●INTRO END — Introductory pricing for 3.8, 3.7 and 3.6 Flash ends on 12/31. 30 days left●VERTEX — Developers are asking how to run Gemini CLI with Vertex AI credentials●NEON — Gemini 4 Neon became generally available on 11/18 (paid tier only)●IMAGE TEXT — A new test shows text inside an image can sway Gemini's answer
Designing a Multi-LLM Failover Architecture Around Gemini API: Production Redundancy Patterns That Actually Hold
A production pattern for keeping Gemini API as your primary with Claude as the fallback: adapters, failure classification, a single-probe circuit breaker and log columns, in runnable Python. Model IDs and prices updated for the December 1, 2026 rerouting of 2.5 models.
import { Callout } from '@/components/ui/callout';
I was reworking the feature in my app that drafts review replies with the Gemini API one evening when the error count on my dashboard jumped. The frontend loaded, the database answered, and yet every call to Gemini was timing out.
I sat there running curl against the endpoint and refreshing a status page, and for the first time I felt, rather than merely knew, how fragile it is to let one provider's bad night switch off a feature. There was nothing on my side I could do but wait. It is not a feeling I want to repeat.
This piece is the setup I landed on afterwards: Gemini stays the primary, Claude sits behind it as the fallback, and the whole thing is plain Python you can run. I'm writing for developers whose Gemini-only feature should keep answering through outages and quota walls. What I hope you take away is a working set of adapters, a breaker, a router and the log lines — and, more importantly, a rule for which failures are allowed to move to another provider.
Google's Gemini API deprecations page says that from December 1, 2026, calls to `gemini-2.5-pro` are routed to `gemini-3.8-flash` and calls to `gemini-2.5-flash` to `gemini-3.5-flash-lite`, billed at the destination model's rates. The earlier version of this article used `gemini-2.5-pro` as the primary; the code below has been updated. Before anything else, it's worth searching your own code for 2.5 model IDs.
The short version: three decisions
Multi-LLM failover sounds like a big architecture project. In practice I've found it comes down to three decisions.
Take model names out of the calling code. The app calls router.complete(request) and nothing else; the response records which provider and which model actually answered.
Decide which failures may move. Timeouts, 429s and 5xx errors are the other side having a bad moment, so they go to the next provider. A 400 is my mistake, and sending it elsewhere just fails again for the same reason.
Exercise the fallback path on a schedule. A path that never runs rots quietly — an expired key or an SDK update is enough.
Everything below is just those three decisions written down as code.
Why avoid depending on one provider
Picking a primary is not the problem. Gemini balances quality, price and multimodal input well, and I haven't changed my mind about keeping it first. What I'd separate is "choosing a primary" from "having somewhere to go when the primary can't answer."
In my own services, LLM calls stop going through for roughly three reasons.
Provider incidents. Google, Anthropic and OpenAI all have hour-scale incidents in their status history, and launches of new models seem to be the shakiest windows.
Hitting limits. A burst of traffic or a wave of new users, and suddenly you're getting 429s that you caused yourself. Gemini API limits are set per project and tier, and raising them is not instant.
Model swaps. As with the December 1 rerouting, a model ID you specified can start being answered by a different model. Nothing breaks, which is exactly why it's easy to miss.
Failover absorbs the first two. Logging is how you notice the third. The rest of the design follows that split.
✦
Thank you for reading this far.
Continue Reading
What follows includes implementation code, benchmarks, and practical content we hope you'll find useful. This site runs without ads — server and development costs are supported entirely by members like you. If it's been helpful, we'd be truly grateful for your support.
WHAT YOU'LL LEARN
✦Move a Gemini-only feature to a setup that falls back to Claude without touching application code
✦Get runnable Python that fails over on timeouts, 429s and 5xx errors but never on a 400
✦Log the requested and served model side by side so swaps like the December 1 rerouting show up in your logs
Secure payment via Stripe · Cancel anytime
✦
Unlock This Article
Get full access to the rest of this article. Buy once, read anytime. This site is ad-free — your support goes directly toward keeping it running.
Application code: one abstract call, "ask the LLM"
Router: chooses a provider from breaker state, input length and task type
Adapters: thin wrappers that turn each SDK into one shared request/response type
Observability: per call, the provider, requested model, served model, latency and cost
Circuit breaker: stops calling a provider for a while after repeated failures
Once everything flows app → router → adapter → provider, the app no longer cares who answered, and adding a provider is one new adapter file plus one line in the router.
Adapters: one request type, one response type
I start with a Protocol every adapter satisfies. Without it, the router turns into a thicket of provider-specific branches.
# llm/base.pyfrom __future__ import annotationsfrom dataclasses import dataclassfrom typing import Protocol@dataclass(frozen=True)class LLMRequest: """Shared request. Provider differences are absorbed inside each adapter.""" system: str user: str max_tokens: int = 2048 temperature: float | None = None # None means "use the model default" expects_json: bool = False@dataclass(frozen=True)class LLMResponse: """Shared response. Always records who answered and with which model.""" text: str provider: str # "gemini" / "claude" requested_model: str # the model ID we asked for served_model: str # the model ID reported in the response input_tokens: int output_tokens: int # includes thinking tokens cost_usd: float | None # None when we have no verified priceclass LLMAdapter(Protocol): name: str context_tokens: int async def complete(self, request: LLMRequest) -> LLMResponse: ...
The change from the previous version is splitting requested_model from served_model. When the ID you asked for and the model that answered drift apart — as they will on December 1 for 2.5 IDs — it shows up as one column in the logs.
The Gemini adapter assumes Python 3.11 and the google-genai SDK.
# llm/gemini_adapter.pyimport osfrom google import genaifrom google.genai import typesfrom .base import LLMRequest, LLMResponse# USD per 1M tokens, taken from the official pricing page in November 2026.# gemini-3.8-flash is on introductory pricing until 2026-12-31; from 2027-01-01 it is 1.50 in / 7.50 out.# Models without an entry are logged with cost None rather than a guessed price.PRICING = { "gemini-3.8-flash": {"input": 0.75, "output": 3.75},}class GeminiAdapter: name = "gemini" context_tokens = 1_000_000 def __init__(self, model: str = "gemini-3.8-flash", timeout_ms: int = 20_000, thinking_level: str | None = None): self._client = genai.Client( api_key=os.environ["GEMINI_API_KEY"], http_options=types.HttpOptions(timeout=timeout_ms), # milliseconds ) self._model = model self._thinking_level = thinking_level async def complete(self, request: LLMRequest) -> LLMResponse: config = types.GenerateContentConfig( system_instruction=request.system, max_output_tokens=request.max_tokens, ) if request.temperature is not None: config.temperature = request.temperature if request.expects_json: config.response_mime_type = "application/json" if self._thinking_level: config.thinking_config = types.ThinkingConfig(thinking_level=self._thinking_level) result = await self._client.aio.models.generate_content( model=self._model, contents=request.user, config=config, ) usage = result.usage_metadata input_tokens = usage.prompt_token_count or 0 # Thinking tokens are billed as output, so count them there output_tokens = (usage.candidates_token_count or 0) + (usage.thoughts_token_count or 0) price = PRICING.get(self._model) cost = None if price is None else ( input_tokens / 1_000_000 * price["input"] + output_tokens / 1_000_000 * price["output"] ) return LLMResponse( text=result.text or "", provider=self.name, requested_model=self._model, served_model=result.model_version or "unknown", input_tokens=input_tokens, output_tokens=output_tokens, cost_usd=cost, )
Three details are worth slowing down for. First, the timeout: HttpOptions.timeout takes milliseconds, and without it a struggling provider's wait becomes your user's wait. Second, thoughts_token_count: on thinking models, those tokens are billed as output. The old version only used candidates_token_count and underestimated cost.
Third, I no longer send temperature by default. Google's developer guide for the Gemini 3 generation recommended leaving temperature at its default of 1.0, warning that lowering it could cause looping or degraded results. I haven't been able to confirm whether 3.8 Flash is treated the same way, so the adapter only sends a temperature when the caller asks for one.
The Claude adapter has the same shape.
# llm/claude_adapter.pyimport osimport anthropicfrom .base import LLMRequest, LLMResponse# USD per 1M tokens (checked on Anthropic's pricing page, November 2026)PRICING = { "claude-haiku-4-5-20251001": {"input": 1.00, "output": 5.00}, "claude-sonnet-4-6": {"input": 3.00, "output": 15.00},}JSON_HINT = "Respond with valid JSON only. Do not add any prose before or after it."class ClaudeAdapter: name = "claude" context_tokens = 200_000 def __init__(self, model: str = "claude-haiku-4-5-20251001", timeout_s: float = 20.0): # Turn off SDK retries; the router is the only place that decides to retry self._client = anthropic.AsyncAnthropic( api_key=os.environ["ANTHROPIC_API_KEY"], timeout=timeout_s, max_retries=0, ) self._model = model async def complete(self, request: LLMRequest) -> LLMResponse: user = request.user + ("\n\n" + JSON_HINT if request.expects_json else "") kwargs = dict( model=self._model, system=request.system, messages=[{"role": "user", "content": user}], max_tokens=request.max_tokens, ) if request.temperature is not None: kwargs["temperature"] = request.temperature result = await self._client.messages.create(**kwargs) text = "".join(b.text for b in result.content if b.type == "text") price = PRICING.get(self._model) cost = None if price is None else ( result.usage.input_tokens / 1_000_000 * price["input"] + result.usage.output_tokens / 1_000_000 * price["output"] ) return LLMResponse( text=text, provider=self.name, requested_model=self._model, served_model=result.model, input_tokens=result.usage.input_tokens, output_tokens=result.usage.output_tokens, cost_usd=cost, )
The previous version listed Claude Haiku at $0.25 in / $1.25 out per million tokens. Those were an older generation's numbers; Haiku 4.5 is $1 in / $5 out. Fallback cost estimates were off by a factor of four, so please replace them if you copied the old code.
max_retries=0 is deliberate too. The Anthropic Python SDK retries on its own by default. If the router also moves on to another provider, both layers keep trying, and outage latency multiplies.
Which failures may move to another provider
This is what the old version lacked most. At first I caught except Exception and sent everything to the next provider.
Then an oversized request with an image attached got a 400 from Gemini, went straight on to Claude, and was rejected there as well. The user waited through two providers before seeing an error, my logs counted it as a "Gemini failure," and the breaker opened — pushing perfectly good requests over to Claude. It wasn't until I laid out the failure breakdown that night that I saw I'd been treating my own mistake as their outage.
Move their bad moments, never my mistakes. That's the rule I use now, and it splits exceptions three ways.
# llm/errors.pyimport asyncioimport anthropicfrom google.genai import errors as genai_errorsTRANSIENT = {408, 429, 500, 502, 503, 504, 529} # 529 is Anthropic's "overloaded"CONFIG = {401, 403, 404} # key, permission or model-ID problemsdef classify(exc: Exception) -> str: """'failover' (move on) / 'alert' (move on, but flag a config problem) / 'raise' (don't move)""" if isinstance(exc, (asyncio.TimeoutError, TimeoutError)): return "failover" if isinstance(exc, (anthropic.APITimeoutError, anthropic.APIConnectionError)): return "failover" status = None if isinstance(exc, genai_errors.APIError): status = exc.code elif isinstance(exc, anthropic.APIStatusError): status = exc.status_code if status in TRANSIENT: return "failover" if status in CONFIG: return "alert" return "raise" # 400 and friends fail the same way everywhere
401, 403 and 404 move on and alert because I don't want users to lose the feature, but these failures never fix themselves. A 404 from a retired model ID is exactly this kind.
Condition
Typical cause
Handling
Counts toward breaker
Timeout / connection error
Provider incident, network trouble
Move to next provider
Yes
429
Rate or quota limit reached
Move to next provider
Yes
500 / 503 / 529
Provider internal error or overload
Move to next provider
Yes
401 / 403 / 404
Expired key, permissions, retired model ID
Move on and raise a config alert
Yes
400
Input too large, invalid argument
Return to caller without moving
No
Circuit breaker: stop calling a provider that's down
Without a breaker, every request goes "call Gemini anyway → wait for the timeout → finally try Claude," and each user pays the full timeout.
The old breaker had a bug: in HALF_OPEN it let every request through, not just one probe. A backlog would hit a provider that was only beginning to recover, knock it over again, and the breaker would flap. This version allows a single probe.
# llm/breaker.pyimport timefrom dataclasses import dataclassfrom enum import Enumclass BreakerState(Enum): CLOSED = "closed" # normal OPEN = "open" # don't call for a while HALF_OPEN = "half_open" # let exactly one probe through@dataclassclass CircuitBreaker: failure_threshold: int = 3 recovery_timeout_sec: float = 30.0 state: BreakerState = BreakerState.CLOSED failure_count: int = 0 opened_at: float = 0.0 probing: bool = False def can_attempt(self) -> bool: if self.state is BreakerState.OPEN and \ time.monotonic() - self.opened_at >= self.recovery_timeout_sec: self.state = BreakerState.HALF_OPEN if self.state is BreakerState.CLOSED: return True if self.state is BreakerState.HALF_OPEN and not self.probing: self.probing = True # one probe only return True return False def record_success(self) -> None: self.state, self.failure_count, self.probing = BreakerState.CLOSED, 0, False def record_failure(self) -> None: self.probing = False if self.state is BreakerState.HALF_OPEN: self._open() # failed probe: reopen immediately return self.failure_count += 1 if self.failure_count >= self.failure_threshold: self._open() def _open(self) -> None: self.state, self.opened_at = BreakerState.OPEN, time.monotonic()
I use time.monotonic() rather than time.time() so an NTP correction on the server can't stretch or shrink the open window. This breaker keeps state inside one process; with several workers, each opens and closes on its own. That's been fine at my scale. If you need them in sync, the state has to live somewhere shared, such as Redis.
Router: try in order, record, return
The router ties together classification, breakers and the input-length check. In the old version, the length check and the logging helper were shown in the text but never wired into the router. Here they are connected.
# llm/router.pyimport loggingfrom .base import LLMAdapter, LLMRequest, LLMResponsefrom .breaker import CircuitBreakerfrom .errors import classifyfrom .observability import observe_calllogger = logging.getLogger(__name__)class AllProvidersFailed(RuntimeError): passdef estimate_tokens(request: LLMRequest) -> int: # Japanese text lands near one token per character, so character count is a safe upper bound return len(request.system) + len(request.user) + request.max_tokensclass LLMRouter: def __init__(self, adapters: list[LLMAdapter]): self._adapters = adapters self._breakers: dict[str, CircuitBreaker] = {} async def complete(self, request: LLMRequest, chain: list[LLMAdapter] | None = None) -> LLMResponse: chain = chain or self._adapters tokens = estimate_tokens(request) last_error: Exception | None = None for position, adapter in enumerate(chain): if tokens > adapter.context_tokens * 0.8: logger.warning("skip provider=%s reason=too_long tokens=%d", adapter.name, tokens) continue breaker = self._breakers.setdefault(adapter.name, CircuitBreaker()) if not breaker.can_attempt(): logger.warning("skip provider=%s reason=breaker_open", adapter.name) continue try: async with observe_call(request, adapter.name, position): response = await adapter.complete(request) except Exception as exc: kind = classify(exc) if kind == "raise": breaker.record_success() # the provider is reachable; release any probe slot raise breaker.record_failure() if kind == "alert": logger.critical("config_error provider=%s err=%r", adapter.name, exc) last_error = exc continue breaker.record_success() if not response.served_model.startswith(response.requested_model): logger.warning("model_mismatch requested=%s served=%s", response.requested_model, response.served_model) return response raise AllProvidersFailed("no provider could answer") from last_error async def complete_with_profile(self, profile, request: LLMRequest) -> LLMResponse: return await self.complete(request, chain=profile.chain)
Breakers are keyed by adapter.name, which means one per provider. If I register two Gemini models, a Google-side incident should take both out of rotation.
Calling it looks like this.
# main.pyimport asynciofrom llm.base import LLMRequestfrom llm.router import LLMRouterfrom llm.gemini_adapter import GeminiAdapterfrom llm.claude_adapter import ClaudeAdapterrouter = LLMRouter([ GeminiAdapter(model="gemini-3.8-flash"), ClaudeAdapter(model="claude-haiku-4-5-20251001"),])async def main(): response = await router.complete(LLMRequest( system="You are a concise, polite assistant.", user="This is a failover check. Reply in one sentence.", )) print(response.provider, response.requested_model, response.served_model, response.cost_usd)asyncio.run(main())
The output has the shape gemini gemini-3.8-flash <model ID from the response> <cost>. I'm leaving the third value out on purpose, because it can change between versions. What that field will contain for a gemini-2.5-pro call after the December 1 rerouting is something I haven't been able to check yet. That uncertainty is the whole argument for logging both columns.
Choosing a fallback strategy: three options
You might wonder whether weighted distribution or round-robin is the more sophisticated choice. I tried the clever versions first. In operation, an ordered list turned out to be far easier to live with.
Strategy
Fits when
Readable during incidents
Predictable cost
Prompt tuning
Ordered list
Clear primary, others are a safety net
High — you always know who's serving
High — primary budget plus what failed over
High — tune for the primary
Weighted distribution
Sustained volume above one provider's limits
Low — always a mix
Medium
Low — no single target to tune
Per-task profiles
Light classification and heavy reasoning in one feature
High — each profile is a list
High — split by task
Medium
As a single rule: distribute only if you're permanently above one provider's limits; otherwise use an ordered list or profiles. I'm never permanently above the limits, so distribution has never earned its complexity for me.
Per-task profiles: split cost without losing simplicity
There's one case where I deliberately break the single list: when a feature mixes light work, like short classification or intent extraction, with heavy work, like long summaries or multi-step reasoning.
The trick is not to roll dice per request, but to give each task type its own ordered list. Inside a profile it's still a plain list, so incidents remain easy to read.
# llm/profiles.pyfrom dataclasses import dataclassfrom .gemini_adapter import GeminiAdapterfrom .claude_adapter import ClaudeAdapter@dataclass(frozen=True)class TaskProfile: name: str chain: listCHEAP_QA = TaskProfile("cheap_qa", [ GeminiAdapter(model="gemini-3.5-flash-lite"), # add its price to PRICING after checking the official page ClaudeAdapter(model="claude-haiku-4-5-20251001"),])DEEP_REASONING = TaskProfile("deep_reasoning", [ GeminiAdapter(model="gemini-3.8-flash", thinking_level="high"), ClaudeAdapter(model="claude-sonnet-4-6"),])# Callers pass a profile, not a model name# response = await router.complete_with_profile(CHEAP_QA, request)
The previous version claimed this cut the monthly bill by about 40%. I've removed that figure because the article couldn't show the period or conditions behind it. Whether you save money depends on how much of your traffic is light work. Counting cheap_qa against deep_reasoning in your logs for a week will tell you more than any number I could quote.
Logging: the columns that reveal outages and swaps
Redundancy without observation doesn't make operations any easier. These are the fields I always keep.
provider / requested_model / served_model: who answered, with what, and whether it matches what you asked for
position: where in the list the call succeeded (0 means the primary)
latency_ms: time to answer
input_tokens / output_tokens / cost_usd: cost tracking (blank when the price isn't registered)
Cost and model names only exist once the response is back, so the router writes them as a second line just before return. With both lines you can reconstruct when the primary's success rate dropped, how many calls moved to position 1 and when, and what that cost.
During an incident, the log should look roughly like this. Values are illustrative; the shape is the point.
Once the breaker opens, Gemini attempts disappear and only position=1 successes remain. When the single probe succeeds after 30 seconds, traffic returns to position=0. Users see errors only in the few requests before the breaker opens; most of them never notice anything. Not zero incidents — incidents you only see in the logs. That's the goal.
Diagnosing by symptom
These are the symptoms I've run into after go-live, with how to confirm and how to fix each.
Symptom
Likely cause
How to confirm
Fix
Responses take over a minute during incidents
No timeout set; SDK retries stacked on router failover
latency_ms on failures and attempts per request
HttpOptions timeout for Gemini; timeout and max_retries=0 for Claude
Only long inputs fail after failover
Smaller context on the fallback (Gemini 3.8 Flash: 1M tokens, Claude Haiku 4.5: 200K)
input_tokens on failures; reason=too_long skips
Check length in the router and skip providers that can't fit it
Bills or output length change after December 1
2.5 model IDs auto-routed, billed at destination rates
model_mismatch warnings; search code for gemini-2.5
Change the model ID explicitly and compare outputs
Breaker keeps flapping after recovery
HALF_OPEN letting every request through
breaker_open and failures alternating on a 30s cycle
Allow a single probe (the CircuitBreaker above)
JSON parsing fails only on the fallback
Preamble text or code fences in output
Count parse failures by provider
response_mime_type on Gemini; instruction plus safe parser elsewhere
Monthly drill gets 401 from the fallback
Unused key expired or permissions changed
config_error alert
Rotate the key and rerun the drill
For JSON, every provider's output passes through this before use.
import jsonimport redef safe_parse_json(text: str): try: return json.loads(text) except json.JSONDecodeError: fenced = re.search(r"```(?:json)?\s*(\{.*\}|\[.*\])\s*```", text, re.DOTALL) if fenced: return json.loads(fenced.group(1)) bare = re.search(r"\{.*\}|\[.*\]", text, re.DOTALL) if bare: return json.loads(bare.group(0)) raise
Three common misunderstandings
"Set temperature to 0 and every provider gives the same answer." The Gemini API's seed is documented as improving reproducibility, not guaranteeing identical output — and across providers, all bets are off. Aim for the same format after failover, not the same answer, and enforce the format with validation.
"OpenAI's max_tokens caps input plus output." The old version of this article said that, and it was wrong. In Chat Completions, max_tokens limits generated tokens; it has been superseded by max_completion_tokens, which also counts reasoning tokens, and reasoning models reject max_tokens outright. If you add OpenAI as a third provider, absorb that naming difference inside its adapter.
"2.5 IDs keep working after December 1, so I can leave them." They will answer, but a different model will be doing the answering, at a different price. The changes that don't break anything are the ones you have to go looking for.
Keeping the fallback path alive
The hardest part of redundancy is keeping a path you almost never use in working order. I keep two guards on it.
A monthly synthetic drill. Production has a flag that forces the primary to fail; a fixed prompt runs through it, and an automated check confirms the answer came back at position=1. If not, I get paged. Expired keys and adapters broken by SDK upgrades have surfaced this way, before a real outage could find them for me.
Unit tests. An always-failing adapter goes first, and the tests confirm both that timeouts fall through and that a bad request does not.
They're small tests, but they've caught router refactors that quietly broke failover more than once.
Where you'll likely get stuck next
Right after adding failover, the surprise is usually that calls moved to the fallback consume that provider's limits too. I've written up how Gemini's limits and tiers behave in my notes on Gemini API rate limits and 429s.
If you do one thing today, search your code for gemini-2.5 and add a line that logs served_model next to each call you find. The rest of the redundancy can be built once you can see, side by side, the model you asked for and the model that answered. That one column changed how I read my own logs.
Share
Thank You for Reading
Gemini Lab is ad-free, supported entirely by members like you. We publish practical guides daily with implementation code, benchmarks, and production-ready patterns. If you've found it useful, we'd love to have you on board.