The Outage You Didn't Plan For
At 11:47pm on a Thursday, your primary LLM provider started returning overload errors (a 529 from Anthropic, a 503 from most others). Not all requests - about 30%. Enough to degrade your system visibly. Not enough to trigger your simple error rate alert.
By midnight, it was 60%. Your application was timing out on every other request. Support tickets were filing. Your on-call engineer was staring at a graph that looked like a saw blade.
At 12:23am the provider posted an incident report. Estimated resolution: 2-4 hours.
Your system had three options: wait for the provider to recover, fail entirely, or fall back to something that kept working. You'd built options one and two. Option three didn't exist.
grid-rows: 1
grid-gap: 14
classes: {
grey: {style: {fill: "#F3F4F6"; stroke: "#D1D5DB"; font-color: "#2C2C2A"}}
red: {style: {fill: "#FB923C"; stroke: "#EA580C"; font-color: "#2C2C2A"}}
green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
}
wait: "1. Wait\nusers stare at spinners\nfor 2-4 hours" {class: grey}
fail: "2. Fail entirely\nevery request errors" {class: red}
fall: "3. Fall back\nkeep serving, degraded\n(not built)" {class: green; style.stroke-dash: 4}
The dashed box is the option nobody had built. The first two are what happens by default, and only the third has to be designed.
This is the failure mode the Graceful Degradation layer exists to prevent. Not model errors - infrastructure failures. The LLM endpoint going slow, rate-limited, or offline entirely. And since you treat the LLM as the application rather than a dependency, you have no fallback when it fails.
This is Part 6 of the Harness Engineering series. Part 1 introduced the seven-layer Harness Architecture. This article covers Layer 6 - Graceful Degradation - including retry strategies, fallback model selection, and circuit breaker patterns for LLM infrastructure.
This series grew into a book: Harness Engineering for Production AI Systems. Chapter 8, "Retry, Fallback, Circuit Breaking," covers this layer.
17 November 2026: rewrote the circuit breaker, whose earlier version deadlocked on its own lock and could never leave the open state. Also: the retry layer now accounts for the SDK's built-in retries, never re-sends a timed-out non-idempotent call, and treats quota 429s as final. A breaker no longer counts our own 400s as outages. Added streaming timeouts, gateways and middleware, and the authority and budget a fallback model inherits. Every section now has its own diagram.
The LLM Is an External Dependency
This reframe matters more than any specific pattern.
Your LLM provider is an external service. It has SLAs it may not meet. It has rate limits. It has incident history. It behaves exactly like any other third-party API in your infrastructure - except most teams treat it as if it were local function call.
Every pattern that distributed systems engineers use for external service reliability applies to LLMs:
- Retry with backoff for transient failures
- Circuit breakers to stop hammering degraded endpoints
- Fallback paths for when the primary is unavailable
- Timeouts to prevent cascading latency
- Bulkheads to isolate LLM failures from the rest of the system
None of this is novel. It's all standard distributed systems practice. The novelty is applying it to an LLM - which most teams don't, because they built the LLM call as if it were a reliable internal function.
Treat your LLM like you treat your payment processor. It will fail. Design for it.
direction: down
classes: {
blue: {style: {fill: "#38BDF8"; stroke: "#0EA5E9"; font-color: "#2C2C2A"}}
violet: {style: {fill: "#6F00FF"; stroke: "#5500CC"; font-color: "#FFFFFF"}}
yellow: {style: {fill: "#FACC15"; stroke: "#CA8A04"; font-color: "#2C2C2A"}}
}
app: "Your application" {class: blue}
stack: "" {
grid-rows: 1
grid-gap: 10
t: "Timeouts" {class: violet}
r: "Retry +\nbackoff" {class: violet}
b: "Circuit\nbreaker" {class: violet}
f: "Fallback" {class: violet}
k: "Bulkhead" {class: violet}
}
llm: "LLM provider: an external dependency" {class: yellow}
app -> stack
stack -> llm
The violet row is standard distributed-systems equipment. None of it is specific to LLMs, and that is the point: the provider sits in the same position as any other third-party API.
I call the deliberate allocation of reliability work across these patterns Failure Budget Allocation: your system has a maximum tolerable error rate, and each resilience layer absorbs a portion of that budget. Retry absorbs transient noise. The circuit breaker absorbs degraded endpoints. The fallback absorbs extended outages. If any layer is missing, the failures it should have absorbed become user-facing incidents.
The Three Failure Modes of LLM Infrastructure
Failure Mode 1: Transient Errors
Rate limit hits. Temporary 503s. Network timeouts. Connection resets. These are brief, recoverable, and common. They affect individual requests, not the entire endpoint.
The right response is retry with exponential backoff. Wait, try again, wait longer, try again. Most transient failures resolve within seconds.
What teams get wrong: retrying immediately and repeatedly, which hammers an already-stressed endpoint and worsens the problem. Or not retrying at all, which turns a transient 1-second failure into a user-facing error.
grid-rows: 1
grid-gap: 10
classes: {
red: {style: {fill: "#FB923C"; stroke: "#EA580C"; font-color: "#2C2C2A"}}
grey: {style: {fill: "#F3F4F6"; stroke: "#D1D5DB"; font-color: "#2C2C2A"}}
green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
}
a1: "Attempt 1\n429" {class: red}
w1: "wait ~1s\n(jittered)" {class: grey}
a2: "Attempt 2\n503" {class: red}
w2: "wait ~2s\n(jittered)" {class: grey}
a3: "Attempt 3\nsuccess" {class: green}
a1 -> w1 -> a2 -> w2 -> a3
The grey boxes do the work. Each wait is longer than the last and randomized, so a thousand clients that failed together don't all come back at the same instant.
Failure Mode 2: Degraded Performance
The endpoint is responding but slowly. P50 latency goes from 800ms to 8 seconds. Some requests succeed, some time out. This is the hardest failure mode to detect and respond to.
The right response is timeout enforcement plus fallback. Set hard timeouts on LLM calls. When the timeout rate exceeds a threshold, treat it as a degraded endpoint and route to a fallback.
What teams get wrong: no timeouts on LLM calls (requests hang indefinitely), no threshold monitoring (don't know it's degraded until users complain), no fallback (when they detect it, there's nowhere to go).
direction: down
classes: {
yellow: {style: {fill: "#FACC15"; stroke: "#CA8A04"; font-color: "#2C2C2A"}}
violet: {style: {fill: "#6F00FF"; stroke: "#5500CC"; font-color: "#FFFFFF"}}
green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
}
slow: "Endpoint answers, slowly\nP50 800ms -> 8s" {class: yellow}
timeout: "Timeouts fire on the slow tail" {class: violet}
rate: "Timeout rate crosses a threshold" {class: violet}
route: "Treat as degraded: route to fallback" {class: green}
slow -> timeout -> rate -> route
Nothing in this chain is an error code. Degradation only becomes visible if timeouts turn slowness into a signal you count.
Failure Mode 3: Extended Outage
The endpoint is down or unresponsive for minutes to hours. This is rare but happens. Provider incidents, maintenance windows, regional outages.
The right response is a circuit breaker that stops attempting the failed endpoint, routes all traffic to a fallback, and periodically probes for recovery.
What teams get wrong: no circuit breaker (keep hammering the dead endpoint until it recovers), no fallback (system is fully down for the duration), no recovery detection (don't know when it's safe to resume primary).
grid-rows: 1
grid-gap: 14
classes: {
red: {style: {fill: "#FB923C"; stroke: "#EA580C"; font-color: "#2C2C2A"}}
green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
}
without: "Without a breaker" {
label.near: top-center
grid-columns: 1
grid-gap: 8
a: "every request retries\nthe dead endpoint" {class: red}
b: "connection pools fill" {class: red}
c: "nobody knows when\nit recovered" {class: red}
}
with: "With a breaker" {
label.near: top-center
grid-columns: 1
grid-gap: 8
d: "requests skip the primary\nimmediately" {class: green}
e: "fallback serves traffic" {class: green}
f: "one probe checks\nfor recovery" {class: green}
}
The rows line up on purpose: each red box is the cost of a missing behaviour, and the green box beside it is what the breaker does instead.
Building the Retry Layer
Before writing a retry loop, check the one you already have. The official Anthropic and OpenAI Python SDKs both retry by default: twice, on connection errors, 408, 409, 429 and 5xx, with a short exponential backoff (Anthropic's documents that it honours retry-after). Wrap a default client in three retries of your own and a single request can become twelve attempts. Retry in exactly one layer. Either build the client with max_retries=0 and own the loop, as below, or keep the SDK's and don't add one.
Retry logic for LLM calls also has requirements that a generic HTTP retry gets wrong:
- Overload has its own code. Anthropic returns 529
overloaded_error, and a list that stops at 504 misses it. - Not every 429 is a rate limit. A usage-tier spend cap also comes back as 429, and it will keep failing however long you wait. Anthropic sends
retry-afteron rate limits but not on that cap. OpenAI returns quota and spend errors as 429s with their owncode, such ascredit_balance_exhaustedororganization_spend_limit_exceeded, and an error type that can beinsufficient_quota. - A timeout is not proof that nothing happened. The request may have reached the server and run. That's fine to retry for a completion, which has no side effects. For a tool call that writes, refunds or sends, it means doing it twice, unless the call carries an idempotency key persisted before the first attempt.
Here it is with the Anthropic SDK's exception classes, checked against anthropic 2.9.0:
import asyncioimport randomimport anthropic# Retry only what a retry can fix. 529 is Anthropic's "overloaded".RETRYABLE_STATUS = {408, 409, 429, 500, 502, 503, 504, 529}def retry_after_seconds(exc: anthropic.APIError) -> float | None: response = getattr(exc, "response", None) value = response.headers.get("retry-after") if response is not None else None try: return float(value) if value else None except ValueError: return Nonedef is_retryable(exc: anthropic.APIError, idempotent: bool) -> bool: if isinstance(exc, anthropic.APIConnectionError): # includes timeouts # The request may have reached the server and run return idempotent if isinstance(exc, anthropic.APIStatusError): if exc.status_code == 429 and retry_after_seconds(exc) is None: return False # likely a quota or spend cap: waiting won't help return exc.status_code in RETRYABLE_STATUS return Falseasync def llm_call_with_retry( call, # async () -> response *, idempotent: bool = True, # an LLM completion is; a tool write may not be max_retries: int = 3, base_delay: float = 1.0, max_delay: float = 60.0,): for attempt in range(max_retries + 1): try: return await call() except anthropic.APIError as e: if attempt == max_retries or not is_retryable(e, idempotent): raise backoff = random.uniform(0, min(base_delay * 2 ** attempt, max_delay)) await asyncio.sleep(max(backoff, retry_after_seconds(e) or 0.0))Use it with a client that doesn't retry on its own: client = anthropic.AsyncAnthropic(max_retries=0), then await llm_call_with_retry(lambda: client.messages.create(**request)). Run against errors built from the SDK's own classes, is_retryable answers:
529 retryable: True429 w/ retry-after: True429 no retry-after: False400: Falsetimeout idempotent: True non-idempotent: FalseThe missing retry-after is a heuristic for "this 429 is a cap, not a burst". It's the right default for Anthropic. For OpenAI, read the error's code (and type) instead. Every retry also costs money, so count attempts against the run's budget: a spend limit should reserve before the call, not reconcile afterwards.
direction: down
classes: {
yellow: {style: {fill: "#FACC15"; stroke: "#CA8A04"; font-color: "#2C2C2A"}}
violet: {style: {fill: "#6F00FF"; stroke: "#5500CC"; font-color: "#FFFFFF"}}
green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
red: {style: {fill: "#FB923C"; stroke: "#EA580C"; font-color: "#2C2C2A"}}
}
err: "An API error" {class: yellow}
q: "Retryable for this call?" {class: violet}
out: "" {
grid-rows: 1
grid-gap: 12
yes: "408, 409, 5xx, 529\n429 with retry-after\ntimeout on an idempotent call" {class: green}
no: "400, 401, 403, 404\n429 with no retry-after\ntimeout on a write" {class: red}
}
err -> q
q -> out
The red box includes two errors a status-code list would have retried: a quota 429 and a timed-out write. Both have the same problem: waiting and repeating can't fix them, and the timed-out write can make it worse.
Without retry: every transient 503 is a user-facing failure. A one-second blip becomes a broken request.
Without jitter: all clients retry simultaneously after a rate limit, causing a thundering herd that worsens the outage they're recovering from. The code above jitters every wait, and never waits less than the server asked.
Streaming needs its own timeouts. A single 30-second deadline kills long reasoning calls, and the SDKs default to ten minutes for a reason. For streamed responses, time two things instead: time to first token, and the idle gap between chunks. Errors can also arrive inside a stream that started with a 200, as an error event, so check for them. And don't retry a stream that has already delivered half its output as if nothing happened. Either resume it explicitly or tell the caller that the partial result is partial.
Building the Circuit Breaker
The circuit breaker pattern stops attempting a failing endpoint before you've exhausted all retries on every single request. It tracks the health of the endpoint globally and opens when the failure rate crosses a threshold.
An earlier version of the code below had three bugs, and they are worth naming because they are the easy ones to write. Its on_success took a lock and then called a method that took the same non-reentrant lock, so it deadlocked on first use. Its only transition from OPEN to HALF_OPEN ran when a result was recorded, and an open breaker sends no traffic and so records nothing: it could never close again. And its half-open state let every concurrent caller through, not one. This version fixes all three and uses a monotonic clock for intervals:
import threadingimport timefrom collections import dequefrom enum import Enumclass CircuitState(Enum): CLOSED = "closed" # normal operation OPEN = "open" # failing: reject immediately HALF_OPEN = "half_open" # one probe allowedclass CircuitBreaker: def __init__( self, failure_threshold: float = 0.5, # open at 50% failures... window_seconds: float = 60.0, # ...over a 60-second window min_requests: int = 10, # ...once there are enough samples recovery_timeout: float = 60.0, # seconds before a probe clock=time.monotonic, # monotonic: immune to clock changes ): self.failure_threshold = failure_threshold self.window = window_seconds self.min_requests = min_requests self.recovery_timeout = recovery_timeout self.clock = clock self.state = CircuitState.CLOSED self.requests: deque = deque() # (timestamp, success) self.opened_at = 0.0 self._probe_in_flight = False self._lock = threading.Lock() def allow_request(self) -> bool: with self._lock: now = self.clock() # The OPEN -> HALF_OPEN move happens here, because an open # breaker sends no traffic and so never records anything. if (self.state is CircuitState.OPEN and now - self.opened_at >= self.recovery_timeout): self.state = CircuitState.HALF_OPEN if self.state is CircuitState.CLOSED: return True if self.state is CircuitState.HALF_OPEN and not self._probe_in_flight: self._probe_in_flight = True # exactly one probe return True return False def on_success(self): with self._lock: if self.state is CircuitState.HALF_OPEN: self.state = CircuitState.CLOSED self.requests.clear() self._probe_in_flight = False else: self._record(True) def on_failure(self): with self._lock: if self.state is CircuitState.HALF_OPEN: self._open() else: self._record(False) def on_neutral(self): # A call that says nothing about provider health (e.g. a 400) with self._lock: self._probe_in_flight = False def _open(self): self.state = CircuitState.OPEN self.opened_at = self.clock() self._probe_in_flight = False def _record(self, success: bool): # caller holds the lock now = self.clock() self.requests.append((now, success)) while self.requests and self.requests[0][0] < now - self.window: self.requests.popleft() if len(self.requests) >= self.min_requests: failures = sum(1 for _, ok in self.requests if not ok) if failures / len(self.requests) >= self.failure_threshold: self._open()Driven with a fake clock (min_requests=4, recovery_timeout=30), it opens after four failures, admits exactly one caller once 30 seconds have passed, and closes when that probe succeeds:
after 4 failures: open allow: Falseafter 31s, first caller: True second caller: False half_openprobe succeeded: closed allow: TrueThe circuit breaker has three states:
Closed: normal operation. All requests go through. Failures are tracked.
Open: endpoint is failing. Requests are rejected immediately without attempting the LLM call. This is the key behavior - you stop paying retry costs on a dead endpoint and stop making your users wait for timeouts.
Half-open: recovery probe. One request is allowed through. If it succeeds, the circuit closes. If it fails, the circuit reopens and the recovery timeout resets.
direction: down
classes: {
green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
red: {style: {fill: "#FB923C"; stroke: "#EA580C"; font-color: "#2C2C2A"}}
yellow: {style: {fill: "#FACC15"; stroke: "#CA8A04"; font-color: "#2C2C2A"}}
}
closed: "CLOSED\nall requests pass" {class: green}
open: "OPEN\nreject immediately" {class: red}
half: "HALF_OPEN\none probe only" {class: yellow}
closed -> open: "failure rate >= threshold"
open -> half: "recovery timeout\n(checked in allow_request)"
half -> closed: "probe succeeds"
half -> open: "probe fails"
The edge from OPEN to HALF_OPEN is the one the earlier code had in the wrong place. It's driven by the clock at the moment a request asks to go through, because while the breaker is open there are no results to react to.
Without a circuit breaker: every request during an outage burns a full retry budget before failing. At scale, this means thousands of requests waiting 30 seconds each, consuming connection pools and cascading the failure to the rest of your system.
Building the Fallback Layer
A circuit breaker that rejects requests is better than hammering a dead endpoint. A fallback that serves degraded-but-functional responses is better than rejecting requests.
Fallback strategies in order of decreasing preference:
1. Secondary model provider. Route to a different model (or the same model via a different provider) when the primary is unavailable.
class AllProvidersUnavailable(Exception): passclass FallbackRouter: def __init__(self, primary, secondary, breaker: CircuitBreaker, adapt): self.primary = primary # async (request) -> response, with retries self.secondary = secondary # a different model or provider self.breaker = breaker self.adapt = adapt # rewrites the request for the secondary async def call(self, request: dict) -> dict: if self.breaker.allow_request(): try: result = await self.primary(request) except anthropic.APIError as e: if not is_retryable(e, idempotent=True): self.breaker.on_neutral() raise # a bad request is our bug, not an outage self.breaker.on_failure() else: self.breaker.on_success() return {"result": result, "provider": "primary"} try: result = await self.secondary(self.adapt(request)) except anthropic.APIError as e: raise AllProvidersUnavailable("primary and secondary both failed") from e return {"result": result, "provider": "secondary", "degraded": True}Two choices in that router matter more than the rest:
- A 400 is not an outage. The earlier version counted every exception as a provider failure, so a malformed request of ours could open the breaker and quietly move all traffic to the secondary. Here, an error a retry can't fix is re-raised and doesn't count, which is also why a remote agent that starts reporting its refusals as failures can open the breaker without a line of your code changing. In a test, a 400 left the breaker closed and a 529 sent the call to the secondary.
- The secondary gets an adapted request. Replaying the exact primary request on another model fails in ordinary ways. Models differ in which parameters they accept, such as prefill, thinking settings or forced tool choice, and a request that is valid on one returns a 400 on another.
adaptis where those differences live. Test every fallback with the request shape you send in production, not with a toy prompt.
2. Smaller/faster model on same provider. If the large tier of a model family is unavailable, fall back to the small tier of the same family. Lower quality, but functional - and often a different set of supported request parameters, so it goes through adapt too.
A fallback model has its own authority. "Lower quality" is not the only difference. A secondary model inherits whatever tools and permissions the primary had, but it never earned them: nobody evaluated it on your refund flow. And the requests it spends while it covers for the primary often go uncounted. Give the fallback path its own authority band, and its own budget line. The later part on fallback models inheriting authority they never earned works through what that looks like.
3. Cached responses. For common queries, serve cached responses from previous successful calls. Not appropriate for dynamic tasks, but acceptable for FAQ-style or classification tasks where recency doesn't matter.
4. Rule-based fallback. For classification and routing tasks, implement a deterministic fallback that uses keyword matching or simple heuristics. Much lower quality than the LLM, but infinitely better than a 503.
5. Graceful degradation message. The last resort. Tell the user the AI feature is temporarily unavailable and offer a manual path. Honest, recoverable, and far better than a spinner that never resolves.
grid-columns: 1
grid-gap: 8
classes: {
green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
teal: {style: {fill: "#4B0082"; stroke: "#3A0066"; font-color: "#FFFFFF"}}
yellow: {style: {fill: "#FACC15"; stroke: "#CA8A04"; font-color: "#2C2C2A"}}
orange: {style: {fill: "#F3F4F6"; stroke: "#D1D5DB"; font-color: "#2C2C2A"}}
red: {style: {fill: "#FB923C"; stroke: "#EA580C"; font-color: "#2C2C2A"}}
}
f1: "1. Secondary provider (own authority band)" {class: green}
f2: "2. Smaller model, same provider" {class: teal}
f3: "3. Cached response" {class: yellow}
f4: "4. Rule-based answer" {class: orange}
f5: "5. Degradation message" {class: red}
Each rung down trades quality for availability. The bottom rung always works, which is what makes the ladder safe to climb down.
The Named Pattern: Failure Budget Allocation
Inspired by the error budgets of Google's SRE practice, I call this Failure Budget Allocation for LLM infrastructure. An SRE error budget is the risk a service may spend on releases and change. This is a different use of the same idea: deciding which resilience layer is responsible for which part of the failures you can tolerate.
Your system has a reliability budget - a maximum tolerable error rate. Allocate that budget across your failure modes deliberately (the split below is illustrative, not measured):
Total error budget: 0.1% (99.9% availability target)├── Transient errors (absorbed by retry): 0.01%├── Degraded performance (absorbed by timeout + fallback): 0.05%└── Extended outage (absorbed by circuit breaker + fallback): 0.04%Each layer in the resilience stack absorbs a portion of the failure budget. Retry absorbs transient failures. The circuit breaker absorbs extended outages. The fallback absorbs what both miss.
If your fallback is unavailable, you have no failure budget for extended outages. This is the most common gap - teams build retry but not fallback, leaving extended outages as full-budget events.
The Full Resilience Pipeline
Retry, circuit breaker, and fallback don't operate independently - they form a layered decision flow on every LLM call. Here's how a request moves through all three:
grid-rows: 5
grid-columns: 2
vertical-gap: 40
horizontal-gap: 170
classes: {
blue: {style: {fill: "#38BDF8"; stroke: "#0EA5E9"; font-color: "#2C2C2A"}}
violet: {style: {fill: "#6F00FF"; stroke: "#5500CC"; font-color: "#FFFFFF"}}
yellow: {style: {fill: "#FACC15"; stroke: "#CA8A04"; font-color: "#2C2C2A"}}
green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
orange: {style: {fill: "#F3F4F6"; stroke: "#D1D5DB"; font-color: "#2C2C2A"}}
red: {style: {fill: "#FB923C"; stroke: "#EA580C"; font-color: "#2C2C2A"}}
}
req: "1. Request" {class: blue}
none: "" {style.opacity: 0}
gate: "2. breaker.allow_request()\nCLOSED, or the one HALF_OPEN probe" {class: violet}
fb: "Rejected: breaker OPEN,\nskip the primary" {class: orange}
call: "3. Primary call, retried in one layer\na 400 or auth error is re-raised" {class: yellow}
none1: "" {style.opacity: 0}
rec: "4. Record the outcome\non_success / on_failure" {class: green}
fbout: "Fallback ladder, adapted request:\nsecondary, cache, rules, message" {class: orange}
resp: "5. Response" {class: blue}
none2: "" {style.opacity: 0}
req -> gate
gate -> call: "allowed"
gate -> fb
fb -> fbout
call -> rec: "retries done"
rec -> resp: "success"
rec -> fbout: "retryable failure"
Four things this diagram makes explicit that prose alone undersells. First, the breaker check happens before the call: an open circuit never attempts the primary, so no retry budget is spent on a dead endpoint. Second, the breaker records one outcome per call, after the retries are used up, so one bad minute can't fill its window three times over. Third, a non-retryable error leaves the breaker alone, so our own bugs can't open it. Fourth, the fallback is a ladder of its own, and the request it receives is adapted for the model that will serve it.
Buy or Build
You don't have to write any of this yourself, and you should know what the off-the-shelf versions do before you choose.
- LLM gateways. LiteLLM's Router puts deployments on cooldown after failures, retries per error type, and falls back on context-window and content-policy errors. Portkey has a circuit breaker configured by failure threshold, minimum requests and cooldown, alongside fallbacks. OpenRouter fails over between providers by default and accepts a list of fallback models.
- Agent frameworks. LangGraph puts
RetryPolicyand timeouts on individual nodes. LangChain ships retry and fallback middleware for model and tool calls.
Read their documented semantics against the bugs above. Portkey documents only open and closed states, with no half-open probe. By default it counts only status codes above 500 as failures, so a storm of 429s never opens it. And it bypasses the breaker when every target is open. LiteLLM's cooldowns are time-based, with no documented probe. None of that is wrong, but each is a different design from the breaker in this article. Pick the one whose failure semantics you can state, and keep the two questions a gateway can't answer for you: whether the fallback model may take the same actions, and whose budget its requests spend.
grid-rows: 1
grid-gap: 14
classes: {
blue: {style: {fill: "#38BDF8"; stroke: "#0EA5E9"; font-color: "#2C2C2A"}}
green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
}
buy: "A gateway or framework gives you" {
label.near: top-center
grid-columns: 1
grid-gap: 8
a: "retries and cooldowns" {class: blue}
b: "provider and model failover" {class: blue}
c: "its own breaker semantics" {class: blue}
}
own: "You still own" {
label.near: top-center
grid-columns: 1
grid-gap: 8
d: "which errors count as failures" {class: green}
e: "what the fallback may do" {class: green}
f: "what retries may spend" {class: green}
}
The left column is plumbing, and buying it is usually right. The right column is policy, and no vendor knows yours.
What Observability Looks Like for This Layer
Circuit breaker state changes - log every CLOSED→OPEN and OPEN→CLOSED transition with timestamp, failure rate at trigger, and duration in OPEN state. This is your LLM infrastructure incident log.
Retry attempt distribution - what fraction of requests succeed on first attempt vs. require 1, 2, or 3 retries? A shifting distribution (more requests requiring multiple retries) is an early signal of endpoint degradation before the circuit breaker opens.
Fallback activation rate - what fraction of requests are served by the secondary provider or cached response? A rising fallback rate signals primary provider degradation even when the circuit breaker hasn't opened yet.
Provider latency percentiles - track P50, P95, and P99 latency separately for primary and secondary. A rising P99 while P50 is stable is a classic sign of partial degradation - some requests are hanging while most succeed.
Timeout rate - requests that hit the hard timeout before returning. A rising timeout rate is often the first observable signal of provider degradation, appearing before error rates increase.
grid-rows: 2
grid-columns: 4
grid-gap: 12
classes: {
violet: {style: {fill: "#6F00FF"; stroke: "#5500CC"; font-color: "#FFFFFF"}}
grey: {style: {fill: "#F3F4F6"; stroke: "#D1D5DB"; font-color: "#2C2C2A"}}
}
a: "Retry layer" {class: violet}
b: "Breaker" {class: violet}
c: "Fallback" {class: violet}
d: "Provider" {class: violet}
m1: "Attempts per success" {class: grey}
m2: "State transitions\nand time open" {class: grey}
m3: "Fallback activation rate" {class: grey}
m4: "P50/P95/P99 latency,\ntimeout rate" {class: grey}
Read the bottom row left to right during an incident. Retries climb first, then timeouts, then the breaker opens, and the fallback rate tells you how much of it users actually saw.
What to Build First
First: Hard timeouts on all LLM calls. If your LLM calls have no timeout, a slow provider turns into hanging requests that consume connections and memory until your server runs out of both. Set timeouts deliberately: a per-call deadline sized to the model and task, and for streams, time to first token plus an idle timeout between chunks.
Second: Retry in one layer. Either the SDK's built-in retries or your own loop with the SDK's turned off, not both. Retry 408, 409, 5xx, 529 and rate-limit 429s with jittered backoff, and respect Retry-After. Don't retry quota 429s, and don't retry timed-out writes that have no idempotency key. Cap attempts, and count them against the run's budget.
Third: Circuit breaker. Wire up a circuit breaker on your primary LLM client. Start with conservative thresholds (50% failure rate over 60 seconds, 10 request minimum). Tighten as you observe production behavior.
Fourth: Secondary provider. Configure a secondary LLM client (different provider or smaller model on same provider). Wire it to activate when the circuit breaker opens, with a request adapter, its own authority band and its own budget line, and test it with production request shapes.
Fifth: Degradation messaging. Implement a user-facing message for when all providers are unavailable. "Our AI assistant is temporarily unavailable. You can still [manual path]." Better than a spinner.
Sixth: Observability. Add metrics for all of the above. Circuit state, retry counts, fallback activations, latency percentiles. You cannot manage what you cannot measure.
grid-columns: 1
grid-gap: 8
classes: {
green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
blue: {style: {fill: "#38BDF8"; stroke: "#0EA5E9"; font-color: "#2C2C2A"}}
violet: {style: {fill: "#6F00FF"; stroke: "#5500CC"; font-color: "#FFFFFF"}}
}
s1: "1. Deliberate timeouts (streams too)" {class: green}
s2: "2. Retry in exactly one layer" {class: green}
s3: "3. Circuit breaker with a real half-open" {class: blue}
s4: "4. Secondary with adapter, authority, budget" {class: blue}
s5: "5. Degradation message" {class: violet}
s6: "6. Observability for all of it" {class: violet}
The first two are small changes, and they prevent the outages you would otherwise cause yourself. The rest is what keeps you serving when the outage isn't yours.
The Principle
Your LLM provider will have an incident. The question was never whether - it's when, and whether your system was designed to handle it.
Retry absorbs the noise. The circuit breaker absorbs the storm. The fallback keeps the lights on.
An LLM system without a circuit breaker is a system that fails loudly and completely when its provider has an incident. An LLM system with one fails gracefully, partially, and recovers automatically.
Your users shouldn't know your provider had an incident. That's the standard. Build to it.
What's Next in This Series
- Part 1: Harness Engineering - The Missing Layer - The full seven-layer Harness Architecture overview
- Part 2: Normalization and Input Defense - Prompt injection, input sanitization, and multi-surface consistency
- Part 3: Context Engineering - Memory architectures, retrieval strategies, and context compression
- Part 4: Gated Execution - Policy engines, human-in-the-loop design, and dry-run patterns
- Part 5: Validation Layer Design - Schema validators, semantic checks, and repair prompt patterns
- Part 7: State Management for Agentic Systems - Checkpoint-resume strategies, cross-session memory, and durable state for long-running agents
- Part 8: Deterministic Constraint Systems - Building tool registries and action manifests that prevent hallucinated actions in agentic systems
Going deeper: Chapter 8 of the book
This is Part 6 of the Harness Engineering series, which grew into Harness Engineering for Production AI Systems. This layer became Chapter 8, "Retry, Fallback, Circuit Breaking," which explains why a timeout on a non-idempotent write must not be retried while a rate limit may be, and why jitter matters. It wires the retry loop into a LangGraph node with injected sleeps and covers the morning-after reprocess path.
The code for that chapter is the ch08-retry-fallback-breaking tag of the companion repository. Its tests need no model and no API key.
For a chapter-length treatment on this blog, including where it departs from the book, see LLM Fallback Models Inherit Authority They Never Earned, Part 8 of the chapter-by-chapter guide to the book.
References
-
Fowler, M. (2014). Circuit Breaker. martinfowler.com. https://martinfowler.com/bliki/CircuitBreaker.html
-
Nygard, M. (2007). Release It! Design and Deploy Production-Ready Software. Pragmatic Bookshelf.
-
Google SRE Team. (2016). Site Reliability Engineering: How Google Runs Production Systems. O'Reilly Media. https://sre.google/sre-book/table-of-contents/
-
Brooker, M. (2015, updated 2023). Exponential Backoff And Jitter. AWS Architecture Blog. https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/
-
Beyer, B., Jones, C., Petoff, J., & Murphy, N. R. (2018). The Site Reliability Workbook. O'Reilly Media. https://sre.google/workbook/table-of-contents/
-
Netflix. Hystrix. https://github.com/Netflix/Hystrix (the library that popularized the pattern; now in maintenance mode, and its README points to resilience4j)
-
Anthropic. API errors. https://platform.claude.com/docs/en/api/errors
-
Kumar, R. (2026). Harness Engineering for Production AI Systems. Chapter 8, "Retry, Fallback, Circuit Breaking." https://harness.ranjankumar.in/
-
Anthropic. Python SDK: retries and timeouts. https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/python
-
OpenAI. Error codes. https://developers.openai.com/api/docs/guides/error-codes
-
LiteLLM. Router: load balancing, retries and fallbacks. https://docs.litellm.ai/docs/routing
-
Portkey. Circuit breaker. https://portkey.ai/docs/product/ai-gateway/circuit-breaker
-
OpenRouter. Provider selection and model fallbacks. https://openrouter.ai/docs/guides/routing/provider-selection and https://openrouter.ai/docs/guides/routing/model-fallbacks
-
LangGraph. Fault tolerance (retry policies, node timeouts). https://docs.langchain.com/oss/python/langgraph/fault-tolerance
-
LangChain. Built-in middleware (model retry, model fallback, tool retry). https://docs.langchain.com/oss/python/langchain/middleware/built-in
Related Articles
- Normalization and Input Defense: Hardening the Entry Point of Your LLM System
- Harness Engineering: The Missing Layer Between LLMs and Production Systems
- Validation Layer Design: Building the Reflex That Catches What the Model Gets Wrong
- Fault Isolation and Circuit Breaking: Stop Retrying LLM Calls Like Microservices






