{"slug": "a-fallback-llm-is-just-another-adapter-wrap-two-providers-test-failover-with", "title": "A Fallback LLM Is Just Another Adapter: Wrap Two Providers, Test Failover With Fakes", "summary": "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.", "body_md": "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.\n\nThe 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.\n\nThere 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.\n\nStart with what the application needs from a model, in its own words. No SDK types, no vendor names:\n\n``` python\n# app/ports.py\nfrom dataclasses import dataclass\nfrom typing import Protocol\n\n@dataclass(frozen=True)\nclass Completion:\n    text: str\n    provider: str\n    fallback_reason: str | None = None\n\nclass ProviderUnavailable(Exception):\n    \"\"\"Timeout, connection error, 5xx or 429.\"\"\"\n\nclass RequestRejected(Exception):\n    \"\"\"The provider says the request itself is wrong.\"\"\"\n\nclass LLM(Protocol):\n    async def complete(self, prompt: str) -> Completion: ...\n```\n\nTwo 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.\n\n`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.\"\n\nA use case depends on the port and nothing else:\n\n``` python\n# app/summarize.py\nfrom app.ports import LLM, Completion\n\nclass SummarizeTicket:\n    def __init__(self, llm: LLM) -> None:\n        self._llm = llm\n\n    async def __call__(self, ticket: str) -> Completion:\n        return await self._llm.complete(\n            f\"Summarize this support ticket:\\n{ticket}\"\n        )\n```\n\nNo `try`, no vendor import. That stays true after you add the second provider.\n\n*One port, two adapters behind it. The core only ever sees the socket.*\n\nEach 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.\n\nThe [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`:\n\n``` python\n# adapters/openai_compat.py\nimport openai\nfrom openai import AsyncOpenAI\n\nfrom app.ports import (\n    Completion,\n    ProviderUnavailable,\n    RequestRejected,\n)\n\nTRANSIENT = (\n    openai.APIConnectionError,  # includes timeouts\n    openai.RateLimitError,\n    openai.InternalServerError,\n)\n\nclass OpenAICompatLLM:\n    def __init__(\n        self, client: AsyncOpenAI, model: str, name: str\n    ) -> None:\n        self._client = client\n        self._model = model\n        self.name = name\n\n    async def complete(self, prompt: str) -> Completion:\n        try:\n            resp = await self._client.chat.completions.create(\n                model=self._model,\n                messages=[{\"role\": \"user\", \"content\": prompt}],\n            )\n        except TRANSIENT as exc:\n            raise ProviderUnavailable(str(exc)) from exc\n        except openai.APIStatusError as exc:\n            raise RequestRejected(str(exc)) from exc\n        text = resp.choices[0].message.content or \"\"\n        return Completion(text, self.name)\n```\n\nOrder 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.\n\nThe 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\":\n\n``` python\n# adapters/anthropic_llm.py\nimport anthropic\nfrom anthropic import AsyncAnthropic\n\nfrom app.ports import (\n    Completion,\n    ProviderUnavailable,\n    RequestRejected,\n)\n\nTRANSIENT = (\n    anthropic.APIConnectionError,  # includes timeouts\n    anthropic.RateLimitError,\n    anthropic.InternalServerError,  # 500, 504, 529\n)\n\nclass AnthropicLLM:\n    name = \"anthropic\"\n\n    def __init__(self, client: AsyncAnthropic, model: str) -> None:\n        self._client = client\n        self._model = model\n\n    async def complete(self, prompt: str) -> Completion:\n        try:\n            msg = await self._client.messages.create(\n                model=self._model,\n                max_tokens=1024,\n                messages=[{\"role\": \"user\", \"content\": prompt}],\n            )\n        except TRANSIENT as exc:\n            raise ProviderUnavailable(str(exc)) from exc\n        except anthropic.APIStatusError as exc:\n            raise RequestRejected(str(exc)) from exc\n        text = \"\".join(\n            b.text for b in msg.content if b.type == \"text\"\n        )\n        return Completion(text, self.name)\n```\n\nNotice 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`.\n\nThe 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.\n\nNow the adapter that does the switching. It implements `LLM`, holds two `LLM` s, and catches exactly one exception type:\n\n``` python\n# app/fallback.py\nfrom dataclasses import replace\n\nfrom app.ports import LLM, Completion, ProviderUnavailable\n\nclass FallbackLLM:\n    def __init__(self, primary: LLM, secondary: LLM) -> None:\n        self._primary = primary\n        self._secondary = secondary\n\n    async def complete(self, prompt: str) -> Completion:\n        try:\n            return await self._primary.complete(prompt)\n        except ProviderUnavailable as first:\n            answer = await self._secondary.complete(prompt)\n            return replace(answer, fallback_reason=str(first))\n```\n\nThree 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.\n\nIt also composes. `FallbackLLM(primary, FallbackLLM(secondary, tertiary))` is a three-provider chain with no new code.\n\n*Fail over on \"can't serve you now.\" Never on \"your request is wrong.\"*\n\nBecause 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.\n\n``` python\n# tests/test_fallback.py\nimport asyncio\n\nimport pytest\n\nfrom app.fallback import FallbackLLM\nfrom app.ports import (\n    Completion,\n    ProviderUnavailable,\n    RequestRejected,\n)\n\nclass AnsweringLLM:\n    def __init__(self, name: str) -> None:\n        self.name = name\n        self.calls: list[str] = []\n\n    async def complete(self, prompt: str) -> Completion:\n        self.calls.append(prompt)\n        return Completion(f\"{self.name} says ok\", self.name)\n\nclass FailingLLM:\n    def __init__(self, error: Exception) -> None:\n        self.error = error\n        self.calls: list[str] = []\n\n    async def complete(self, prompt: str) -> Completion:\n        self.calls.append(prompt)\n        raise self.error\n```\n\nOne 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:\n\n``` python\ndef test_healthy_primary_never_calls_secondary():\n    secondary = AnsweringLLM(\"secondary\")\n    llm = FallbackLLM(AnsweringLLM(\"primary\"), secondary)\n\n    answer = asyncio.run(llm.complete(\"hi\"))\n\n    assert answer.provider == \"primary\"\n    assert answer.fallback_reason is None\n    assert secondary.calls == []\n\ndef test_unavailable_primary_falls_back():\n    primary = FailingLLM(ProviderUnavailable(\"429\"))\n    llm = FallbackLLM(primary, AnsweringLLM(\"secondary\"))\n\n    answer = asyncio.run(llm.complete(\"hi\"))\n\n    assert answer.provider == \"secondary\"\n    assert answer.fallback_reason == \"429\"\n\ndef test_rejected_request_never_falls_back():\n    secondary = AnsweringLLM(\"secondary\")\n    primary = FailingLLM(RequestRejected(\"400\"))\n    llm = FallbackLLM(primary, secondary)\n\n    with pytest.raises(RequestRejected):\n        asyncio.run(llm.complete(\"hi\"))\n    assert secondary.calls == []\n\ndef test_both_down_keeps_both_errors():\n    first = ProviderUnavailable(\"primary timeout\")\n    second = ProviderUnavailable(\"secondary 503\")\n    llm = FallbackLLM(FailingLLM(first), FailingLLM(second))\n\n    with pytest.raises(ProviderUnavailable) as info:\n        asyncio.run(llm.complete(\"hi\"))\n    assert info.value is second\n    assert info.value.__context__ is first\n```\n\nFour 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.\n\nThe 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):\n\n```\n# pytest.ini\n[pytest]\npythonpath = .\n```\n\nThe 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.\"\n\nThe composition root is the only file that knows which vendor is primary:\n\n``` python\n# main.py\nimport os\n\nfrom anthropic import AsyncAnthropic\nfrom openai import AsyncOpenAI\n\nfrom adapters.anthropic_llm import AnthropicLLM\nfrom adapters.openai_compat import OpenAICompatLLM\nfrom app.fallback import FallbackLLM\nfrom app.summarize import SummarizeTicket\n\ndef build_summarizer() -> SummarizeTicket:\n    deepseek = OpenAICompatLLM(\n        AsyncOpenAI(\n            base_url=\"https://api.deepseek.com\",\n            api_key=os.environ[\"DEEPSEEK_API_KEY\"],\n            max_retries=1,\n            timeout=30.0,\n        ),\n        model=os.environ[\"PRIMARY_MODEL\"],\n        name=\"deepseek\",\n    )\n    claude = AnthropicLLM(\n        AsyncAnthropic(max_retries=1, timeout=30.0),\n        model=os.environ[\"SECONDARY_MODEL\"],\n    )\n    return SummarizeTicket(FallbackLLM(deepseek, claude))\n```\n\nThe `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.\n\nSwapping 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.\n\nA 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.\n\nIt 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.\n\nAnd 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.\n\nThe 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).", "url": "https://wpnews.pro/news/a-fallback-llm-is-just-another-adapter-wrap-two-providers-test-failover-with", "canonical_source": "https://dev.to/gabrielanhaia/a-fallback-llm-is-just-another-adapter-wrap-two-providers-test-failover-with-fakes-3kck", "published_at": "2026-11-29 07:02:57+00:00", "updated_at": "2026-11-29 07:13:00.005136+00:00", "lang": "en", "topics": ["large-language-models", "ai-infrastructure", "mlops", "developer-tools"], "entities": ["DeepSeek", "OpenAI", "Yicai"], "also_reported_by": [], "takeaway": "Put failover in an adapter behind a shared LLM port and map SDK errors to two cases — ProviderUnavailable (timeouts, connection errors, 5xx, 429) and RequestRejected (400s) — so only transient failures trigger a switch to a second provider.", "recommendation": {"advice": "Map each provider SDK's exceptions to ProviderUnavailable and RequestRejected in the adapter, and fail over only on the former so malformed requests aren't retried against a second vendor.", "playbook": "production-ops", "playbook_url": "https://wpnews.pro/playbooks/production-ops"}, "alternates": {"html": "https://wpnews.pro/news/a-fallback-llm-is-just-another-adapter-wrap-two-providers-test-failover-with", "markdown": "https://wpnews.pro/news/a-fallback-llm-is-just-another-adapter-wrap-two-providers-test-failover-with.md", "text": "https://wpnews.pro/news/a-fallback-llm-is-just-another-adapter-wrap-two-providers-test-failover-with.txt", "jsonld": "https://wpnews.pro/news/a-fallback-llm-is-just-another-adapter-wrap-two-providers-test-failover-with.jsonld"}}