AiCredits
Reliability

LLM Fallback Strategies: Routing Between Providers for Maximum Uptime

Design LLM fallback that survives real incidents: classify failures, retry with jitter, add a breaker per route, and escalate tiers without doubling spend.

Published 2026-10-20 Updated 2026-10-20 9 min

Most teams discover their fallback plan on the day it matters, and most fallback plans turn out to be a single except block that retries the same endpoint three times. That is not a fallback strategy, it is a delay.

Uptime for an LLM feature is a routing property, not a model property. Every provider has good days and bad days; the job of the routing layer is to convert a provider's bad day into a slightly slower response instead of an error page. The design below assumes a cheap default tier, a stronger backup tier, and a second vendor only where it earns its complexity.

Classify failures before you route them

Your HTTP client sees one thing: an exception. Your routing layer needs to see six. Getting this taxonomy right is most of the work, because every class wants a different response — and treating them identically is how you end up in a retry storm against a route that was never going to answer.

  • Transport errors and timeouts — DNS failure, connection reset, read timeout. Retry once, then move to the next route. This is the class fallback was invented for.

  • 429 rate limits — back off with jitter. A different tier often succeeds immediately because capacity is provisioned separately.

  • 5xx from the provider — usually brief. One short retry, then fail over; don't let a retry budget turn a two-second blip into a thirty-second hang.

  • 4xx you caused — malformed body, bad key, context over the window. Never retry and never fail over; a different model will reject the same request. Shrink the prompt or fix the payload.

  • Semantic failures — HTTP 200, unusable content: invalid JSON, empty message, a refusal where you expected data. Invisible to your transport layer and, in practice, the most common production failure.

  • Quota and billing — looks like an auth error and will not heal on its own. Alert a human instead of burning your fallback budget on it.

Retry first — but only the failures that heal

Retries belong inside a route; fallback belongs between routes. Keeping them separate lets you reason about worst-case latency: with three attempts and a capped exponential backoff you know the ceiling, and escalation only begins after that ceiling is spent.

The helper below sets max_retries=0 on the SDK so there is exactly one retry policy in the system, classifies errors properly, and adds jitter so a fleet of workers doesn't synchronise into a thundering herd.

import os
import random
import time

from openai import (
    APIConnectionError,
    APIStatusError,
    APITimeoutError,
    OpenAI,
    RateLimitError,
)

client = OpenAI(
    api_key=os.environ["AICREDITS_API_KEY"],
    base_url="https://api.aicreditsapi.com/v1",
    timeout=30.0,
    max_retries=0,  # we own the retry loop so fallback order stays predictable
)


def complete(messages, model="deepseek-v4-flash", max_attempts=3, **kwargs):
    """Call one model, retrying only failures that can actually heal."""
    error = None
    for attempt in range(max_attempts):
        try:
            return client.chat.completions.create(
                model=model, messages=messages, **kwargs
            )
        except (RateLimitError, APITimeoutError, APIConnectionError) as exc:
            error = exc
        except APIStatusError as exc:
            if exc.status_code < 500:
                raise  # 400/401/422 will not fix themselves on a retry
            error = exc
        time.sleep(min(2 ** attempt + random.random(), 8.0))
    raise error


if __name__ == "__main__":
    reply = complete([{"role": "user", "content": "Reply with the single word: ok"}])
    print(reply.choices[0].message.content)

Keep the request body byte-identical across attempts. If the call has a side effect — writing a ticket, paging someone — deduplicate on an id you generate before the first attempt, because a timeout does not mean the server did nothing.

Build a two-tier ladder, with a breaker on every rung

A two-model ladder covers more than people expect. deepseek-v4-flash is the default: the fast, low-cost tier that should carry the overwhelming majority of traffic. deepseek-v4-pro is the escalation — stronger on genuinely hard prompts and worth paying more for, but not something you want silently handling every request. Because both tiers sit behind one OpenAI-compatible endpoint, changing rungs is a model-string change, not a second SDK.

The breaker is what stops the ladder from making things worse. Without it, a degraded route keeps absorbing traffic and every request pays the full retry budget before failing over. With it, that route is skipped entirely for a cooldown — set longer than a typical blip and shorter than your patience.

import time
from dataclasses import dataclass


@dataclass
class Breaker:
    threshold: int = 5
    cooldown: float = 30.0
    failures: int = 0
    opened_at: float | None = None  # Python 3.10+

    def allow(self) -> bool:
        if self.opened_at is None:
            return True
        return time.monotonic() - self.opened_at >= self.cooldown

    def record(self, ok: bool) -> None:
        if ok:
            self.failures, self.opened_at = 0, None
            return
        self.failures += 1
        if self.failures >= self.threshold and self.opened_at is None:
            self.opened_at = time.monotonic()


LADDER = ["deepseek-v4-flash", "deepseek-v4-pro"]  # cheap first, stronger second
breakers = {name: Breaker() for name in LADDER}


def answer(messages, **kwargs):
    skipped = []
    for model in LADDER:
        breaker = breakers[model]
        if not breaker.allow():
            skipped.append(model)
            continue
        try:
            result = complete(messages, model=model, **kwargs)
            breaker.record(True)
            return result, model
        except Exception:
            breaker.record(False)
    raise RuntimeError(f"all tiers unavailable or skipped: {skipped}")


if __name__ == "__main__":
    reply, served_by = answer(
        [{"role": "user", "content": "Summarize: retries are cheap, fallbacks are cheaper."}]
    )
    print(served_by)
    print(reply.choices[0].message.content)

Two caveats. Keep breakers per model, never global — pro being down tells you nothing about flash. And cap the ladder: escalate only on user-facing, latency-sensitive calls. Nightly batch jobs can simply wait, since pro costs more than flash, off-peak usage costs less than peak, and cached prompt prefixes are cheaper again. Current rates live at aicreditsapi.com/pricing.

Fall back on bad output, not just on errors

A 200 response with broken JSON is a failure your load balancer will never notice. For anything that feeds a schema — triage labels, lint findings, structured extraction — validate the parsed result and treat a miss as a routing signal rather than a parsing bug to patch downstream.

import json

REQUIRED_KEYS = {"severity", "summary"}


def triage(messages, **kwargs):
    for model in LADDER:
        resp = complete(
            messages,
            model=model,
            temperature=0,
            response_format={"type": "json_object"},
            **kwargs,
        )
        try:
            data = json.loads(resp.choices[0].message.content)
        except json.JSONDecodeError:
            continue  # this tier answered, but not usably
        if REQUIRED_KEYS <= data.keys():
            return data, model
    raise ValueError("no tier returned a schema-valid object")


if __name__ == "__main__":
    ticket = [
        {"role": "system", "content": "Return JSON with keys: severity, summary."},
        {"role": "user", "content": "Checkout fails for EU customers on Safari."},
    ]
    print(triage(ticket))

The ladder is reused rather than reinvented, and temperature=0 stops the retry from becoming a dice reroll on every tier. For code review and linting pipelines in particular, a clean "unavailable" beats a malformed finding that quietly enters a report someone ships from.

When a second vendor is actually worth it

Cross-vendor routing is the expensive half of this problem: two SDKs, two key rotations, two error taxonomies, and prompts that drift after the port. It pays for itself when a single vendor's bad day costs you revenue — not before. Compare on what bites at 3am, not on leaderboard scores.

RouteWhere it winsWhere it bites
AiCredits (DeepSeek tiers)One OpenAI-compatible endpoint, two tiers for a clean primary/escalation ladder, billed by card or PayPal for developers outside ChinaDeepSeek-only, so it is a tier fallback rather than a cross-vendor one
OpenRouterMany vendors behind one key; genuinely useful model shopping and real cross-vendor failoverExtra hop in the path, routing rules you don't control, model slugs that shift under you
Direct from a second vendorStrongest isolation and the cleanest blast-radius storyMost work: separate billing, separate quirks, prompt behaviour changes across families
Self-hosted / localFull control and data localityYou now own the uptime problem and provision the capacity for it

OpenRouter earns its place if you are still shopping: one key, many vendors, and failover you don't have to build. The trade is a hop you don't manage and a catalogue that moves — pin what you use and re-test when it changes.

AiCredits is the narrower bet: DeepSeek tiers on an OpenAI-compatible endpoint, sold to developers outside China with a card or PayPal, no Chinese phone number or bank account needed. If DeepSeek is your primary, that removes the most embarrassing failure mode of all — being unable to top up the backup route because of a payment wall. If you truly need a different model family as your second vendor, keep the abstraction and point one rung at it.

Going direct to a second vendor gives the strongest insulation and the most maintenance. It is right for teams already running multi-region infrastructure; everyone else should exhaust the tier ladder first.

Hedge latency, don't blanket-duplicate

Hedging — firing the same request at two routes and taking the first usable answer — addresses tail latency, not outages, and it doubles spend on every hedged call. Use it surgically: trigger only after a threshold that slow requests cross, send the hedge to the cheaper tier, and cancel the loser so you aren't paying for tokens nobody reads. Never hedge writes, and never hedge mid-stream: once tokens are on the wire you cannot quietly swap models, so either buffer short responses or accept that streams only get pre-first-token fallback.

A fallback path you have never exercised is a rumour, not a plan.

The uptime checklist

  • One retry policy in the codebase — disable the SDK's built-in retries or you will multiply them.

  • Per-route breakers with a cooldown longer than a blip, plus a half-open probe before full traffic returns.

  • Log the model that answered, not the model you asked for. Fallback rate is the metric that predicts your next incident.

  • Alert separately on self-inflicted 4xx: a spike there is usually a prompt change, not an outage.

  • Exercise the ladder monthly with a flag that starts at the second rung, so the path is never cold.

  • Serve something on total failure — a cached answer with a timestamp beats a stack trace.

FAQ

Should I fall back to a cheaper model or a stronger one?

Stronger, usually. The fallback exists because the primary could not answer, and dropping to a weaker tier on top of a degraded system tends to produce worse output exactly when users are least forgiving. Keep deepseek-v4-flash as the default and deepseek-v4-pro as the escalation.

How many routes do I actually need?

Two tiers plus a cached degraded response covers most products. A third route only pays for itself when a single vendor outage would breach a commitment you have made to customers.

Do retries eat into my fallback budget?

They consume the same latency budget, so cap attempts per route rather than per request. Three attempts with capped exponential backoff plus one escalation is roughly the ceiling users tolerate on an interactive screen.

How do I test fallback without waiting for an outage?

Force it. Add an environment flag that starts the ladder at the second rung, and run it in staging on every deploy. A path that is only exercised during incidents will fail during incidents.

Does streaming break fallback?

Before the first token, no — swap freely. After it, yes: partial output cannot be retracted. Buffer short responses so you can restart cleanly, or accept degraded behaviour for long streams.

Try Lint in 2 seconds

Wrote something? Paste it here for a free grammar check. No account needed.

More Tools →

Related Tools

Was this article helpful?

| Share on X Reddit Copy link

服务器宕机了?别等用户告诉你

Wakeless 梦哨 帮你 30 秒监控网站 / API / SSL 证书,宕机秒级告警到邮箱、飞书、Slack。免费档 30 个监控,永久免费,无需信用卡。

免费开始监控 →
💬
反馈意见 / Feedback ×