A Fallback LLM Is Just Another Adapter: Wrap Two Providers, Test Failover With Fakes A developer outlined a design for LLM provider failover that places the logic in an adapter implementing the same port as the real providers, so feature code never handles outages directly. The approach defines two exceptions — ProviderUnavailable for timeouts, connection errors, 5xx and 429 responses, and RequestRejected for malformed requests — and maps each SDK's error hierarchy onto them, with a single OpenAI-compatible adapter serving both OpenAI and DeepSeek. The design was motivated by DeepSeek's roughly five-hour API outage on October 15, which took down its web platform, app and both V4.1 APIs. DeepSeek's API had an outage of almost five hours on October 15. By the company's own notice, it could not operate normally from 8:11 a.m. to 1:04 p.m. Beijing time https://magica.com/news/deepseek-api-credits-october-15-outage , and Yicai's report https://www.yicaiglobal.com/news/deepseek-suffers-nearly-five-hour-ai-service-outage-one-of-its-worst-this-year lists the web platform, the app and both V4.1 APIs as hit. If DeepSeek was the only model your product called, every feature that touched it was down for those five hours too. The usual fix is a second provider. The usual mistake is where the fix goes. You add a try/except in the summarize use case, then another in the classify use case, then a third one in the agent loop, each catching a slightly different set of SDK exceptions. Six months later every feature is also an outage handler, and nobody can say which errors trigger the switch. There is a smaller design. Failover belongs to how you reach a model, and your feature shouldn't have to know about it. So it lives in an adapter that implements the same port as the real providers, and the core never learns that two vendors exist. Start with what the application needs from a model, in its own words. No SDK types, no vendor names: python app/ports.py from dataclasses import dataclass from typing import Protocol @dataclass frozen=True class Completion: text: str provider: str fallback reason: str | None = None class ProviderUnavailable Exception : """Timeout, connection error, 5xx or 429.""" class RequestRejected Exception : """The provider says the request itself is wrong.""" class LLM Protocol : async def complete self, prompt: str - Completion: ... Two exceptions carry the whole failover policy. ProviderUnavailable means "this vendor can't serve you right now, another one might." RequestRejected means "this request is broken, and sending it somewhere else will not fix it." A malformed payload, an oversized prompt or a bad parameter fails on the second provider for the same reason it failed on the first, so failing over on a 400 adds a second round trip and still ends in an error. Completion.provider is the record of who answered. You will want it in logs and metrics the first time a user says the answers "felt different this afternoon." A use case depends on the port and nothing else: python app/summarize.py from app.ports import LLM, Completion class SummarizeTicket: def init self, llm: LLM - None: self. llm = llm async def call self, ticket: str - Completion: return await self. llm.complete f"Summarize this support ticket:\n{ticket}" No try , no vendor import. That stays true after you add the second provider. One port, two adapters behind it. The core only ever sees the socket. Each provider adapter does two jobs: make the call, and map the SDK's exception hierarchy onto the two exceptions above. That mapping is the part worth reading twice, because it is where the policy lives. The OpenAI Python SDK README https://github.com/openai/openai-python/blob/main/README.md maps 429 to RateLimitError , every status at or above 500 to InternalServerError , and network failures to APIConnectionError . Its timeout error, APITimeoutError , subclasses APIConnectionError https://github.com/openai/openai-python/blob/main/src/openai/ exceptions.py , so one entry covers both. Every other error response is an APIStatusError . DeepSeek speaks the OpenAI format https://api-docs.deepseek.com/ at https://api.deepseek.com , so one adapter serves both vendors, which is why it takes a name : python adapters/openai compat.py import openai from openai import AsyncOpenAI from app.ports import Completion, ProviderUnavailable, RequestRejected, TRANSIENT = openai.APIConnectionError, includes timeouts openai.RateLimitError, openai.InternalServerError, class OpenAICompatLLM: def init self, client: AsyncOpenAI, model: str, name: str - None: self. client = client self. model = model self.name = name async def complete self, prompt: str - Completion: try: resp = await self. client.chat.completions.create model=self. model, messages= {"role": "user", "content": prompt} , except TRANSIENT as exc: raise ProviderUnavailable str exc from exc except openai.APIStatusError as exc: raise RequestRejected str exc from exc text = resp.choices 0 .message.content or "" return Completion text, self.name Order matters in those except clauses. RateLimitError and InternalServerError are subclasses of APIStatusError , so the transient tuple has to come first or every 429 would be filed as a rejected request. The Anthropic adapter has the same shape. The Claude API error reference https://platform.claude.com/docs/en/api/errors lists RateLimitError for 429 and InternalServerError for every 5xx, including 504 and 529 overloaded error , which it describes as the API being "temporarily overloaded": python adapters/anthropic llm.py import anthropic from anthropic import AsyncAnthropic from app.ports import Completion, ProviderUnavailable, RequestRejected, TRANSIENT = anthropic.APIConnectionError, includes timeouts anthropic.RateLimitError, anthropic.InternalServerError, 500, 504, 529 class AnthropicLLM: name = "anthropic" def init self, client: AsyncAnthropic, model: str - None: self. client = client self. model = model async def complete self, prompt: str - Completion: try: msg = await self. client.messages.create model=self. model, max tokens=1024, messages= {"role": "user", "content": prompt} , except TRANSIENT as exc: raise ProviderUnavailable str exc from exc except anthropic.APIStatusError as exc: raise RequestRejected str exc from exc text = "".join b.text for b in msg.content if b.type == "text" return Completion text, self.name Notice that 401 and 403 land in RequestRejected . That is a choice, and you can make the other one. A revoked key on the primary is something a human should hear about today, and falling back quietly hides it until the secondary's invoice arrives. If you would rather stay up, move AuthenticationError into the transient tuple and alert on fallback reason . The 400 rule has one documented wrinkle. Anthropic says the API also returns a 400 when usage reaches a spend limit you set https://platform.claude.com/docs/en/api/errors , and a 429 can mean a tier spend cap that "keeps failing until access resumes." The 429 case is exactly when a second vendor helps, and the mapping above already sends it there. The spend-limit 400 is yours to decide; check the error details before you widen the rule for every 400. Now the adapter that does the switching. It implements LLM , holds two LLM s, and catches exactly one exception type: python app/fallback.py from dataclasses import replace from app.ports import LLM, Completion, ProviderUnavailable class FallbackLLM: def init self, primary: LLM, secondary: LLM - None: self. primary = primary self. secondary = secondary async def complete self, prompt: str - Completion: try: return await self. primary.complete prompt except ProviderUnavailable as first: answer = await self. secondary.complete prompt return replace answer, fallback reason=str first Three things fall out of those few lines. A RequestRejected from the primary passes straight through, so the secondary is never called for a broken request. A successful fallback returns the secondary's Completion with the primary's failure attached, so a log line shows both who answered and why the first choice didn't. And if the secondary also fails, its exception leaves the except block with the primary's error attached as context by Python's normal exception chaining, so the traceback shows both outages. It also composes. FallbackLLM primary, FallbackLLM secondary, tertiary is a three-provider chain with no new code. Fail over on "can't serve you now." Never on "your request is wrong." Because the core only knows the port, the tests never touch an SDK, a network or an API key. Two fakes are enough: one that answers and one that raises whatever you hand it. python tests/test fallback.py import asyncio import pytest from app.fallback import FallbackLLM from app.ports import Completion, ProviderUnavailable, RequestRejected, class AnsweringLLM: def init self, name: str - None: self.name = name self.calls: list str = async def complete self, prompt: str - Completion: self.calls.append prompt return Completion f"{self.name} says ok", self.name class FailingLLM: def init self, error: Exception - None: self.error = error self.calls: list str = async def complete self, prompt: str - Completion: self.calls.append prompt raise self.error One fake answers and records the prompt. The other records the prompt and raises whatever error you hand it. The four tests go in the same file: python def test healthy primary never calls secondary : secondary = AnsweringLLM "secondary" llm = FallbackLLM AnsweringLLM "primary" , secondary answer = asyncio.run llm.complete "hi" assert answer.provider == "primary" assert answer.fallback reason is None assert secondary.calls == def test unavailable primary falls back : primary = FailingLLM ProviderUnavailable "429" llm = FallbackLLM primary, AnsweringLLM "secondary" answer = asyncio.run llm.complete "hi" assert answer.provider == "secondary" assert answer.fallback reason == "429" def test rejected request never falls back : secondary = AnsweringLLM "secondary" primary = FailingLLM RequestRejected "400" llm = FallbackLLM primary, secondary with pytest.raises RequestRejected : asyncio.run llm.complete "hi" assert secondary.calls == def test both down keeps both errors : first = ProviderUnavailable "primary timeout" second = ProviderUnavailable "secondary 503" llm = FallbackLLM FailingLLM first , FailingLLM second with pytest.raises ProviderUnavailable as info: asyncio.run llm.complete "hi" assert info.value is second assert info.value. context is first Four tests, four branches: healthy primary, failover, no failover on a bad request, both providers down. The calls lists are what make the "never" tests honest. Asserting that the secondary was never called is the whole point of the 400 rule, and a fake that records its calls is the cheapest way to prove it. The tests use asyncio.run so they need no async plugin. To import app from tests/ , put the project root on pytest's path with the pythonpath option https://docs.pytest.org/en/stable/reference/reference.html : pytest.ini pytest pythonpath = . The adapters' error mapping deserves its own small tests against the real exception classes, but that is a separate, narrower job. FallbackLLM doesn't care how a vendor spells "overloaded." The composition root is the only file that knows which vendor is primary: python main.py import os from anthropic import AsyncAnthropic from openai import AsyncOpenAI from adapters.anthropic llm import AnthropicLLM from adapters.openai compat import OpenAICompatLLM from app.fallback import FallbackLLM from app.summarize import SummarizeTicket def build summarizer - SummarizeTicket: deepseek = OpenAICompatLLM AsyncOpenAI base url="https://api.deepseek.com", api key=os.environ "DEEPSEEK API KEY" , max retries=1, timeout=30.0, , model=os.environ "PRIMARY MODEL" , name="deepseek", claude = AnthropicLLM AsyncAnthropic max retries=1, timeout=30.0 , model=os.environ "SECONDARY MODEL" , return SummarizeTicket FallbackLLM deepseek, claude The max retries and timeout arguments are not decoration. Both SDKs already retry on their own: the OpenAI SDK retries connection errors, 408, 409, 429 and 5xx twice by default https://github.com/openai/openai-python/blob/main/README.md , and the Anthropic SDK does the same https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/python , with a default timeout of 10 minutes per request on both. Leave the defaults on the primary and a hung provider can hold a request for three long attempts before FallbackLLM ever sees an error. Pick a timeout that matches your feature's latency budget, keep one retry for blips, and let the fallback handle the rest. Swapping primary and secondary is now a one-line change in this file. Switching the secondary to a third vendor means writing one adapter and its mapping tests. No use case changes in either case. A second provider is a different model. Prompts tuned on one can behave differently on the other, structured-output quirks differ, and so do prices. Run your evals against both adapters, not just the primary, or the fallback path is a feature you have never tested with real outputs. The fake-based tests above prove the routing; they say nothing about answer quality. It also sends your prompts to another company. If your contracts or data-residency rules name one vendor, the secondary is a legal decision before it is a code decision. And during a long outage, every request still pays the primary's timeout before it falls back. If you expect five-hour outages like October's, add a circuit breaker that skips the primary for a while after repeated ProviderUnavailable errors. FallbackLLM is the natural home for it, behind the same port, and the same two fakes can drive its tests. The move in this post is the one I keep coming back to in Hexagonal Architecture in Python https://www.amazon.com/dp/B0HQWDH23Q : decide what the core needs, name it as a port, and push everything vendor-shaped into adapters you can swap and fake. The book isn't about LLMs. It builds one async FastAPI and SQLAlchemy 2 service five ways Hexagonal, Clean, Onion, layered and vertical slice and measures what each costs you. That same boundary is what kept FallbackLLM to a dozen lines instead of a try/except in every feature. Every listing runs from the free companion repo https://github.com/gabrielanhaia/hexagonal-python-examples .