LLM API Failover: Circuit Breakers, Fallback Chains, Sessions

Blog / Developer tools

LLM API Failover: Circuit Breakers, Fallback Chains, Sessions

The basic recipe for LLM API failover: give each provider a three-state circuit breaker, and count only failures that truly belong to the provider (5xx, timeouts, connection errors) toward tripping it. Switch along a fallback chain you ranked in advance. Once a session or a stream has started, avoid changing providers mid-way. Add a quality-monitoring layer on top to catch the "returns 200 but the output got worse" case. The sections below cover each step, with a Python implementation you can adapt directly.

This article is only about reliability. If you want to split traffic by task to cut costs, that is a different problem; see how to build multi-model routing.

How risky is relying on a single provider?

Start with the public record. cdnping's API status page syncs the official status pages of several services every 15 minutes. The table below shows the incident counts synced for 2026-09-17 through 2026-10-17, with severity levels as labeled by each provider's own status page:

ServiceTotal incidentsOf which major / critical
OpenAI25major 4
Claude8major 6
Moonshot (Kimi)8critical 8
Groq3major 1
Cloudflare25major 3
Cursor25major 5
GitHub16critical 5, major 1

Every provider in the table had incidents during this one month. The counts are not directly comparable, because each provider logs "incidents" differently: some record even minor widget latency, others only record broad outages. Check each provider's severity definitions before reading the numbers. What we can say for sure is that several providers had problems in the same month, and if you depend on just one, your service goes down every time it does. For a month-by-month breakdown, see AI service incidents, September to October 2026.

Here is an example of duration. On 2026-10-15 at 16:29 (UTC), the OpenAI status page logged a major-severity "Widespread feature degradation" that lasted 146 minutes. Retries cannot ride out a degradation of more than two hours. You have to switch to another provider.

Which errors should count toward tripping the breaker, and which should not?

The most common circuit breaker mistake is treating every non-200 response as a provider failure. The result is often that your own request was malformed, or you simply used up your own quota, and the breaker kicks out a perfectly healthy provider.

ErrorCounts toward breakerHow to handle
400 bad parameters, request too longNoThe request itself is the problem; another provider would fail too. Return the error directly
401 / 403 auth failureNoAlert and check keys and permissions; you can take this provider offline manually
404 model not foundNoMisconfiguration or the model was retired; alert
429 rate limitGenerally noWait per Retry-After; if it persists, temporarily down-weight this provider without tripping the breaker
500 / 502 / 503 / 504YesCount one failure; you may retry on the next provider
529 overloadedYesSame as above
Connect timeout, TLS failure, first-token timeoutYesCount one failure
Content-safety refusalNoThis is a normal response; do not switch

For the exact meaning of each status code, see the LLM API error code cheat sheet. For waiting and down-weighting on 429, see what to do when the API returns 429. For retry intervals within a single provider, see how to write LLM API retries.

Public availability statistics often use a similar definition. For example, AGI Plan publishes availability as "successes / (successes + failures caused by the platform itself)", and counts only 5xx as platform failures (AGI Plan is a commercial partner of cdnping, and /en/status/agiplan mirrors that data). If breaker counting and external reporting use the same rules, your alert numbers and report numbers will match.

How do you implement a three-state circuit breaker?

There are three states:

  • Closed: traffic passes normally, and the failure rate over a recent period is tracked.
  • Open: entered after the failure rate exceeds the threshold. For the duration, no requests go to this provider; traffic goes straight to the fallback chain.
  • Half-open: after the cooldown expires, a small number of probe requests are let through. If they succeed, the breaker returns to closed; if they fail, it reopens and the cooldown doubles.

A sliding window is more stable for measuring the failure rate than "N consecutive failures". Under high concurrency, a consecutive-failure counter is easily reset by one or two successful requests.

import time, threading
from collections import deque

RETRYABLE = {500, 502, 503, 504, 529}

class CircuitBreaker:
    def __init__(self, name, window_s=60, min_calls=20, fail_ratio=0.5,
                 cooldown_s=30, max_cooldown_s=600, half_open_probes=3):
        self.name = name
        self.window_s, self.min_calls, self.fail_ratio = window_s, min_calls, fail_ratio
        self.base_cooldown, self.max_cooldown = cooldown_s, max_cooldown_s
        self.cooldown = cooldown_s
        self.half_open_probes = half_open_probes
        self.state, self.opened_at = "closed", 0.0
        self.calls = deque()          # (timestamp, ok)
        self.probes_in_flight = 0
        self.lock = threading.Lock()

    def release(self):
        """Give back a probe slot when a half-open probe is inconclusive (e.g. got a 429)"""
        with self.lock:
            if self.state == "half_open" and self.probes_in_flight > 0:
                self.probes_in_flight -= 1

    def _trim(self, now):
        while self.calls and now - self.calls[0][0] > self.window_s:
            self.calls.popleft()

    def allow(self):
        with self.lock:
            now = time.monotonic()
            if self.state == "open":
                if now - self.opened_at < self.cooldown:
                    return False
                self.state, self.probes_in_flight = "half_open", 0
            if self.state == "half_open":
                if self.probes_in_flight >= self.half_open_probes:
                    return False
                self.probes_in_flight += 1
            return True

    def record(self, ok):
        with self.lock:
            now = time.monotonic()
            if self.state == "half_open":
                if ok:
                    self.state, self.cooldown = "closed", self.base_cooldown
                    self.calls.clear()
                else:
                    self._open(now, backoff=True)
                return
            self.calls.append((now, ok))
            self._trim(now)
            n = len(self.calls)
            fails = sum(1 for _, s in self.calls if not s)
            if n >= self.min_calls and fails / n >= self.fail_ratio:
                self._open(now, backoff=False)

    def _open(self, now, backoff):
        if backoff:
            self.cooldown = min(self.cooldown * 2, self.max_cooldown)
        self.state, self.opened_at = "open", now
        self.calls.clear()


def classify(status=None, exc=None):
    """Returns 'provider_fail' / 'client_error' / 'rate_limited' / 'ok'"""
    if exc is not None:                      # timeout, connection reset, TLS error
        return "provider_fail"
    if status in RETRYABLE:
        return "provider_fail"
    if status == 429:
        return "rate_limited"
    if status and status >= 400:
        return "client_error"
    return "ok"


def call_with_failover(chain, breakers, send, request):
    """chain: provider names in the fallback chain; send(provider, request) -> (status, body)"""
    last_err = None
    for p in chain:
        br = breakers[p]
        if not br.allow():
            continue
        try:
            status, body = send(p, request)
            kind = classify(status=status)
        except Exception as e:
            kind, last_err = classify(exc=e), e
            status = body = None
        if kind == "ok":
            br.record(True)
            return p, body
        if kind == "client_error":
            br.record(True)          # the provider is fine; the request is the problem
            raise ValueError(f"{p} 返回 {status},换供应商也没用")
        if kind == "rate_limited":
            br.release()             # not a failure; give back the probe slot
            continue                 # try the next provider directly
        br.record(False)
        last_err = last_err or RuntimeError(f"{p} 返回 {status}")
    raise RuntimeError("备用链全部不可用") from last_err

The parameters in the code are just example starting values: a 60-second window, at least 20 requests before a verdict, open at a 50% failure rate, a 30-second starting cooldown, and a 10-minute maximum. A low-traffic service (a few requests per minute) will not reach min_calls. You can widen the window to 5 minutes or lower the threshold to 5 calls.

Why shouldn't breaker thresholds be too sensitive?

Look at some real request data. In AGI Plan's public hourly request statistics (fetched by cdnping on 2026-10-17, covering 19:00 on 10-15 through 18:00 on 10-17 Beijing time, 48 hourly buckets), most hours had failure counts from single digits to a few dozen. But the buckets for 14:00 and 15:00 on October 16 show 664 successes / 722 failures and 455 successes / 877 failures, a success rate of about 48% and 34%. The following hour returned to 921 successes / 107 failures.

Two things stand out in this data. First, the failures were concentrated in a few hours, so a rule like "more than half of requests fail within one window" catches them; you do not need to react to a stray 5xx or two. Second, recovery takes time: the hour after the outage still had a failure rate of around 10%. If the first successful half-open probe sent all traffic back at once, the breaker would likely be knocked straight back to open. So the half-open phase lets only a few probes through and doubles the cooldown on failure, which avoids flapping between open and closed.

How should you order the fallback chain?

A static fallback chain (fixed order) is easier to debug than "pick the fastest in real time", so start with a static chain. When ordering, consider these in turn:

  1. Is it capable enough? If the fallback model cannot do the task, switching only swaps one failure for another. First use your own eval set to confirm the fallback model's pass rate on this type of task.
  2. Are the failures independent? Two hosted endpoints for the same model often fail together if they run on the same company's infrastructure. Ideally the second fallback comes from a different company and a different cloud.
  3. Recent availability. /en/models lists the 30-minute and 1-day availability of the same model across OpenRouter's inference providers. In cdnping's 2026-10-17 snapshot, one popular open-source model had 36 provider endpoints; most had 100% 1-day availability, and the lowest few were at 88%-89%. That is a big spread for the same model behind different endpoints; for details see how much uptime differs when you switch OpenRouter providers for the same model.
  4. Latency from your network. API status at /en/status probes the official API endpoints from the Cloudflare edge every 5 minutes. In cdnping's 2026-10-17 snapshot, the 24-hour p95 across endpoints ranged from a few dozen milliseconds to over a thousand; the Kimi open platform endpoint had a probe success rate of 94.4% over the same window. These were measured from an edge node (DEN at the time), which is not what your server's location sees. Rely on probes from your own machines in the end.

Quantization also counts as "capability". The same model may run as fp8 or fp4 on different providers, and output quality can differ. Before switching, see inference providers and fp8 vs fp4 quantization.

If you would rather not maintain the integration and breaker logic for several providers yourself, you can use an aggregation gateway and move the switching to the gateway side. For example, AGI Plan schedules by capability group and is compatible with both the OpenAI and Anthropic API formats (AGI Plan is a commercial partner of cdnping, and AGI Plan states clearly that it is not an officially authorized channel). The cost is that the gateway itself becomes a single point of failure, so clients should still keep a direct fallback endpoint.

Can you switch providers in the middle of a session?

The rule is: new sessions may switch; sessions in progress should avoid it where possible.

Switching providers midway through a multi-turn conversation or agent task commonly causes these problems:

  • Tool-call formats and ID rules differ, so the tool_use records from earlier turns may fail to parse on the other provider;
  • The prompt cache is lost, so every later turn recomputes the long context at full price;
  • The model's style and judgment differ, so the agent's earlier and later plans do not line up.

The approach is to record which provider each session is "bound" to. When the bound provider's breaker opens, you have two choices. If the session is short, convert the full history into the target format and replay it on the new provider. If the session is very long or carries tool state, tell the user plainly that "the current session is temporarily unavailable" and have them start again. The latter looks blunt, but it is easier to debug than silently switching midway and getting wrong results.

If a stream breaks, should you switch to the next provider automatically?

The hard part of streaming is that once tokens have been sent to the user, you cannot take them back. Split it into two phases:

  1. Before commit: until the first valid content block arrives (or while you buffer the first few hundred milliseconds or first few dozen tokens), on error switch silently to the next provider in the chain, and the user will not notice. A first-token timeout belongs here too and counts as one failure.
  2. After commit: once output to the user has begun, do not automatically switch providers to continue after a mid-stream disconnect. Two models cannot pick up the same passage. Show "output interrupted" in the frontend and let the user retry manually, and record one failure against this provider.

One case to rule out first: a mid-stream disconnect is often not the provider's fault but your own Nginx, CDN, or load balancer cutting the long-lived connection. Such disconnects should not count toward the provider's breaker; track them separately. For how to diagnose them, see LLM streaming disconnects mid-output.

How do you detect a 200 response with degraded quality?

A breaker that looks only at status codes cannot see this: every request succeeds, but the output gets shorter, empty, or malformed. The cause may be that the provider changed the quantization, the backend routed to a different model, or a degraded service cut output short. To catch it, you have to monitor the output itself:

SignalHow to computeWhen to alert
Empty-response rateShare of responses where content is empty or only whitespaceClearly above the 7-day baseline
Truncation rateShare where finish_reason is lengthSame
Structured-output failure rateShare of JSON parse failures or tool arguments that violate the schemaSame
Output lengthMedian output tokens for the same class of taskA sudden drop
Canary questionsSend a few questions with fixed answers every 15 minutesConsecutive wrong answers

Record these metrics per provider. When one provider's metrics look abnormal, you can manually mark it as "down-weighted", which has the same effect as opening its breaker. If you suspect the provider is not serving the model you asked for, run a consistency check using the method in how to confirm which model an API is really giving you.

Which tasks can be degraded, and which cannot?

The last decision: when the primary model is unavailable, do you switch to a comparable model, fall back to a weaker one, or just return an error?

Task typeSwitch to same-tier modelDrop to a weaker tierWhen primary and fallback are both down
Code completion, classification, formattingYesYesDisable the feature and show a notice in the frontend
Everyday coding Q&A, code reviewYesYes, label it "degraded mode"Queue for later processing
Long-running agents, cross-file refactoringOnly when a new task startsNot recommended; likely to make wrong editsPause the task and save progress
Structured extraction (output consumed by programs)Yes, after schema validationYes; error out if validation failsMove to the retry queue
Long user-facing answersYesDepends on the business; tell the userReturn a clear error message
Batch offline jobsYesNot recommended; wait for the primary to recoverDefer execution

Pre-launch checklist

  • Error classification covers 4xx, 429, 5xx, 529, and timeouts, and client errors do not count toward the breaker
  • Each provider has its own breaker, and state changes are logged and alerted
  • The fallback chain has at least one provider from a different company and different infrastructure
  • The fallback model meets the pass-rate bar on your own eval set
  • Sessions record their bound provider and do not switch automatically midway
  • Streaming distinguishes "before commit" from "after commit", and a disconnect after commit does not auto-continue
  • Empty-response, truncation, and structured-output failure rates are recorded per provider
  • A quarterly drill: manually open the primary provider's breaker, confirm traffic moves away, and confirm it can switch back after recovery

During the drill, open /en/status and /en/down alongside, and compare the official status pages with the probe results to confirm that your breaker decisions agree with outside observations. cdnping's data collection began on 2026-10-17, so the history is still short. It works as a reference, but do not use it as a long-term statistic for setting thresholds; base thresholds on your own service's request logs.

Related articles

Keep reading