11C.3 Fallbacks, Gateways and Reliability

ProductionLesson 3 of 615,866 words12 parts
Module 11C · 0 of 5 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6

An LLM feature is only as reliable as its weakest dependency, and its dependencies are unusually flaky: providers have outages, rate-limit spikes and bad deploys; models get deprecated under you; a well-formed request can still come back refused, truncated or silently worse after a provider ships a new checkpoint. Retries alone don't fix this — they can make it worse, turning one outage into a retry storm that amplifies the load on a struggling provider. This lesson is the complete engineering reference for making LLM features survive their dependencies: what "reliable" means when outputs are non-deterministic, the layered defence model (retries, timeouts, circuit breakers, bulkheads, rate limiters, fallback chains, graceful degradation, idempotency, hedging), production implementations of each in the module's llm_service project, the LLM gateway landscape as of November 2026, multi-provider failover under data-policy constraints, and the testing discipline — chaos tests, canaries, game days — that proves any of it works. It builds on the per-call mechanics of 03.8, the thin provider-agnostic client of 03.11, the cost and latency work of 11B.1 and the routing work of 11B.5; observability and alerting are 11A.1 and 11A.2.

What you'll learn

  • What "reliability" means for an LLM feature — availability, latency and quality are three different promises, and a system can be up and still be broken
  • The full catalogue of dependency failure modes: outages, partial degradation, 429s (slow-down and out-of-money), overload, slow first tokens, model deprecation, content-policy blocks, quota exhaustion, regional incidents, bad deploys and silent quality regressions
  • The layered defence model: which mechanism handles which failure, and why each layer exists — retries, timeouts, circuit breakers, bulkheads, rate limiters and load shedding, fallback chains, graceful degradation, idempotency and hedging
  • A production circuit breaker in async Python: closed/open/half-open states, failure-rate windows, per-provider-per-model breakers, jittered recovery probes — full code, injectable clock, tested against a flaky fake provider
  • Bulkheads (bounded concurrency pools per feature and tenant) and load shedding (reject or queue when saturated, with priorities)
  • Deadlines and cancellation end to end: per-stage time budgets, deadline propagation through pipelines, and what happens when the client disconnects mid-stream
  • Fallback chains with policies: which error classes trigger a fallback, which never do, how to prevent fallback loops, how to tell users and logs that the answer came from a degraded path, and why a fallback must not violate your data policy
  • Streaming failures: what changes when a call breaks after the first token (invisible fallback only before it; reset or surface the break after it; never restart past a tool call), with a tested stdlib helper
  • Graceful degradation ladders: from a smaller model, to a cached answer, to retrieval-only, to an honest "try again later" — and why every rung is a product decision
  • Rate-limit management at scale: token-aware client-side throttling, a shared limiter for multi-instance deployments, tenant fairness and backoff coordination — full code with an in-memory store you can swap for Redis
  • Health checks, canaries and chaos testing: liveness vs readiness vs model canaries, synthetic probes, scheduled eval canaries, and a fault-injection suite that kills your fake providers in every documented way
  • The LLM gateway landscape as of November 2026: LiteLLM proxy, Portkey, OpenRouter, Cloudflare AI Gateway, Vercel AI Gateway, Kong AI Gateway, Helicone AI Gateway, Amazon Bedrock AgentCore Gateway, Azure API Management, Google Apigee, Agent Router (formerly Envoy AI Gateway), Bifrost, TensorZero, and a self-built thin gateway — verified features, licences, deployment models and trade-offs in one comparison table, plus the library-level options (Vercel AI SDK, any-llm, aisuite, LangChain init_chat_model, Pydantic AI) that unify providers without a proxy
  • Gateway config in practice: a LiteLLM config.yaml with fallbacks, retries and cooldowns; OpenRouter's server-side models fallback; a minimal FastAPI gateway skeleton — and the rules that keep a gateway from becoming your biggest new failure mode
  • Provider SLAs and multi-region failover: what the providers actually promise (very little, as of November 2026), how to monitor their status, and how to fail over across regions without breaking data-residency commitments
  • Quality reliability: pinned versions vs aliases, scheduled canary evals on provider model updates, and output validators as first-class reliability tools

What you don't need

  • API keys or running services. Every mechanism in this lesson is demonstrated against fake providers, mock servers and an in-memory clock; the gateway configs are reference material you can run later. Pure-local code is run for real output wherever it can be.
  • The per-call error taxonomy and retry mechanics. 03.8 owns those — including llm_errors.py's classify(), the Failure/Kind types and areliable_call(). This lesson assumes you have read it and reuses its vocabulary; it does not re-teach it.
  • The provider-agnostic client's fallback chain. 03.11 Part 8 built a simple ordered fallback; this lesson is the system-level version: memory (breakers), isolation (bulkheads), shared state (limiters) and policy (degradation).
  • Metrics, dashboards, SLOs and alerting design. 11A.2 owns those; this lesson produces the signals they consume and shows where the boundary falls.
  • Security architecture. Module 12 owns threat modelling, guardrails and data-protection policy; the data-residency section here covers only what failover must not break.

Setup

The resilience code in this lesson is pure Python 3.11+ with the standard library — no providers, no keys, no services. The examples live in the Modules 11A to 11C running project, llm_service, a FastAPI package built across those modules. If you haven't created it yet (the tracing and metrics lessons create it first), run:

bash
uv init llm-service --bare --python 3.13 && cd llm-service
uv add pytest pytest-asyncio

Or pip install pytest pytest-asyncio (pytest-asyncio runs the chaos suite in 8.3). The .env file is only needed for the provider-facing gateway examples, which are labelled illustrative:

bash
# .env  (never commit this file)
OPENAI_API_KEY=...
ANTHROPIC_API_KEY=...
OPENROUTER_API_KEY=...   # optional: only for the OpenRouter gateway examples

Every code block in this lesson is self-contained: llm_service/resilience.py is given in full in Part 12, and the chaos suite in 8.3. You can also copy the individual excerpts into the same folder as you read.


What you must be able to do after this lesson#

  • Name the three promises of an LLM feature: availability, latency and quality
  • Choose which mechanism handles which failure: retry, breaker, bulkhead, deadline, fallback
  • Implement a circuit breaker with closed, open and half-open states and a failure-rate window
  • Propagate one deadline through every stage and cancel on client disconnect
  • Build a fallback chain that skips error classes that must never fall back, and a degradation ladder
  • Throttle by tokens, not just by request count
  • Decide which health check catches silent model drift

Why this matters for an AI engineer#

You'll hear... You'll understand it after...
"The provider is down — why are we still getting timeouts instead of fallbacks?" 3. Circuit breakers
"We retried and now the outage is worse." 1.3 The layered defence and 9.5 Gateway risks
"The fallback model gave worse answers last Tuesday." 6. Fallback chains and 11. Quality reliability
"Our data can't leave the EU, but the fallback went to a US endpoint." 6.4 Fallbacks and data policy
"Requests hang for 60 seconds and then fail." 5. Deadlines and cancellation
"One noisy tenant is starving everyone else." 4. Bulkheads and load shedding and 7. Rate limits
"Should we buy a gateway or build one?" 9. LLM gateways and 03.11, 1.4
"What uptime does OpenAI actually promise us?" 10.1 What providers promise
"The model changed behaviour and nobody deployed anything." 11. Silent quality degradation
"Let's chaos-test the service before launch." 8.3 The chaos suite

Part 1: What "reliable" means for an LLM feature#

1.1 Three promises, not one#

Classic backend reliability reduces mostly to one number: availability — the fraction of requests that get a response. An LLM feature makes three promises at once, and they fail independently:

Promise Question it answers How it fails silently
Availability Did the user get an answer? Timeout, 5xx, refused connection — loud, easy to alert on
Latency Did it arrive in time? A 200 that took 90 seconds; TTFT of 40 s on a "fast" feature; queueing that looks like thinking. Users refresh and double-submit
Quality Was the answer good enough? HTTP 200, fluent prose, wrong invoice total, or — worst — a plausible answer from a fallback model nobody evaluated. Nothing raises an exception

A system can be 99.9% available and 0% reliable if every answer is wrong. This is why the observability lesson (11A.1) insists quality is the fourth pillar, and why this lesson treats fallbacks as a quality risk as much as an availability tool: every fallback path is a different model with different behaviour, and it must be evaluated like one (6.5).

SLOs for LLM features therefore need at least three SLIs — availability, latency, and a quality pass-rate measured by evals or validators — which is 11A.2's subject. This lesson's job is to keep all three promises when dependencies misbehave.

1.2 The failure catalogue#

Before choosing mechanisms, name the failures. Each row is a dependency failure mode, how you detect it, and the first mechanism that should respond — the rest of the lesson explains each one.

Failure mode What it looks like Detect via First responder
Provider outage Connect errors, 5xx on every request Error rate by provider in traces/metrics Circuit breaker → fallback chain
Partial degradation One region or model tier degraded; others fine Latency/error percentiles per route Per-route breakers, routing away
Rate limits (429) slow_down / rate_limit_error / RESOURCE_EXHAUSTED 429 share, Retry-After headers Backoff + shared limiter (7)
Out-of-money 429/402/403 credit_balance_exhausted, spend caps, quotas Error code, not status (03.8, 4.2) Never retry; alert a human; failover only if another account exists
Overload (529-style) Anthropic 529, OpenAI 503 server_is_overloaded, Gemini UNAVAILABLE Status + code Retry with backoff → breaker → fallback
Slow responses TTFT or total latency drifting up Latency percentiles per route Hedging (11B.1), timeout tightening, fallback
Model deprecation Announced shutdown date; 404/model_not_found Deprecation calendar, Models API audit (03.1, Part 10) Migration before the date (10 and 11)
Content-policy blocks Refusals, content_filter finish reasons, safety 400s Outcome checks (03.8, Part 10) Usually not a fallback — a refusal may be correct (6.2)
Quota exhaustion Daily/monthly caps, tier limits Quota headers, 403 quota_exceeded Queue + shed load; upgrade tier; failover only across your accounts
Regional incidents One geography down Provider status page + per-region metrics Multi-region routing with data-policy checks (10.3)
Bad deploys (yours) New prompt/model/index regresses quality Canary evals, error-budget burn Rollback, not fallback (11C.2)
Silent quality regressions Provider updates a model behind an alias; answers drift Scheduled eval canaries on pinned snapshots Pin versions; alert on eval deltas (11)

1.3 The layered defence model#

No single mechanism is enough. Reliability for LLM features is a stack, ordered by cost and blast radius — cheap, local protections first, expensive or risky ones last:

flowchart TD
    req["Incoming LLM request"] --> rl["Rate limiter / load shed<br/>(your side: don't make it worse)"]
    rl --> to["Timeout + deadline<br/>(bound every wait)"]
    to --> rt["Retry layer<br/>(one owner only: 03.8 / 03.11)"]
    rt --> cb["Circuit breaker<br/>(stop paying for a dead dependency)"]
    cb --> fb["Fallback chain<br/>(another model/provider/route)"]
    fb --> deg["Graceful degradation<br/>(smaller model, cache, retrieval-only, queue, honest failure)"]
    deg --> out["Response + honest signal<br/>(headers, logs, user message)"]
Layer Mechanism Failure it absorbs Cost of being wrong
0 Validation, schema checks, prompt hygiene Bad requests, malformed output Low — catch before spending tokens
1 Rate limiter, concurrency caps, load shedding You becoming the cause of the outage Low — shed early, honestly
2 Timeouts, deadlines, cancellation Hanging requests holding connections and money Medium — too tight kills healthy slow calls
3 Retries with backoff (one layer owns them) Transient blips, brief overload Medium — retry storms amplify outages; retries can double-bill
4 Circuit breakers Sustained dependency failure Medium — flapping or premature opening
5 Fallback chains Provider/model-level failure High — the fallback is an untested model until you test it
6 Graceful degradation Total dependency loss Medium — degraded answers must be labelled, never silent
7 Idempotency on your side effects (03.8, Part 11) Duplicate execution after timeout-retry High if skipped — double charges, double emails

Two cross-cutting rules sit above the stack:

  • One layer owns retries. The SDK retries, your client retries, and the gateway retries, and a single logical call can become dozens of attempts (03.8, 5.5). Decide explicitly which layer retries what; everywhere else, max_retries=0 / retries off.
  • Telemetry must never break the request. Observability, budgets and logging are fail-open and asynchronous (11A.1); a monitoring outage must not become a product outage.

Part 2: Choosing the mechanism — a decision table#

Before any code, the most useful artefact in this lesson: given a failure, which mechanism should respond? Read it top-down — the cheapest adequate mechanism wins.

Symptom Reach for Don't reach for Why
One request in a hundred fails with a transport error Retry (same route), bounded Fallback The dependency is healthy; the blip is noise
A route fails >50% of attempts for 30 s Circuit breaker on that route More retries Retrying a dead route pays its timeout on every call
Provider returns 429 with Retry-After Wait + shared limiter Immediate fallback Rate limits are your speed problem, not an outage; another provider just moves the bill
429 that is actually quota/billing (credit_balance_exhausted, spend caps) Fail fast + alert Retry, fallback "to dodge the cap" Nothing improves until a human pays or raises a limit; switching providers to evade your own cap just moves the bill (03.8, 4.2)
Whole provider region down Fallback chain to another provider/region Retry forever A different provider probably isn't down at the same moment — but check the data policy first (6.4)
One model snapshot deprecated Scheduled migration, not runtime fallback Relying on the alias Deprecation is announced; a runtime fallback papers over a planning failure
Request legitimately too big / malformed Fix the request Retry, fallback A bug on every provider; fallback doubles the bill for the same failure
Refusal or content block Handle as an outcome Automatic fallback A refusal may be the correct answer; shopping it around defeats the safety behaviour (6.2)
Intermittent 30–90 s latency spikes Hedged request or tighter deadline Bigger timeout for everyone Hedging buys tail latency at 2× cost on the hedged slice — a budget decision, not a default (11B.1)
Your own deploy regressed quality Rollback + eval gate Model fallback The model didn't change; your prompt/index/config did
Provider silently changed model behaviour Canary evals + alert + migrate deliberately "It still returns 200s" Only evaluation sees this (11)

2.1 The decision flow#

flowchart TD
    f["A call failed or is degraded"] --> q1{"Is it your bug?<br/>(400, malformed, auth, quota)"}
    q1 -->|"yes"| fix["Fix config/request; alert.<br/>No retry, no fallback"]
    q1 -->|"no: transient"| q2{"Same route healthy<br/>overall? (breaker closed)"}
    q2 -->|"yes"| retry["Retry per 03.8 policy:<br/>Retry-After or jittered backoff,<br/>inside the deadline"]
    q2 -->|"no: breaker open"| q3{"Fallback allowed<br/>by error class + data policy?"}
    q3 -->|"yes"| fb["Next entry in fallback chain<br/>(different provider preferred)"]
    q3 -->|"no, or chain exhausted"| deg["Degradation ladder:<br/>cached → smaller model →<br/>retrieval-only → queue → honest error"]
    retry -->|"still failing"| q3
    fb -->|"answer served"| sig["Mark response:<br/>X-Served-By / log model_key"]
    deg --> sig

2.2 Where each mechanism can live#

The same protection can be implemented in three places, and they compose rather than substitute:

Layer Examples Sees Blind to
Your application / llm_service resilience.py (this lesson), the 03.11 client's policy, in-process libraries such as Pydantic AI's FallbackModel (9.2b) Your tenants, features, budgets, user impact Other services' traffic
A gateway / proxy LiteLLM proxy, Portkey, Bifrost, TensorZero, Cloudflare/Vercel AI Gateway, Kong, Helicone, Apigee, your own FastAPI gateway All traffic through it, central keys and budgets Per-user semantics your app owns
The provider / aggregator OpenRouter models fallbacks and provider routing; a provider's own multi-region routing Their fleet Your data policy unless you constrain it (zdr, data_collection, only)

The golden rule from 03.8: retries live in exactly one layer. Everything else — breakers, fallbacks, shedding — may exist at several layers if each layer's trigger is distinct (your breaker trips on your error budget; the gateway's on its view). Two layers independently retrying the same failure is the double-retry trap at fleet scale.


Part 3: Circuit breakers#

3.1 What a breaker is for#

A circuit breaker is a small state machine that sits in front of a dependency and refuses to call it while it looks dead. Without one, every request during an outage pays the full failure cost — connect timeouts of 10–30 s, retry backoffs, user-visible latency — before failing anyway. With one, after enough recent failures the breaker opens: calls fail fast (in microseconds) and go straight to your fallback or degradation path, while a trickle of probe requests tests whether the dependency has recovered.

stateDiagram-v2
    [*] --> Closed
    Closed --> Open: failure rate over threshold<br/>in the window
    Open --> HalfOpen: cooldown elapsed<br/>(jittered)
    HalfOpen --> Closed: probe succeeds
    HalfOpen --> Open: probe fails
    Closed --> Closed: success resets window

The three states:

  • Closed — normal operation; failures and successes are counted.
  • Open — the dependency is presumed down; calls raise immediately (or route to fallback). No traffic is sent except recovery probes.
  • Half-open — after a cooldown, allow a small number of probe calls through. Successes close the breaker; a failure re-opens it (often with a longer cooldown).

3.2 Design choices that matter#

Choice Options Guidance
What counts as failure Any exception; only retryable classes; only timeouts/5xx Count what your fallback policy would act on — typically RateLimited? No: 429s are your speed problem (the shared limiter in Part 7 is the fix, not a breaker). Count Overloaded, ServerError, ConnectionFailed, Timeout — the 03.11 LLMError classes 03.11, 8.4 already falls back on. Never count QuotaExceeded, AuthFailed, PermissionDenied, BadRequest, ContextTooLong — those aren't "the dependency is down"
Window type Consecutive failures; sliding time window; failure rate Consecutive-count is simplest but flaps on alternating success/failure. A failure-rate window (e.g. ≥50% failures over the last N calls or T seconds) is the production choice — it tolerates a flaky-but-alive route
Key granularity Per provider; per provider+model; per deployment/region Per provider+model (or per route) is the sweet spot: an OpenAI outage shouldn't open the breaker for Anthropic, and a deprecated model shouldn't mark its provider dead
Threshold Failure count; failure ratio; both Ratio-based (e.g. ≥5 failures and ≥50% rate in window) avoids opening on one unlucky call and on a quiet period
Cooldown Fixed; exponential backoff per re-open Exponential (30 s → 60 s → 120 s, capped) prevents probe stampedes during a long outage
Half-open probes 1 probe; small batch One probe for LLM calls — they're seconds long and expensive; a batch of probes during half-open just re-creates the load you're avoiding
Jitter None; randomised cooldown Jitter the cooldown so thousands of instances don't all probe at the same instant after a provider recovers
What "open" does Raise immediately; return cached; route to fallback In llm_service the breaker raises a typed CircuitOpen error and the fallback chain above it decides — separation of concerns

3.3 The implementation#

llm_service/resilience.py is provider-agnostic: it wraps any async callable. The full file is in Part 12; here is the breaker with its demo.

python
# llm_service/resilience.py (excerpt) — the circuit breaker.
# States: closed -> open -> half-open -> closed. Counts a sliding window of
# recent outcomes per key; opens on a failure RATE, probes one call at a time.
from __future__ import annotations

import asyncio
import random
import time
from collections import deque
from dataclasses import dataclass, field
from enum import Enum
from typing import Any, Awaitable, Callable, TypeVar

T = TypeVar("T")


class BreakerState(str, Enum):
    CLOSED = "closed"
    OPEN = "open"
    HALF_OPEN = "half_open"


class CircuitOpenError(Exception):
    """Raised fast while the breaker is open. Carries when it may be probed."""

    def __init__(self, key: str, retry_at: float):
        super().__init__(f"circuit open for {key!r}; probe after {retry_at:.1f}")
        self.key = key
        self.retry_at = retry_at


@dataclass
class BreakerConfig:
    window: int = 20            # outcomes kept per key (calls, not seconds)
    min_calls: int = 5          # don't judge before this many outcomes
    failure_rate: float = 0.5   # open when failures / outcomes >= this
    cooldown_s: float = 30.0    # first open duration
    max_cooldown_s: float = 300.0
    cooldown_growth: float = 2.0  # exponential backoff per consecutive open
    probe_timeout_s: float | None = None  # cap a half-open probe (None = caller's timeout)

    def __post_init__(self) -> None:
        # A misconfigured breaker fails silently: with min_calls > window the
        # outcome window can never reach min_calls, so it would never trip.
        if not (isinstance(self.window, int) and isinstance(self.min_calls, int)
                and 1 <= self.min_calls <= self.window):
            raise ValueError("need integers 1 <= min_calls <= window")
        if not 0 < self.failure_rate <= 1:
            raise ValueError("failure_rate must be in (0, 1]")
        if not (0 <= self.cooldown_s <= self.max_cooldown_s and self.cooldown_growth >= 1):
            raise ValueError("need 0 <= cooldown_s <= max_cooldown_s and cooldown_growth >= 1")
        if self.probe_timeout_s is not None and not self.probe_timeout_s > 0:
            raise ValueError("probe_timeout_s must be positive or None")


@dataclass
class _Window:
    outcomes: deque[bool] = field(default_factory=lambda: deque(maxlen=20))
    opened_at: float | None = None
    consecutive_opens: int = 0
    cooldown_s: float = 30.0


class CircuitBreaker:
    """Async circuit breaker, keyed by dependency (e.g. 'openai/gpt-6-luna').

    `is_failure(exc)` decides which exceptions count; the default counts
    everything, so pass the predicate your fallback policy uses (03.8 kinds).
    clock/sleep/rng are injectable for deterministic tests.
    """

    def __init__(
        self,
        config: BreakerConfig | None = None,
        *,
        is_failure: Callable[[BaseException], bool] | None = None,
        clock: Callable[[], float] = time.monotonic,
        sleep: Callable[[float], Awaitable[None]] = asyncio.sleep,
        rng: random.Random | None = None,
    ) -> None:
        self.config = config or BreakerConfig()
        self.is_failure = is_failure or (lambda exc: True)
        self._clock = clock
        self._sleep = sleep
        self._rng = rng or random.Random()
        self._windows: dict[str, _Window] = {}
        self._half_open_inflight: set[str] = set()

    # -- state -----------------------------------------------------------------
    def state(self, key: str) -> BreakerState:
        w = self._windows.get(key)
        if w is None or w.opened_at is None:
            return BreakerState.CLOSED
        if self._clock() - w.opened_at >= w.cooldown_s and key not in self._half_open_inflight:
            return BreakerState.HALF_OPEN
        return BreakerState.OPEN

    def _window(self, key: str) -> _Window:
        if key not in self._windows:
            self._windows[key] = _Window(outcomes=deque(maxlen=self.config.window),
                                         cooldown_s=self.config.cooldown_s)
        return self._windows[key]

    # -- the call ---------------------------------------------------------------
    async def call(self, key: str, fn: Callable[[], Awaitable[T]]) -> T:
        """Run fn() under the breaker for `key`. Raises CircuitOpenError fast
        when open; lets exactly one probe through in half-open."""
        st = self.state(key)
        if st is BreakerState.OPEN:
            raise CircuitOpenError(key, self._probe_at(key))
        if st is BreakerState.HALF_OPEN:
            if key in self._half_open_inflight:
                raise CircuitOpenError(key, self._probe_at(key))
            self._half_open_inflight.add(key)
        try:
            if st is BreakerState.HALF_OPEN and self.config.probe_timeout_s is not None:
                # A probe that never returns would hold the one probe slot for ever.
                result = await asyncio.wait_for(fn(), self.config.probe_timeout_s)
            else:
                result = await fn()
        except asyncio.CancelledError:
            # Client disconnect / task cancellation is not evidence the provider
            # is down — never count it toward the failure window.
            raise
        except Exception as exc:
            try:
                failed = bool(self.is_failure(exc))
            except Exception:       # a broken predicate must not hide an outage
                failed = True
            # Free the probe slot BEFORE recording so state() inside _record
            # sees HALF_OPEN: the probe's outcome then closes or re-opens the
            # breaker instead of being discarded as "already open".
            self._half_open_inflight.discard(key)
            self._record(key, failed)
            raise
        else:
            self._half_open_inflight.discard(key)
            self._record(key, False)
            return result
        finally:
            self._half_open_inflight.discard(key)

    # -- bookkeeping -------------------------------------------------------------
    def _probe_at(self, key: str) -> float:
        w = self._windows[key]
        jitter = self._rng.uniform(0, w.cooldown_s * 0.1)
        return w.opened_at + w.cooldown_s + jitter

    def _record(self, key: str, failed: bool) -> None:
        w = self._window(key)
        w.outcomes.append(failed)
        st = self.state(key)
        if st is BreakerState.HALF_OPEN:
            # A probe result decides immediately: success closes, failure re-opens longer.
            if failed:
                self._open(key, w)
            else:
                w.opened_at = None
                w.consecutive_opens = 0
                w.cooldown_s = self.config.cooldown_s
            return
        if st is BreakerState.OPEN:
            return  # already open; outcome of a probe that raced is ignored
        if len(w.outcomes) >= self.config.min_calls:
            rate = sum(w.outcomes) / len(w.outcomes)
            if rate >= self.config.failure_rate:
                self._open(key, w)

    def _open(self, key: str, w: _Window) -> None:
        w.opened_at = self._clock()
        w.consecutive_opens += 1
        # The exponent is capped: 2.0 ** 1100 raises OverflowError, which would
        # surface from the failing call after about 1,000 consecutive re-opens.
        growth = self.config.cooldown_growth ** min(w.consecutive_opens - 1, 64)
        w.cooldown_s = min(self.config.cooldown_s * growth, self.config.max_cooldown_s)
        w.outcomes.clear()          # start the next window clean

3.4 Try it: a flaky provider, a real breaker#

python
# s3_breaker_demo.py — run: uv run python s3_breaker_demo.py  (stdlib only)
import asyncio
import random

from llm_service.resilience import BreakerConfig, CircuitBreaker, CircuitOpenError


class FakeClock:
    """Deterministic clock + sleep for tests: time only moves when slept."""

    def __init__(self) -> None:
        self.t = 0.0
        self.slept: list[float] = []

    def __call__(self) -> float:
        return self.t

    async def sleep(self, s: float) -> None:
        self.slept.append(s)
        self.t += s


class FlakyProvider:
    """A provider that fails `fail_rate` of calls and records what it saw."""

    def __init__(self, fail_rate: float, seed: int = 7) -> None:
        self.fail_rate = fail_rate
        self.rng = random.Random(seed)
        self.calls = 0
        self.script: list[str] = []   # 'ok' | 'fail' | 'hang' — overrides rng when set

    async def complete(self) -> str:
        self.calls += 1
        step = self.script.pop(0) if self.script else ("fail" if self.rng.random() < self.fail_rate else "ok")
        if step == "hang":
            await asyncio.sleep(30)  # would be a client timeout in production
        if step == "fail":
            raise TimeoutError("provider timed out")
        return "answer"


async def main() -> None:
    clock = FakeClock()
    provider = FlakyProvider(fail_rate=1.0)          # fully down
    breaker = CircuitBreaker(
        BreakerConfig(window=10, min_calls=4, failure_rate=0.5, cooldown_s=30.0),
        clock=clock, sleep=clock.sleep, rng=random.Random(1),
    )

    async def guarded() -> str:
        return await breaker.call("openai/gpt-6-luna", provider.complete)

    # Phase 1: the provider is down — calls fail until the breaker opens
    for i in range(8):
        try:
            await guarded()
            print(f"call {i}: ok")
        except CircuitOpenError as e:
            print(f"call {i}: OPEN — fast fail ({e})")
        except TimeoutError:
            print(f"call {i}: TimeoutError (paid the failure cost)")
        await clock.sleep(0.01)                        # a tiny real delay; clock.sleep advances fake time

    # Phase 2: provider recovers; cooldown elapses; a probe succeeds -> closed
    provider.fail_rate = 0.0
    print(f"\nprovider healed. calls seen by provider: {provider.calls}")
    await clock.sleep(31.0)                            # past the 30 s cooldown (+ jitter)
    key = "openai/gpt-6-luna"
    for i in range(3):
        try:
            print(f"probe {i}: {await guarded()}  state={breaker.state(key).value}")
        except CircuitOpenError:
            print(f"probe {i}: still open  state={breaker.state(key).value}")
        except TimeoutError:
            print(f"probe {i}: failed again -> re-open  state={breaker.state(key).value}")


asyncio.run(main())
Output · deterministic — fake clock and seeded RNG13 lines
call 0: TimeoutError (paid the failure cost)
call 1: TimeoutError (paid the failure cost)
call 2: TimeoutError (paid the failure cost)
call 3: TimeoutError (paid the failure cost)
call 4: OPEN — fast fail (circuit open for 'openai/gpt-6-luna'; probe after 30.4)
call 5: OPEN — fast fail (circuit open for 'openai/gpt-6-luna'; probe after 32.6)
call 6: OPEN — fast fail (circuit open for 'openai/gpt-6-luna'; probe after 32.3)
call 7: OPEN — fast fail (circuit open for 'openai/gpt-6-luna'; probe after 30.8)

provider healed. calls seen by provider: 4
probe 0: answer  state=closed
probe 1: answer  state=closed
probe 2: answer  state=closed

Read the economics: the provider saw 4 calls during the outage window, not 8 — calls 4–7 failed in microseconds at the breaker. During a real outage with hundreds of requests per second, that is the difference between "the provider gets a trickle of doomed requests" and "we amplify the outage". The retry_at timestamp in CircuitOpenError is what your fallback chain uses to decide whether to wait for the probe or move to the next route now. And watch state=closed: the first post-cooldown call is the single half-open probe, and its success is what returns the breaker to CLOSED — calls 1 and 2 then run as normal traffic, not probes.

Symptom Likely cause Fix
Breaker opens on the first blip min_calls too low or failure_rate too low Raise min_calls; require a minimum failure count too
Breaker flaps open/closed Cooldown too short; probes too generous; half-open allows >1 probe Longer cooldown, exponential growth, exactly one probe
Provider "recovers" then immediately re-opens Probe succeeded but real traffic still fails Probe with a representative request (same model, similar size); half-open should stay conservative
Breaker never opens during an outage is_failure predicate too narrow (e.g. only counts 5xx, but the outage is timeouts) Count the union of classes your fallback policy acts on
All routes open simultaneously Shared fate: your network/VPC is the problem, not the provider Per-route keys already isolate providers; check your own egress before blaming providers
Open breaker hides a quota problem Quota errors counted as failures Exclude QuotaExceeded/AuthFailed/BadRequest classes — they are not "dependency down"

Per-instance vs shared breakers. The breaker above is per-process. With N service instances, each learns the outage independently — acceptable for moderate fleets (each instance stops calling within window calls). At larger scale you can share breaker state through the same store as the rate limiter (7), at the cost of a network dependency in the failure path — usually not worth it; per-instance breakers plus shared metrics (alert when >X% of instances have the route open) is the pragmatic pattern.


Part 4: Bulkheads and load shedding#

4.1 Bulkheads: isolate the blast radius#

A bulkhead is a bounded pool of resources per caller class — per feature, per tenant, per model route — so one group's surge or failure cannot consume everyone's capacity. The name comes from ships: watertight compartments keep a hull breach from flooding the whole vessel.

LLM services need bulkheads because the resource being protected isn't CPU — it's concurrency slots and provider quota:

  • A burst of agent runs (each holding a slot for 30–120 s) can starve the interactive chat feature if they share one semaphore.
  • One tenant's batch backfill can consume the shared rate-limit budget and 429 everyone else.
  • A slow model route (reasoning at high effort) can hold connections open long enough to exhaust the HTTP client's connection pool for everyone.

The implementation is deliberately boring: a bounded pool of slots per key — implemented with asyncio.Queue because asyncio.Semaphore has no non-blocking acquire (see the note below) — acquired before the provider call and released after. What makes it a bulkhead rather than just a semaphore is the policy around the key: per-tenant limits sized to fair share, per-feature limits sized to product priority, and — critically — what happens when the bulkhead is full (see 4.2).

python
# llm_service/resilience.py (excerpt) — bulkheads: bounded concurrency per key.
# asyncio.Queue slots give explicit non-blocking semantics (get_nowait);
# asyncio.Semaphore has no equivalent, which is why it isn't used here.
from __future__ import annotations

import asyncio
from contextlib import asynccontextmanager
from typing import AsyncIterator


class BulkheadFullError(Exception):
    """Raised immediately when a bulkhead has no free slots."""

    def __init__(self, key: str, limit: int):
        super().__init__(f"bulkhead {key!r} full ({limit} in flight)")
        self.key = key
        self.limit = limit


class Bulkheads:
    """Per-key bounded concurrency using asyncio.Queue slots. Keys are yours:
    'tenant:acme', 'feature:chat', 'route:reasoning'. acquire() fails fast;
    acquire(wait_s=...) queues up to that long, then BulkheadFullError."""

    def __init__(self, default_limit: int = 8, limits: dict[str, int] | None = None) -> None:
        self._default, self._limits = default_limit, limits or {}
        self._slots: dict[str, asyncio.Queue] = {}
        self._limits_seen: dict[str, int] = {}

    def _queue(self, key: str) -> tuple[asyncio.Queue, int]:
        if key not in self._slots:
            limit = self._limits.get(key, self._default)
            q = asyncio.Queue(maxsize=limit)
            for _ in range(limit):          # pre-fill with `limit` slot tokens
                q.put_nowait(None)
            self._slots[key] = q
            self._limits_seen[key] = limit
        return self._slots[key], self._limits_seen[key]

    @asynccontextmanager
    async def acquire(self, key: str, *, wait_s: float | None = None) -> AsyncIterator[None]:
        """Hold one slot for `key`. wait_s=None -> fail fast when full;
        wait_s>0 -> queue up to that long, then BulkheadFullError."""
        q, limit = self._queue(key)
        try:
            if wait_s is None:
                q.get_nowait()              # documented non-blocking acquire
            else:
                await asyncio.wait_for(q.get(), timeout=wait_s)
        except (asyncio.QueueEmpty, TimeoutError) as exc:
            raise BulkheadFullError(key, limit) from exc
        try:
            yield
        finally:
            q.put_nowait(None)              # return the slot

4.2 Load shedding: what to do when the bulkhead is full#

A full bulkhead is a signal, and the response is a product decision, not an exception to swallow:

Option When it's right Cost
Fail fast (429/503 to the caller) Interactive traffic where an honest "busy" beats a 60 s spinner Lost request; must be retryable by the client
Queue with a deadline Background work, non-interactive jobs Latency grows; must bound queue depth and wait
Serve degraded A cheaper/faster path exists (smaller model, cached answer, retrieval-only) Quality drops — label it (6.3)
Drop lowest priority Mixed traffic with priorities Starvation of low-priority work by design

The worst response is the one most systems accidentally implement: queue unboundedly. An unbounded queue converts a provider outage into a memory leak and a thundering-herd retry storm when the provider returns. Bound the queue, bound the wait, and shed honestly.

python
# Priority queue with a hard cap — the "shed" in load shedding.
# (Simplified excerpt — the canonical version is in Part 12.)
import heapq
from dataclasses import dataclass, field


@dataclass(order=True)
class _Item:
    priority: int                      # lower = more important
    seq: int = field(compare=False)    # FIFO within a priority
    payload: object = field(compare=False, default=None)


class PriorityQueue:
    """Bounded priority queue. put() sheds the LOWEST-priority item when full
    (or rejects the incoming one if it is itself the lowest)."""

    def __init__(self, maxsize: int) -> None:
        if isinstance(maxsize, bool) or not isinstance(maxsize, int) or maxsize < 1:
            raise ValueError("maxsize must be an integer >= 1")
        self._q: list[_Item] = []
        self._max = maxsize
        self._seq = 0
        self.shed_count = 0

    def put(self, payload: object, priority: int = 100) -> bool:
        item = _Item(priority=priority, seq=self._seq, payload=payload)
        self._seq += 1
        if len(self._q) < self._max:
            heapq.heappush(self._q, item)
            return True
        # Full: find the least-important item — highest priority number; on a
        # tie, the OLDEST (smallest seq). LIFO-shed (newest first) is the
        # alternative policy; oldest-first keeps fresh work.
        worst_idx = max(range(len(self._q)), key=lambda i: (self._q[i].priority, -self._q[i].seq))
        self.shed_count += 1
        if item.priority < self._q[worst_idx].priority:
            self._q.pop(worst_idx)
            heapq.heapify(self._q)
            heapq.heappush(self._q, item)
            return True
        return False

4.3 Bulkheads in the gateway vs in your app#

Gateway-level bulkheads (per-API-key rate limits, per-team budgets in LiteLLM/Cloudflare/Vercel/Kong) protect the provider account from all your services combined. App-level bulkheads protect your features from each other. You need both: the gateway can't know that "feature:chat" matters more than "feature:batch", and your app can't see traffic from other services sharing the same provider key.


Part 5: Deadlines and cancellation#

5.1 One deadline, propagated#

03.8, Part 6 covered per-request timeouts; 03.9, 5.3 covered a deadline for a whole job. Production LLM features need both at once: a deadline is an absolute point in time by which the whole request must finish, and every stage — retrieval, rerank, generate, tool calls, guardrails — spends from the same budget. Without propagation, a RAG pipeline can spend 8 s retrieving, then hand the generator a 2 s timeout and guarantee failure; or a client that disconnected 30 s ago keeps paying for tokens nobody will read.

The pattern is a Deadline object created at the edge, passed down, and queried (remaining) before each stage decides how much time it may take:

python
# llm_service/resilience.py (excerpt) — deadline propagation.
from __future__ import annotations

import time
from dataclasses import dataclass
from typing import Callable


class DeadlineExceededError(Exception):
    """Raised when a stage finds the shared deadline already spent."""


@dataclass
class Deadline:
    """An absolute time budget shared by every stage of one request.

    clock is injectable (tests); monotonic is correct for measuring elapsed
    time — never wall-clock, which can jump.
    """

    budget_s: float
    clock: Callable[[], float] = time.monotonic
    _start: float = 0.0

    def __post_init__(self) -> None:
        self._start = self.clock()

    @property
    def remaining(self) -> float:
        return max(0.0, self.budget_s - (self.clock() - self._start))

    def stage_budget(self, fraction: float) -> float:
        """A sub-budget for one stage: at most `fraction` of what remains.
        Stages must check remaining BEFORE starting expensive work."""
        return self.remaining * fraction

    def check(self) -> None:
        if self.remaining <= 0:
            raise DeadlineExceededError(f"deadline of {self.budget_s}s exhausted")

    def timeout_for(self, provider_default_s: float) -> float:
        """The timeout to hand a provider call: never more than what remains,
        and never the provider default if the deadline is tighter."""
        return min(provider_default_s, self.remaining)

A RAG-style pipeline using it (conceptual — the real docs_qa pipeline is 07.11):

python
from llm_service.resilience import Deadline   # retrieve() and generate() are your own stage functions


async def answer(question: str, deadline: Deadline) -> str:
    deadline.check()                                    # cheap gate first
    hits = await retrieve(question, timeout_s=deadline.stage_budget(0.3))
    deadline.check()                                    # don't generate if retrieval ate the budget
    return await generate(question, hits,
                          timeout_s=deadline.timeout_for(provider_default_s=60.0))

5.2 Cancellation: the client left, stop paying#

Two distinct problems hide under "timeout":

  1. Our deadline passed — the request is hopeless; cancel upstream work and return an honest error (or a degraded answer if one is cheap).
  2. The client disconnected — nobody is listening. Continuing to generate tokens is pure waste: the provider bills for output nobody reads.

For (2), the mechanism depends on your stack. In FastAPI/Starlette, await request.is_disconnected() polls the connection; for streaming responses, checking it between tokens lets you abort mid-stream and cancel the upstream call. The clean pattern is to race the provider call against a disconnect watcher:

python
# FastAPI excerpt — abort the provider call when the client disconnects.
# Reference code, unrun. Pattern: race the work against is_disconnected().
import asyncio


async def watch_disconnect(request) -> None:
    """Completes when the client goes away."""
    while not await request.is_disconnected():
        await asyncio.sleep(0.5)
    raise asyncio.CancelledError("client disconnected")


async def generate_with_disconnect(request, prompt: str) -> str:
    work = asyncio.create_task(provider_call(prompt))       # the LLM call
    watcher = asyncio.create_task(watch_disconnect(request))
    try:
        done, pending = await asyncio.wait(
            {work, watcher}, return_when=asyncio.FIRST_COMPLETED)
        for t in pending:
            t.cancel()
        if watcher in done:
            raise asyncio.CancelledError("client disconnected")
        return work.result()
    finally:
        # Cancelling work() propagates into the SDK's httpx call: the TCP
        # connection closes and the provider MAY still finish server-side
        # (billed, per 03.8, 6.6) — but we stop paying for tokens we won't read.
        if not work.done():
            work.cancel()

5.3 Per-stage budgets: a worked split#

A sensible default split for a chat-with-RAG request on a 30 s deadline:

Stage Budget share Notes
Auth, rate limit, validation ~0 (local) Must never wait on the network
Retrieval (embed + vector search + rerank) ≤30% p95 retrieval is usually <2 s; the cap is a guard, not a target
Generation remainder minus reserve Reserve ~10% for post-processing, logging, response framing
Fallback attempt only if primary fails fast A fallback that starts with 2 s left will itself time out — check remaining before trying

The rule that makes this work: every stage gets min(its own need, remaining × fraction), and a stage that can't fit its minimum useful budget should fail fast rather than start work it can't finish.


Part 6: Fallback chains and degradation#

6.1 The chain, and what triggers it#

03.11, Part 8 built an ordered fallback chain inside the provider-agnostic client: try the primary model, retry per policy, then move to the next entry. This lesson generalises it into FallbackChain in resilience.py: a list of named routes, each with its own breaker, tried in order when the previous one fails for an allowed reason.

6.2 When to fall back — and when never to#

The trigger table is the heart of fallback policy. It extends 03.11, 8.4's table with the system-level cases. The vocabulary is the 03.11 LLMError classes — the exceptions may_fall_back actually inspects — with the matching 03.8 Kind values in brackets:

Failure class (03.11 LLMError; 03.8 Kind) Fall back? Why
Overloaded, ServerError, ConnectionFailed, Timeout (after max_timeout_attempts) — OVERLOADED, SERVER_ERROR, CONNECTION, TIMEOUT, CONFLICT (409 maps to ServerError/CONFLICT; retryable in both taxonomies) Yes Another provider probably isn't down at the same moment
RateLimited (genuine 429 slow-down) — RATE_LIMITED Usually yes, after backoff — but see note If your quota is the problem, fallback moves the bill; if the provider's capacity is, fallback helps. Distinguish via Retry-After magnitude and whether other routes are also 429ing
QuotaExceeded — QUOTA (credits, spend caps, billing; often arrives as a 429) Only across your own accounts/providers Retrying an empty wallet can't help, but a different provider's account can — if your data policy allows it
AuthFailed, PermissionDenied — AUTH, PERMISSION No A configuration bug on every provider; silent fallback would hide a broken deployment
BadRequest, ContextTooLong — BAD_REQUEST, CONTEXT_TOO_LONG, TOO_LARGE (413 folds into BadRequest in 03.11) No A bug on every provider; fallback doubles the bill for the same failure
UNKNOWN kind / unclassified error — UNKNOWN Only if retryable An error you can't classify may be transient — or your own bug. Let the retryable flag (03.8 classify, LLMError.retryable) decide rather than the class name
Refused / ContentBlocked finish, Truncated (length) — no Kind; a 200 outcome, not an exception No, unless explicitly opted in A refusal may be the correct answer; opt-in is a deliberate product decision, never a default
CircuitOpen Yes — that is its purpose The breaker already decided this route is dead; don't pay its timeout again
DeadlineExceeded Only if budget remains Check deadline.remaining before starting a fallback that itself needs seconds
Silent quality failure (validator fails) Yes — this is a cascade decision The 11B.5 router owns quality-based escalation; a fallback on invalid output is legitimate because the answer is unusable

6.3 The degradation ladder#

When the whole chain is exhausted — or when falling back isn't allowed — the request still needs an answer. The degradation ladder is the ordered list of "less good but honest" outcomes, from best to worst:

flowchart TD
    a["Primary route fails"] --> b{"Fallback chain<br/>exhausted or disallowed?"}
    b -->|"no"| c["Serve fallback answer<br/>marked degraded"]
    b -->|"yes"| d{"Cheap degraded path?<br/>cached answer / smaller model /<br/>retrieval-only summary"}
    d -->|"yes, and labelled"| e["Serve degraded answer<br/>with X-Degraded header + log"]
    d -->|"no"| f{"Async-tolerant?<br/>queue the job"}
    f -->|"yes"| g["202 Accepted + job id;<br/>worker retries later"]
    f -->|"no"| h["Honest error:<br/>503 + Retry-After, user-friendly message"]
Rung Example When it's acceptable Label required?
1. Fallback model/provider OpenAI → Claude, or Claude → OpenAI (a third provider such as Gemini is optional) Transient failure; fallback passed evals Yes — X-Served-By + structured log
2. Smaller/cheaper model Sonnet → Haiku → nano Cost/latency emergency; quality dip acceptable for the task Yes
3. Cached/stale answer Last good answer for this exact query FAQ-style, low-stakes, TTL-bounded Yes — and a freshness note to the user
4. Retrieval-only Return the documents, no synthesis Synthesis is what's failing; user can read sources Implicit — the response shape differs
5. Queued "We'll email you when it's ready" Non-interactive work The 202/job pattern
6. Honest failure "Try again in a minute" + 503 Interactive, no degraded path The message is the label

The cardinal sin is silent degradation: serving a fallback or cached answer that looks identical to a primary answer. Every degraded path must be marked — in the response (X-Served-By, X-Degraded: reason), in logs (which route/model served, why the primary was skipped), and where the user might notice, in the UI.

6.4 Fallbacks and data policy#

A fallback is a different processor. 02.9, Part 9 established that your data goes to whoever serves the model; a fallback to a provider you haven't cleared is a compliance breach, not a resilience win. The rules:

  • The fallback chain is part of the data-flow diagram. If primary is "Anthropic direct, US processing", the fallback "OpenRouter with zdr: true" is only valid if OpenRouter's ZDR endpoints satisfy the same policy — verify per endpoint, not per brand.
  • Regional failover needs regional policy. A EU-residency commitment doesn't survive a failover to a US endpoint. Either the fallback is also EU-resident, or the degraded path is "queue and retry" — not "send it to the US anyway".
  • ZDR/enterprise features may not carry over. Anthropic ZDR requires an arrangement; a fallback to a provider without it silently drops the protection. Check per-route, per-feature (some features — files, batches, stored responses — are never ZDR-eligible on any provider).
  • Log the serving route for audit. "Which processor saw this request" must be answerable after the fact; that's why Response.model_key/provider/resolved_model exist in 03.11.

6.5 Fallback quality and telling the user#

A fallback is an untested model until you test it (03.11, 8.4). Before a fallback ever serves production traffic:

  • Run your eval set on it (Module 10A); a fallback that passes 95% as well as the primary is fine, one that passes 70% is a hidden incident.
  • Check its different failure modes: different refusals, different formatting habits, different tokenizer (different cost and context limits).
  • Decide the UX: does the user see "answered by backup system"? For a support bot, a slightly different tone is fine; for a medical-style FAQ or a legal document summary, the degradation may need to be explicit.

In code, mark every fallback-served response:

python
# Convention: every degraded response carries provenance.
response.headers["X-Served-By"] = f"{route.provider}/{route.model_key}"
if route.is_fallback:
    response.headers["X-Degraded"] = fallback_reason   # e.g. "primary_overloaded"
# and always: log {call_id, alias, model_key, provider, resolved_model,
# attempts:[{route, outcome}]} — 03.11's LoggingHook already emits this shape.

6.6 The FallbackChain implementation#

python
# llm_service/resilience.py (excerpt) — fallback chain with per-route breakers.
from __future__ import annotations

from dataclasses import dataclass, field
from typing import Any, Awaitable, Callable


@dataclass
class Route:
    """One entry in a fallback chain: a name and the callable that serves it."""
    name: str                                  # 'openai/gpt-6-luna', 'anthropic/claude-haiku-5-5'
    call: Callable[[], Awaitable[Any]]
    is_fallback: bool = False
    data_policy_ok: bool = True                # does this route satisfy the request's data policy?


class FallbackChain:
    """Try routes in order; move to the next on an allowed failure.

    `may_fall_back(exc)` is the policy hook — in production it inspects the
    03.11 `LLMError` class (or 03.8 `Failure.kind`). The shipped default fails
    CLOSED (never falls back): override it, but only to *widen* fallback to
    the transient classes in 6.2 — quota/auth/bad-request must not fall back.
    `breaker` is consulted before each route so an open circuit skips it fast.
    """

    def __init__(self, routes: list[Route], *, breaker: "CircuitBreaker | None" = None,
                 may_fall_back: Callable[[BaseException], bool] | None = None,
                 deadline: "Deadline | None" = None) -> None:
        self.routes = routes
        self.breaker = breaker
        self.may_fall_back = may_fall_back or (lambda exc: False)
        self.deadline = deadline
        self.attempts: list[dict] = []

    async def run(self) -> tuple[Any, Route]:
        """Returns (result, serving_route). Raises the last error if all fail;
        if every route was skipped instead, raises DeadlineExceededError (no
        time left) or the last CircuitOpenError. Build one chain per request:
        `attempts` accumulates across run() calls."""
        last_exc: BaseException | None = None
        open_exc: CircuitOpenError | None = None
        out_of_time = False
        for route in self.routes:
            # Every route is checked, the primary included: a route that may not
            # receive this request's data must never be called, whatever its position.
            if not route.data_policy_ok:
                self.attempts.append({"route": route.name, "skipped": "data_policy"})
                continue
            # The breaker enforces open/half-open inside call(); an open
            # circuit surfaces as CircuitOpenError below — no pre-check needed.
            if self.deadline is not None and self.deadline.remaining <= 0.5:
                self.attempts.append({"route": route.name, "skipped": "deadline"})
                out_of_time = True
                break
            try:
                if self.breaker is not None:
                    result = await self.breaker.call(route.name, route.call)
                else:
                    result = await route.call()
                self.attempts.append({"route": route.name, "ok": True})
                return result, route
            except CircuitOpenError as exc:
                self.attempts.append({"route": route.name, "skipped": "circuit_open"})
                open_exc = exc
                continue
            except Exception as exc:
                # Exception, not BaseException: asyncio.CancelledError (client
                # disconnect), KeyboardInterrupt and SystemExit must propagate —
                # a cancellation is not a fallback trigger and must not pay for
                # an answer nobody will read.
                self.attempts.append({"route": route.name, "error": type(exc).__name__})
                last_exc = exc
                if not self.may_fall_back(exc):
                    raise                       # permanent: don't try the next route
                continue
        if last_exc is not None:
            raise last_exc
        if out_of_time:
            raise DeadlineExceededError("no time left to try another route")
        if open_exc is not None:
            raise open_exc
        raise RuntimeError("fallback chain empty or every route skipped by data policy")

The demo with a dead primary and a live fallback:

python
# s6_chain_demo.py — run: uv run python s6_chain_demo.py
import asyncio

from llm_service.resilience import CircuitBreaker, FallbackChain, Route


async def main() -> None:
    calls = {"primary": 0, "backup": 0}

    async def primary() -> str:
        calls["primary"] += 1
        raise TimeoutError("primary timed out")

    async def backup() -> str:
        calls["backup"] += 1
        return "answer from backup"

    chain = FallbackChain(
        routes=[Route("openai/gpt-6-luna", primary, is_fallback=False),
                Route("anthropic/claude-haiku-5-5", backup, is_fallback=True)],
        breaker=CircuitBreaker(),
        may_fall_back=lambda exc: isinstance(exc, (TimeoutError, ConnectionError)),  # policy!
    )
    result, route = await chain.run()
    print("result :", result)
    print("served :", route.name, "(is_fallback:", route.is_fallback, ")")
    print("calls  :", calls)
    print("attempts:", chain.attempts)


asyncio.run(main())
Output4 lines
result : answer from backup
served : anthropic/claude-haiku-5-5 (is_fallback: True )
calls  : {'primary': 1, 'backup': 1}
attempts: [{'route': 'openai/gpt-6-luna', 'error': 'TimeoutError'}, {'route': 'anthropic/claude-haiku-5-5', 'ok': True}]

The chain works in both directions: here OpenAI is the primary and Anthropic Claude the backup. To fail over the other way, swap the two Route entries (Claude primary, OpenAI backup); nothing else changes, because the chain only sees named routes. Treat any third route, such as Gemini, as optional.

6.7 Failures after the first token: streaming calls#

Everything above assumed a call that either returns or raises. A streaming call has a third outcome: it starts, shows the user some text, and then breaks (a dropped connection, a mid-stream overloaded_error, a gateway timeout; 03.3, 7.2 lists each provider's shape). The failover rules change at that moment, because the user has already seen part of an answer and the provider has already billed the tokens it generated (03.3, 7.6). Hosted gateways have the same limit: OpenRouter's errors documentation (checked November 2026) says a failure before any token can be retried on another provider endpoint, but that "failover also stops once part of the answer has reached you", and that a failure after the HTTP 200 is sent arrives as an in-band SSE error event (03.3, 7.2; the models fallback itself is in 9.4).

When the stream fails Fall back invisibly? What to do
Before the first chunk (connect error, 429, 5xx on open, first-token timeout) Yes, same rules as any call (6.2) Next route; the user sees only a slower start
After some text, answer is plain prose Not invisibly Either surface the break (keep the partial text, mark it incomplete, offer "retry") or restart on the next route and tell the UI to clear what it showed. A restart is a different model's answer, so the text can change under the user's eyes
After a tool call was emitted or executed No A restart would repeat or contradict a side effect. Fail the turn, show what completed, and rely on idempotency keys (03.8, Part 11)
Structured output (JSON) cut off No splicing A truncated JSON document is a failed parse; retry the whole call on the same or next route, never stitch two partial outputs together
Client disconnected No Cancel upstream and stop paying (5.2)

Two things not to do: resume by concatenation (asking a second model to "continue" a half-written answer works on neither tone nor facts, and prefill support differs by provider and model), and count a broken stream as a success in your breaker or metrics. Report mid-stream failures to the route's breaker yourself (CircuitBreaker.call wraps a coroutine, not a stream), and tag the request outcome abandoned or failed per 11A.2.

Here is that policy as a small, separate stdlib module (llm_service/stream_fallback.py; it needs nothing from resilience.py):

python
# llm_service/stream_fallback.py — fallback for STREAMING calls (stdlib only).
# Before the first chunk a failed route can be replaced invisibly. After it,
# the user has already seen text: you must reset the answer or surface the break.
from __future__ import annotations

from collections.abc import AsyncIterator, Callable
from contextlib import aclosing
from dataclasses import dataclass


@dataclass
class StreamRoute:
    name: str
    open: Callable[[], AsyncIterator[str]]       # returns a fresh async stream of text chunks


@dataclass
class StreamReset:
    """Yielded in-band when a started stream is abandoned and restarted on the
    next route. The UI must clear what it has shown so far."""
    from_route: str
    to_route: str
    reason: str


class StreamBrokenError(Exception):
    """A stream failed AFTER the first chunk and restarting was not allowed.
    Carries the partial text so the caller can show it, label it, or discard it."""

    def __init__(self, route: str, partial: str, cause: BaseException) -> None:
        super().__init__(f"stream from {route!r} broke after {len(partial)} chars: "
                         f"{type(cause).__name__}")
        self.route, self.partial, self.cause = route, partial, cause


async def stream_with_fallback(
    routes: list[StreamRoute],
    *,
    may_fall_back: Callable[[BaseException], bool],
    restart_after_first_token: bool = False,
) -> AsyncIterator[str | StreamReset]:
    """Yield text chunks from the first route that completes.

    Failure before any chunk: next route, invisibly (if may_fall_back allows).
    Failure after a chunk: raise StreamBrokenError(partial) by default; with
    restart_after_first_token=True yield a StreamReset, drop the partial text
    and restart on the next route. CancelledError is never caught.
    """
    partial: list[str] = []
    last_exc: BaseException | None = None
    for i, route in enumerate(routes):
        started = False
        try:
            # aclosing() closes the upstream stream deterministically when the
            # consumer walks away or an error unwinds, so the connection is released
            async with aclosing(route.open()) as stream:
                async for chunk in stream:
                    started = True
                    partial.append(chunk)
                    yield chunk
            return
        except Exception as exc:
            last_exc = exc
            if not may_fall_back(exc):
                raise
            if started and not restart_after_first_token:
                raise StreamBrokenError(route.name, "".join(partial), exc) from exc
            if started and i + 1 < len(routes):
                yield StreamReset(route.name, routes[i + 1].name, type(exc).__name__)
                partial.clear()
    assert last_exc is not None
    raise last_exc

A demo against fake streams — the same primary fails at three different moments (demo_stream.py):

python
# demo_stream.py — three failure timings against fake streams.
import asyncio

from stream_fallback import (StreamBrokenError, StreamReset, StreamRoute,
                             stream_with_fallback)


def fake(chunks: list[str], fail_after: int | None = None):
    async def open_stream():
        for i, c in enumerate(chunks):
            if fail_after is not None and i == fail_after:
                raise ConnectionError("stream reset by peer")
            await asyncio.sleep(0)
            yield c
    return open_stream


async def collect(routes, **kw) -> str:
    shown = ""
    async for item in stream_with_fallback(routes, may_fall_back=lambda e: isinstance(e, ConnectionError), **kw):
        if isinstance(item, StreamReset):
            print(f"  [UI clears: {item.from_route} -> {item.to_route} ({item.reason})]")
            shown = ""
        else:
            shown += item
    return shown


async def main() -> None:
    backup = StreamRoute("backup", fake(["Refunds ", "take ", "14 days."]))

    print("1) fails before the first chunk -> invisible fallback")
    print("  ->", await collect([StreamRoute("primary", fake(["x"], fail_after=0)), backup]))

    print("2) fails after two chunks, default policy -> the break is surfaced")
    try:
        await collect([StreamRoute("primary", fake(["Refunds ", "take ", "21 days."], fail_after=2)), backup])
    except StreamBrokenError as e:
        print("  StreamBrokenError:", e, "| partial:", repr(e.partial))

    print("3) fails after two chunks, restart allowed -> reset then full answer")
    print("  ->", await collect([StreamRoute("primary", fake(["Refunds ", "take ", "21 days."], fail_after=2)), backup],
                               restart_after_first_token=True))


asyncio.run(main())
Output7 lines
1) fails before the first chunk -> invisible fallback
  -> Refunds take 14 days.
2) fails after two chunks, default policy -> the break is surfaced
  StreamBrokenError: stream from 'primary' broke after 13 chars: ConnectionError | partial: 'Refunds take '
3) fails after two chunks, restart allowed -> reset then full answer
  [UI clears: primary -> backup (ConnectionError)]
  -> Refunds take 14 days.

Case 3 shows why restart is a product decision, not a default: the primary had already told the user "Refunds take ..." and was heading for "21 days" while the backup says "14 days". If two models can disagree on a fact, a visible reset is the honest minimum, and for anything high-stakes the better answer is case 2: keep the partial, label it incomplete, and let the user retry.


Part 7: Rate-limit management at scale#

Deep-dive

7.1 The problem: limits are shared, your limiter isn't#

03.8, Part 9 built a per-process client-side rate limiter and flagged the scaling problem: "Several processes or machines? A per-process limiter can't see the others." At fleet scale the arithmetic is brutal — if the provider allows 500k tokens/min and you run 20 instances each politely self-limiting to 500k/min, you collectively request 10M/min and eat 429s.

The fix is a shared limiter: one token bucket (or equivalent) in shared storage — Redis in production — that all instances atomically check before calling. Two subtleties make LLM rate limiting different from ordinary API limiting:

  1. Limits count tokens, not just requests. Providers meter input and output tokens per minute (and Anthropic splits input/output into separate ITPM/OTPM buckets; OpenAI counts cached tokens toward TPM). A limiter that only counts requests lets one 200k-token prompt blow the minute. The limiter must estimate tokens before the call (03.7, 2.7 covers estimation) and reconcile the estimate against actual usage after (settle() in 7.2 — estimates alone drift).
  2. Backoff must be coordinated. If 500 instances all get a 429 and each independently backs off with jitter, you still get a thundering herd. A shared limiter that slows the whole fleet's admission rate on 429 signals is the coordinated response.

7.2 Design: a shared store behind a tiny interface#

The store protocol is deliberately tiny — try_acquire, refund, and a shared backoff deadline (set_backoff/backoff_until) — so the same limiter works against Redis (EVAL a Lua script for atomicity) or the in-memory fake used in tests:

python
# llm_service/resilience.py (excerpt) — shared rate limiter.
from __future__ import annotations

import asyncio
import time
from dataclasses import dataclass
from typing import Protocol


class TokenStore(Protocol):
    """Atomic check-and-debit plus shared 429 backoff state. Implement with
    Redis (Lua for try_acquire) or the in-memory fake below."""

    async def try_acquire(self, key: str, cost: float, capacity: float, refill_per_s: float) -> bool: ...
    async def refund(self, key: str, cost: float) -> None: ...
    async def set_backoff(self, key: str, until: float) -> None: ...
    async def backoff_until(self, key: str) -> float: ...


class InMemoryTokenStore:
    """Single-process store for tests/dev. NOT safe across instances — that's
    what the Redis implementation is for."""

    def __init__(self) -> None:
        self._buckets: dict[str, tuple[float, float]] = {}   # key -> (tokens, last_refill)
        self._backoff: dict[str, float] = {}                # key -> hold-until (monotonic)
        self._lock = asyncio.Lock()

    async def try_acquire(self, key: str, cost: float, capacity: float, refill_per_s: float) -> bool:
        async with self._lock:
            tokens, last = self._buckets.get(key, (capacity, time.monotonic()))
            now = time.monotonic()
            tokens = min(capacity, tokens + (now - last) * refill_per_s)
            if tokens < cost:
                self._buckets[key] = (tokens, now)
                return False
            self._buckets[key] = (tokens - cost, now)
            return True

    async def refund(self, key: str, cost: float) -> None:
        async with self._lock:
            tokens, _ = self._buckets.get(key, (0.0, time.monotonic()))
            self._buckets[key] = (min(1e9, tokens + cost), time.monotonic())

    async def set_backoff(self, key: str, until: float) -> None:
        async with self._lock:
            self._backoff[key] = max(self._backoff.get(key, 0.0), until)

    async def backoff_until(self, key: str) -> float:
        async with self._lock:
            return self._backoff.get(key, 0.0)


@dataclass
class RateLimitConfig:
    tokens_per_min: float
    max_burst: float = 0.0        # 0 -> capacity = tokens_per_min/60 * 10 (10 s of burst)

    def __post_init__(self) -> None:
        # A NaN or non-positive rate makes every comparison in the bucket false:
        # the limiter would admit everything (or nothing) without saying so.
        if not 0 < self.tokens_per_min < float("inf") or not 0 <= self.max_burst < float("inf"):
            raise ValueError("tokens_per_min must be positive and max_burst >= 0, both finite")


class SharedRateLimiter:
    """Token-bucket limiter backed by a shared store.

    The configure() key IS the bucket key — configure per provider *and* per
    model route ('openai', 'openai/gpt-6-luna', 'tenant:acme'). Charge estimated
    tokens before the call (acquire), reconcile against actual usage after
    (settle), and report 429s (report_429) — the backoff deadline lives in the
    shared store, so every instance slows down, not just the one that saw it.
    """

    def __init__(self, store: TokenStore) -> None:
        self.store = store
        self._configs: dict[str, RateLimitConfig] = {}

    def configure(self, key: str, cfg: RateLimitConfig) -> None:
        self._configs[key] = cfg

    def _capacity(self, cfg: RateLimitConfig) -> float:
        return cfg.max_burst or (cfg.tokens_per_min / 60.0) * 10.0

    async def acquire(self, key: str, est_tokens: float) -> bool:
        """Returns True if the call may proceed. False -> wait or shed."""
        # A negative estimate would mint tokens and NaN would debit nothing.
        if not 0 <= est_tokens < float("inf"):
            raise ValueError(f"est_tokens must be finite and >= 0, got {est_tokens!r}")
        cfg = self._configs.get(key)
        if cfg is None:
            return True                                # unconfigured = unlimited
        if await self.store.backoff_until(key) > time.monotonic():
            return False                               # shared 429 backoff: whole fleet holds
        return await self.store.try_acquire(key, est_tokens,
                                            self._capacity(cfg), cfg.tokens_per_min / 60.0)

    async def settle(self, key: str, charged: float, actual: float) -> None:
        """Reconcile the pre-call estimate against real usage: refund
        over-estimates; debit under-estimates (best-effort — if the bucket is
        already empty the next 429 corrects course)."""
        if not (0 <= actual < float("inf") and 0 <= charged < float("inf")):
            raise ValueError("charged and actual must be finite and >= 0")
        cfg = self._configs.get(key)
        if cfg is None or charged == actual:
            return
        if charged > actual:
            await self.store.refund(key, charged - actual)
        else:
            await self.store.try_acquire(key, actual - charged,
                                         self._capacity(cfg), cfg.tokens_per_min / 60.0)

    async def report_429(self, key: str, retry_after_s: float | None) -> None:
        """Called on a 429: write a shared backoff deadline so the whole
        fleet slows down — every instance reads the same store."""
        if key not in self._configs:
            return
        # Retry-After comes from the provider: clamp it to [0, 60] (max() turns NaN into 0).
        wait = min(max(0.0, retry_after_s) if retry_after_s is not None else 5.0, 60.0)
        await self.store.set_backoff(key, time.monotonic() + wait)

Demo:

python
# s7_limiter_demo.py — run: uv run python s7_limiter_demo.py
import asyncio

from llm_service.resilience import InMemoryTokenStore, RateLimitConfig, SharedRateLimiter


async def main() -> None:
    store = InMemoryTokenStore()
    # Two "instances" = two limiter objects sharing ONE store — as Redis would
    # be shared across machines. Each configures the same bucket key.
    limiter_a = SharedRateLimiter(store)
    limiter_b = SharedRateLimiter(store)
    for lim in (limiter_a, limiter_b):
        lim.configure("openai", RateLimitConfig(tokens_per_min=600, max_burst=100))  # 10 tok/s

    for i, (name, lim) in enumerate([("A", limiter_a), ("B", limiter_b),
                                     ("A", limiter_a), ("B", limiter_b)]):
        got = await lim.acquire("openai", est_tokens=50)
        print(f"inst{i} ({name}): {'admitted (50 tok)' if got else 'throttled'}")

    # A 429 seen by instance A is written to the shared store — B is held too.
    await limiter_a.report_429("openai", retry_after_s=10)
    got = await limiter_b.acquire("openai", est_tokens=1)
    print("after 429 on A:", "B admitted" if got else "B held by shared backoff")


asyncio.run(main())
Output5 lines
inst0 (A): admitted (50 tok)
inst1 (B): admitted (50 tok)
inst2 (A): throttled
inst3 (B): throttled
after 429 on A: B held by shared backoff

7.3 Tenant fairness#

A shared limiter protects the provider; per-tenant sub-limits protect tenants from each other. The pattern is a two-level scheme: a global bucket per provider/model (capacity = your real quota headroom) and a per-tenant bucket keyed tenant:{id} (capacity = fair share). Acquire tenant first, then global — a tenant that exhausts its share is throttled without touching the global pool, and noisy-neighbour protection survives even when the global pool has headroom.

7.4 Per-model keys, quota headroom and when to upgrade instead#

Three refinements that turn the limiter from a demo into production policy:

Per-model limits, not just per-provider. Providers publish rate limits per model (and per model class on Anthropic), and a single "openai" bucket under-provisions your cheap models while over-admitting your expensive ones. configure() accepts any key, so key the bucket by the route you actually call:

python
limiter.configure("openai/gpt-6-luna", RateLimitConfig(tokens_per_min=2_000_000))
limiter.configure("openai/gpt-6.1-sol", RateLimitConfig(tokens_per_min=400_000))
# derive the key from the request's model alias per call — the limiter never
# sees a request it wasn't configured for (unconfigured = unlimited, so log it)

Keep the numbers sourced from the provider's own limit pages (03.8, 9.1–9.2) — they are per account and per tier, so read your real values from the rate-limit headers (03.8, 9.3) rather than a table, and treat the limiter config as production config that changes with your tier.

Quota monitoring is a leading indicator, not a 429. Waiting for 429s means you're always reacting at the boundary. Two cheaper signals: (a) the rate-limit headers on every response tell you remaining quota per window — sample them into your metrics and alert on headroom (e.g. "<15% of TPM remaining for 10 min") before you hit the wall; (b) provider usage/quota endpoints and dashboards (03.8, 9.2 lists where each provider exposes them; spend/budget dashboards are 11A.2's subject). An alert on "approaching quota" buys you the option to shed load, queue batch work, or buy headroom before users see errors.

Sometimes the fix isn't engineering — it's a tier. When your sustained demand structurally exceeds your plan's quota, no limiter tuning helps: the honest options are a higher provider tier (limits rise automatically with spend on OpenAI/Anthropic/Gemini — see the tier tables in 03.8, 9.2), committed capacity or provisioned throughput where offered (Vertex AI Provisioned Throughput is the canonical example — it trades a committed spend for dedicated, reserved capacity; check the current terms for what it does and does not guarantee), reserved quota, or a second provider account. Treat "request a quota increase / upgrade tier" as a first-class remediation in your runbook, with the trigger being your quota-headroom alert — and record which limit you're actually hitting, because providers enforce several dimensions at once (RPM and TPM and daily caps) and the binding one is rarely the one you assumed.


Part 8: Health checks, canaries and chaos testing#

Deep-dive

8.1 Three kinds of health check#

Check Question Implementation Frequency
Liveness Is the process alive? GET /healthz → 200 if the event loop responds Every few seconds (orchestrator)
Readiness Can it serve now? Dependencies reachable: DB, vector store, config loaded, breaker states not all-open Every few seconds; gate traffic on it
Model canary Do the models still answer correctly? A tiny fixed eval (3–5 prompts with known-good answers) run on a schedule against each route Every 5–15 min, plus on deploy and on provider announcements

The model canary is the LLM-specific one and the easiest to get wrong. It must be tiny but real: prompts that exercise the features you depend on (structured output, tool calling, long context, refusal behaviour), graded by deterministic checks where possible (schema validates, contains expected substring) rather than another model call. A canary that costs $0.001 per run per route is cheap insurance against "the model silently changed".

8.2 Synthetic probes#

Beyond canaries, synthetic probes are scheduled requests that exercise the whole path — auth, rate limit, retrieval, generation, response shape — from outside your service, exactly as a user would. They belong to 11A.2's alerting story (a probe failure is an alert), but the design is reliability: a probe that only checks /healthz will never notice that the model started returning refusals.

8.3 The chaos suite#

Chaos testing is deliberate fault injection: break your dependencies in controlled ways and verify the resilience stack actually works. For LLM services the faults are specific and documented:

Fault Injects What it proves
Provider timeout asyncio.sleep(forever) or a never-resolving future Deadline fires, breaker counts it, fallback engages
429 slow-down Raise a fake RateLimitError-shaped exception Backoff honoured, shared limiter throttles, no retry storm
429 out-of-money Raise quota/billing-shaped exception No retry, no fallback — fails fast and alerts
Malformed JSON in a 200 Return "{not json" from a "successful" call Outcome check catches it before parsing (03.8, Part 10)
Truncated stream Stream that ends mid-token with finish_reason: length Stream accumulator handles partial output honestly
Slow first token Sleep 30 s before first delta TTFT timeout vs total timeout distinction; hedging decision
Refusal Return a refusal finish reason Fallback does not engage (unless opted in)
Half-open stampede Many concurrent calls during cooldown Exactly one probe goes through; rest fast-fail

The chaos suite reuses the same FlakyProvider pattern as the breaker demo, but drives the whole FallbackChain + CircuitBreaker + Deadline stack:

python
# tests/test_chaos.py — chaos suite for llm_service.resilience.
# Run: uv run pytest tests/test_chaos.py -v   (stdlib + pytest + pytest-asyncio)
import asyncio

import pytest

from llm_service.resilience import (
    BreakerConfig, BreakerState, CircuitBreaker, CircuitOpenError, Deadline, DeadlineExceededError,
    FallbackChain, Route,
)


class ScriptedProvider:
    """A provider that replays a script of outcomes, one per call."""

    def __init__(self, script: list[str]) -> None:
        self.script = list(script)
        self.calls = 0

    async def __call__(self) -> str:
        self.calls += 1
        step = self.script.pop(0) if self.script else "ok"
        if step == "timeout":
            await asyncio.sleep(3600)          # would hang forever without a deadline
        if step == "fail":
            raise ConnectionError("provider unreachable")
        if step == "429":
            raise TimeoutError("rate limited (modelled)")
        if step == "bad_json":
            return "{this is not json"
        return f"ok-{self.calls}"


def may_fall_back(exc: BaseException) -> bool:
    """The production policy, simplified: transient classes fall back;
    'permanent' markers never do."""
    return not isinstance(exc, ValueError)   # ValueError models a permanent failure


@pytest.mark.asyncio
async def test_chaos_timeout_falls_back():
    """Primary hangs forever; deadline + breaker + fallback must still answer."""
    primary = ScriptedProvider(["timeout"])
    backup = ScriptedProvider(["ok"])
    breaker = CircuitBreaker(BreakerConfig(window=5, min_calls=2, failure_rate=0.5))
    chain = FallbackChain(
        [Route("primary", primary), Route("backup", backup, is_fallback=True)],
        breaker=breaker, may_fall_back=may_fall_back)
    # Wrap primary so its 'timeout' step raises quickly instead of sleeping:
    async def primary_guarded():
        try:
            return await asyncio.wait_for(primary(), timeout=0.05)
        except TimeoutError as exc:
            raise ConnectionError("modelled timeout") from exc
    chain.routes[0].call = primary_guarded
    result, route = await chain.run()
    assert result.startswith("ok-")
    assert route.name == "backup"
    assert chain.attempts[0]["route"] == "primary"


@pytest.mark.asyncio
async def test_chaos_permanent_failure_never_falls_back():
    """A permanent failure (bad request) must NOT try the fallback."""
    primary = ScriptedProvider(["fail"])
    backup = ScriptedProvider(["ok"])

    async def bad_request():
        raise ValueError("400 malformed request")

    chain = FallbackChain(
        [Route("primary", bad_request), Route("backup", backup, is_fallback=True)],
        may_fall_back=may_fall_back)
    with pytest.raises(ValueError):
        await chain.run()
    assert backup.calls == 0          # the fallback was never touched


@pytest.mark.asyncio
async def test_chaos_deadline_stops_everything():
    """An exhausted deadline prevents even the fallback from starting."""
    primary = ScriptedProvider(["fail"])
    backup = ScriptedProvider(["ok"])
    dl = Deadline(budget_s=0.0)       # already spent
    chain = FallbackChain(
        [Route("primary", primary), Route("backup", backup, is_fallback=True)],
        deadline=dl, may_fall_back=may_fall_back)
    with pytest.raises(DeadlineExceededError):
        await chain.run()
    assert backup.calls == 0


@pytest.mark.asyncio
async def test_chaos_breaker_opens_and_skips_dead_route():
    """Failures open the breaker; the chain then skips the dead route without
    calling it, and a successful half-open probe closes the breaker again."""
    dead = ScriptedProvider(["fail"] * 3)   # then serves "ok-N" — the provider healed
    alive = ScriptedProvider(["ok"])
    breaker = CircuitBreaker(BreakerConfig(window=5, min_calls=3,
                                           failure_rate=0.6, cooldown_s=0.05))
    chain = FallbackChain(
        [Route("dead", dead), Route("alive", alive, is_fallback=True)],
        breaker=breaker, may_fall_back=may_fall_back)

    # Phase 1: enough failures to open the breaker (3 fails -> rate 1.0 >= 0.6).
    for _ in range(4):
        await chain.run()
    assert breaker.state("dead") is BreakerState.OPEN

    # Phase 2: open breaker — the dead route is skipped WITHOUT a provider call.
    calls_before = dead.calls
    _, route = await chain.run()
    assert route.name == "alive"
    assert dead.calls == calls_before

    # Phase 3: cooldown elapses -> one probe -> dead now answers -> CLOSED.
    await asyncio.sleep(0.08)
    result, route = await chain.run()
    assert route.name == "dead"
    assert result.startswith("ok-")
    assert breaker.state("dead") is BreakerState.CLOSED


@pytest.mark.asyncio
async def test_chaos_cancellation_never_falls_back():
    """A cancelled call (client disconnect) must propagate — the chain must
    NOT 'fall back' and pay for an answer nobody will read."""
    backup = ScriptedProvider(["ok"])

    async def hanging_primary():
        await asyncio.sleep(3600)

    chain = FallbackChain(
        [Route("primary", hanging_primary), Route("backup", backup, is_fallback=True)],
        may_fall_back=lambda exc: True)          # even the permissive policy
    task = asyncio.create_task(chain.run())
    await asyncio.sleep(0.02)
    task.cancel()
    with pytest.raises(asyncio.CancelledError):
        await task
    assert backup.calls == 0                     # no fallback route was invoked

Run it:

bash
uv run pytest tests/test_chaos.py -v
Output · pytest -v, abbreviated to the test lines5 lines
tests/test_chaos.py::test_chaos_timeout_falls_back PASSED
tests/test_chaos.py::test_chaos_permanent_failure_never_falls_back PASSED
tests/test_chaos.py::test_chaos_deadline_stops_everything PASSED
tests/test_chaos.py::test_chaos_breaker_opens_and_skips_dead_route PASSED
tests/test_chaos.py::test_chaos_cancellation_never_falls_back PASSED

Attack tests that need no extra packages. The chaos suite above uses pytest. These four use only unittest and hold fixes for failures a happy-path test never sees: a breaker configured so it can never trip (min_calls larger than window means the outcome window never reaches min_calls; a NaN failure rate compares false with everything), a half-open probe that never returns (it held the single probe slot for ever, so the circuit stayed open: probe_timeout_s is now enforced), a route flagged data_policy_ok=False placed first in the chain (only fallbacks were checked, so the primary was called anyway), and hostile numbers fed to the rate limiter (a negative estimate minted tokens; NaN debited nothing). Save as test_resilience_attacks.py beside llm_service/:

python
# test_resilience_attacks.py — misconfigurations and hostile values for resilience.py.
# Run beside llm_service/: python3 -m unittest test_resilience_attacks -v
import asyncio
import unittest

from llm_service.resilience import (
    BreakerConfig, CircuitBreaker, CircuitOpenError, FallbackChain, PriorityQueue,
    RateLimitConfig, Route, SharedRateLimiter, InMemoryTokenStore,
)


class ResilienceAttackTests(unittest.TestCase):
    def test_a_breaker_that_could_never_trip_is_refused(self):
        for bad in ({"window": 0}, {"min_calls": 30}, {"failure_rate": float("nan")},
                    {"failure_rate": 0}, {"cooldown_growth": 0.5}):
            with self.assertRaises(ValueError):
                BreakerConfig(**bad)

    def test_a_hung_probe_cannot_hold_the_breaker_open_for_ever(self):
        async def scenario():
            now = [0.0]
            breaker = CircuitBreaker(BreakerConfig(window=2, min_calls=1, cooldown_s=10,
                                                   probe_timeout_s=0.05),
                                     clock=lambda: now[0])

            async def failing():
                raise RuntimeError("down")

            async def hanging():
                await asyncio.sleep(60)

            with self.assertRaises(RuntimeError):
                await breaker.call("k", failing)         # opens the circuit
            now[0] = 11                                  # cooldown over: one probe allowed
            with self.assertRaises(TimeoutError):
                await breaker.call("k", hanging)         # the probe is cut off...
            now[0] = 100
            with self.assertRaises(RuntimeError):        # ...so the next probe is allowed
                await breaker.call("k", failing)
        asyncio.run(scenario())

    def test_a_route_that_may_not_see_the_data_is_never_called_even_first(self):
        async def scenario():
            calls = []

            async def forbidden():
                calls.append("a")

            async def allowed():
                return "ok"

            chain = FallbackChain([Route("a", forbidden, data_policy_ok=False),
                                   Route("b", allowed)])
            result, route = await chain.run()
            self.assertEqual((result, route.name, calls), ("ok", "b", []))
        asyncio.run(scenario())

    def test_hostile_token_numbers_are_refused(self):
        async def scenario():
            limiter = SharedRateLimiter(InMemoryTokenStore())
            limiter.configure("m", RateLimitConfig(600))
            for bad in (float("nan"), -5.0, float("inf")):
                with self.assertRaises(ValueError):
                    await limiter.acquire("m", bad)
        asyncio.run(scenario())
        with self.assertRaises(ValueError):
            RateLimitConfig(float("nan"))
        with self.assertRaises(ValueError):
            PriorityQueue(0)


if __name__ == "__main__":
    unittest.main()

Run python3 -m unittest test_resilience_attacks -v and you get real output (the timing differs):

text
test_a_breaker_that_could_never_trip_is_refused ... ok
test_a_hung_probe_cannot_hold_the_breaker_open_for_ever ... ok
test_a_route_that_may_not_see_the_data_is_never_called_even_first ... ok
test_hostile_token_numbers_are_refused ... ok

----------------------------------------------------------------------
Ran 4 tests in 0.052s

OK

Limits that remain: the breaker and the in-memory token store live in one process (share state through Redis for a fleet), a breaker's is_failure predicate that raises is counted as a failure rather than hiding an outage, and the fallback chain trusts the data_policy_ok flag you set on each route: it does not inspect the request.

8.4 Game days#

Beyond automated chaos, game days are scheduled rehearsals: pick a scenario ("OpenAI is down for 20 minutes"), inject it in staging or a canary environment, and watch whether alerts fire, fallbacks engage, on-call knows what to do, and the runbook works. The deliverable isn't the test passing — it's the human learning where the plan breaks. Link to 11C.4 for incident practice and post-incident reviews.


Part 9: LLM gateways#

Deep-dive

9.1 What a gateway is#

An LLM gateway is a proxy or service that sits between your applications and the model providers: your code speaks one API (usually OpenAI-compatible), and the gateway handles routing, retries, fallbacks, caching, rate limits, budgets, key management, logging and guardrails. It is the same idea as an API gateway for REST services, specialised for LLM traffic — where "the upstream" is dozens of models with different shapes, prices and failure modes.

flowchart LR
    subgraph apps ["Your applications"]
        a1["service A"] & a2["service B"] & a3["agent workers"]
    end
    apps --> gw{"LLM gateway<br/>auth · routing · retries<br/>fallbacks · budgets · logging"}
    gw --> p1["OpenAI"] & p2["Anthropic"] & p3["Gemini"] & p4["OpenRouter /<br/>self-hosted models"]

The reliability argument for a gateway: one place to enforce fallbacks, retries, budgets and keys for all your services and languages, instead of re-implementing (or forgetting) them per app. The risk argument: another hop, another dependency, another attack surface — and a gateway that retries and your app that retries is the double-retry trap at fleet scale.

9.2 The landscape as of November 2026#

Verified against official docs/pages on 4–6 November 2026; the rows other than Portkey and Agent Router were checked again on 14 November 2026; the Bifrost and TensorZero rows and the library table in 9.2b were checked on 14 November 2026. "Self-host" = you run it; "Hosted" = vendor-run.

Gateway Licence / model Deployment Fallbacks & retries Rate limits & budgets Caching Guardrails / observability Notable caveats
LiteLLM proxy MIT; Python (enterprise features under a separate commercial licence) Self-host (Docker/litellm --config) or LiteLLM Cloud fallbacks, num_retries, allowed_fails/cooldown_time per deployment; routing strategies incl. least-busy, latency-based-routing Virtual keys, per-key/team budgets & TPM/RPM, redis_host for shared state Exact + Redis semantic cache Guardrails framework, spend logs, success/failure callbacks (Langfuse etc.) March 2026 PyPI supply-chain incident (1.82.7/1.82.8, live on 24 March for about 40 minutes before PyPI quarantined them; 1.82.6 and earlier and the official Docker image were not affected, and clean releases resumed at 1.83.0, per LiteLLM's security notice); heavy dep tree; makes own HTTP calls for many providers (03.11, 13.2, 13.9)
Portkey AI Gateway MIT (OSS gateway); hosted plans extra Self-host (Node/Bun/Docker/Cloudflare Worker) or Portkey cloud Automatic retries (≤5), fallbacks on chosen errors, load balancing, per-strategy circuit breaker, request timeouts Rate limits per provider (req/token per hour, Redis-shared); budgets/virtual keys on hosted In-memory + semantic cache 20+ deterministic + LLM guardrails; extensive logging Acquired by Palo Alto Networks (closed 29 May 2026, per its press release), which plans to make it the gateway layer of its Prisma AIRS platform; the OSS repository's last push was 25 May 2026 (GitHub, checked 12 November 2026)
OpenRouter Hosted aggregator (not OSS) Vendor-run endpoint Server-side models fallback list + provider routing (order, only, sort, require_parameters) Account credits, key limits; :free tier limits Provider-side prompt caching passes through Pass-through logging opt-in; data_collection/zdr routing controls 5.5% credit-purchase fee (8% Business); a data processor; errors inside HTTP 200; fallbacks can trigger on any error incl. moderation (02.9, 5.4, 03.11, 13.8)
Cloudflare AI Gateway Hosted (Cloudflare account); analytics Edge, global Fallback chain on the Universal endpoint (ordered request array, triggered by an error or a timeout); model aliases & dynamic routes Rate limiting (fixed/sliding window), spend limits per model/provider/metadata Exact-match response cache (SHA-256 key, TTL 60 seconds to one month, cf-aig-cache-* headers; opt-in) Guardrails (prompt+response moderation), request logs, GraphQL analytics Cache is exact-match only (semantic caching is not offered); tied to Cloudflare ecosystem; core features are free but logs are capped (100,000 on Workers Free), guardrails bill as Workers AI inference and Unified Billing adds a 5% credit fee
Vercel AI Gateway Hosted Vendor-run Provider failover by default; order/only/sort; model fallbacks (models array) Budgets per team/project/API-key/member; BYOK caching: 'auto' for providers needing explicit markers Request logs (status, provider attempts, tokens, cost); zero markup on token prices Hosted only (no self-host); callable from any language through its OpenAI- and Anthropic-compatible APIs, though examples lean on the AI SDK; budgets cover only spend billed through Vercel's provider keys (BYOK spend is metered separately), and an exceeded budget returns HTTP 402
Kong AI Gateway Kong Gateway plugins / Konnect (AI Proxy Advanced is Enterprise-only; check which tier your plugins need) Self-host Kong or Konnect SaaS AI Proxy Advanced (Kong Gateway 3.8+): round-robin/weighted, consistent-hashing, lowest-latency, lowest-usage, semantic and priority balancing, retries and failover; 4xx errors don't fail over unless failover_criteria says so Rate limiting via Kong plugins; per-consumer quotas Via plugins Full Kong plugin ecosystem (auth, ACL, observability); AI Gateway 2.x first-class entities Heavier infra (Kong itself); config is Kong-native, not LLM-specific
Helicone AI Gateway OSS (Rust; licence ambiguous, see caveats) + hosted platform; ownership unclear, see caveats Self-host Docker or Helicone cloud Automatic failover across providers; smart routing (latency/cost/uptime-aware) Rate limits per user/team/global (requests, tokens, dollars) Response cache (Redis/S3), up to ~95% claimed Full Helicone observability + OTel support Labelled Public Beta; the repo's latest release is v0.2.0-beta.30 (July 2025) and its last push was November 2025 (GitHub, 14 November 2026); Helicone's homepage banner (14 November 2026) reads "Helicone is now part of Experiential Labs. Details to come soon", and third-party reports of a Mintlify acquisition and maintenance mode were not confirmed on Helicone's own pages, so check the vendor's roadmap before adopting it; the README badge says Apache but GitHub detects GPL-3.0, so read the LICENSE before embedding; "0% markup" is a hosted claim; verify self-host feature parity
Amazon Bedrock AgentCore Gateway AWS managed service (Bedrock AgentCore); not OSS Managed AWS service in your account/region; no self-host Model-based routing across inference targets (Bedrock, OpenAI, Anthropic, any OpenAI-compatible endpoint); request interceptors can rewrite model; gateway rules (matchModels + routeToTarget) can pin a model to a target and add an ordered fallback chain (1 to 2 alternatives, triggered by chosen status codes such as 429/5XX, connection errors, first-byte timeouts or unroutable targets, with a per-route circuit breaker; added October 2026); no fallback once a streamed response has started; each attempt bills as a gateway invocation IAM auth + Token Vault credential abstraction; AgentCore Policy fine-grained access control; configurable rate limits (added August 2026) including tokens per minute scoped by dimensions such as qualified model ID (fail-open by default); no virtual-key/team budget model like LiteLLM Not documented Bedrock Guardrails + AgentCore Policy on inference traffic; built-in observability/audit; OpenAI and Anthropic SDK-compatible /inference endpoint with dialect translation AWS-only; also an MCP tool gateway and A2A passthrough — inference targets are one of several target types, so it's broader than an LLM-only gateway; fallback and rate limiting are recent additions (October and August 2026), so check the limits (for example 1 to 2 fallback targets per rule) against your needs
Azure API Management Azure service Cloud (your subscription) Backend pools with load balancing (round-robin, weighted, priority-based, session-aware) and circuit breakers; unified model API (preview) adds model failover across providers llm-token-limit policy: TPM + token quotas per key; subscription keys Semantic caching (llm-semantic-cache-* + embeddings backend) Azure AI Content Safety integration; APIM analytics Azure-hosted (it can front Bedrock and other providers); policy XML; the unified model API is in preview and still rolling out; semantic cache needs Azure Managed Redis (or a RediSearch-compatible external cache) plus an embeddings backend
Google Apigee Google Cloud service Cloud / hybrid GKE Cross-provider fallback via target fault rules (any non-2xx target response counts as a failure); dynamic model routing by model name Spike arrest, quotas, API-key/OAuth/JWT Semantic cache backed by Agent Platform Vector Search Model Armor prompt/response sanitization; Sensitive Data Protection Google Cloud ecosystem; YAML template config
Agent Router (formerly Envoy AI Gateway) Apache-2.0; AAIF/LF project Standalone binary (aigw run), dedicated gateway, or Kubernetes (Envoy Gateway data plane) Quotas, routing, automatic failover via Envoy Token-based rate limiting, quotas Via Envoy filters OTel; MCP/A2A governance; production adopters incl. Bloomberg, Tetrate, Tencent Cloud, Nutanix, LY Corporation You operate the gateway yourself; deepest integration on Kubernetes; renamed Sept 2026
Bifrost (Maxim) Apache-2.0; Go (GitHub: maximhq/bifrost); some features enterprise-only (per its docs: guardrails, adaptive routing, clustering, RBAC, in-VPC deployment, audit logs) Self-host (npx, Docker, Helm/Kubernetes, Terraform) or embed as a Go library; built-in web UI Ordered fallbacks array per request: it moves to the next entry when the primary fails after its retries, and provider timeouts count; per-provider retries are configured in network_config with exponential backoff and jitter, and the documented default is max_retries: 0; weighted load balancing across API keys, and a 429 rotates to another key Virtual keys with budgets and rate limits at key, team and customer level Semantic caching (hash lookup first, then similarity) that needs a vector store (Redis/Valkey, Qdrant or Pinecone); entries are scoped by cache key and by identity by default Prometheus metrics, OpenTelemetry tracing, request logging; guardrails integrations (Bedrock Guardrails, Azure Content Safety, Model Armor, Patronus AI) are enterprise-only Retries are off until you set them; the README's overhead figures (for example 11 µs per request at 5,000 requests per second on a t3.xlarge) are the project's own benchmark, not reproduced here; the README and the docs disagree on whether the MCP gateway is open-source or enterprise, so check the docs for the tier of any feature you depend on; actively developed (last push 14 November 2026, GitHub)
TensorZero Apache-2.0; Rust core (GitHub: tensorzero/tensorzero); no hosted gateway (a paid "Autopilot" product is separate) Self-host: the gateway is one Docker container; optional Postgres or ClickHouse (ClickHouse for higher volume, per its docs) for inference and feedback storage, plus a UI Three levels: model provider routing (a routing list tried in order), variant retries, and function-level variant fallbacks; timeouts apply per attempt; weighted variant sampling for experiments Custom rate limits (scopes such as tags); auth so clients use the gateway without holding provider keys Exact-match inference cache with modes off (default), on, write_only and read_only Stores inferences and feedback in your database; OpenTelemetry trace export and Prometheus metrics; built-in evaluations and adaptive A/B tests Repository archived by its owner on 12 June 2026 (GitHub API, checked 14 November 2026; last release 2026.6.0 on 4 June 2026) and its website says it "remains available on GitHub but is no longer maintained"; Apache-2.0 means you can fork and self-host, but you would own every fix; the README's "<1ms p99 latency" is the project's own claim; better read as a reference design for combining gateway, evals and experiments than as a default pick for new production
Self-built thin gateway Yours Your infra Whatever you implement (this lesson's resilience.py is the core) Whatever you implement Whatever you implement Whatever you implement Zero new supply-chain risk; you own every bug; best for 2–4 providers where 03.11's client suffices

9.2b Library-level options (no proxy to run)#

Not every "one API for many models" tool is a gateway. These five are libraries: they run inside your process, so there is no extra hop and no proxy to patch, but also no central place for keys, budgets or shared rate-limit state. Each service that imports one carries its own copy of the policy. 03.11, Part 13 compares the Python ones in depth; this table is the reliability view.

Library Language What it unifies What it does NOT give you Pick it over a gateway when
Vercel AI SDK TypeScript (npm ai, Apache-2.0) Text generation, structured objects, tool calls and agents behind one API; models named provider/model, with direct provider packages (for example @ai-sdk/openai) or Vercel AI Gateway (@ai-sdk/gateway); UI hooks for chat interfaces Central keys, budgets or shared limits: those exist only if you route through a gateway, and the SDK's default global provider is Vercel's. Cross-provider failover comes from that gateway (or your code), not from the SDK's provider layer One or a few TypeScript or Next.js apps, UI streaming matters, and no platform team will run a proxy
any-llm (Mozilla AI) Python (any-llm-sdk, Apache-2.0) completion and responses calls across providers, built on the official provider SDKs, models named provider:model Central keys, budgets, usage tracking or multi-tenant support: Mozilla ships those as a separate self-hosted gateway (Otari, which calls providers through any-llm, per its README) A Python-only app that wants a thin layer over official SDKs, with a first-party route to a gateway if a second team needs shared budgets
aisuite Python (aisuite, MIT) A Chat Completions-style interface across providers, provider:model names, a tool-call loop helper and MCP tools; provider SDKs are optional extras Its README documents no fallbacks, budgets or central keys; pre-1.0 (latest release v0.1.3, 20 July 2026; last push 18 September 2026, GitHub) Prototypes and small Python scripts where a minimal, readable wrapper beats a framework
LangChain init_chat_model Python (langchain, MIT) and JavaScript (initChatModel) One function returns a chat model for a provider:model string, with the model selectable at call time through runtime config; you install the matching provider extra (for example langchain[openai]) Gateway features, and a fallback chain (the docs page checked describes max_retries and per-request model selection through middleware, not failover); brings LangChain's dependency tree The app already runs on LangChain or LangGraph, so the model factory costs nothing extra
Pydantic AI Python (pydantic-ai, MIT) Typed agents and outputs across many providers, provider:model names, and a FallbackModel that tries the next model on API errors (4xx/5xx, connection failures and timeouts before the response starts, configurable through fallback_on) State shared across instances or services: the fallback is in-process. Keys and spending limits live in its separate hosted Pydantic AI Gateway (gateway/ model prefix) Python agents that want typed outputs and in-process fallback without running a proxy; your own breaker and limiter still belong around it

Two honest observations. First, a library gives you the first layer of 2.2, not the second: even Pydantic AI's FallbackModel is the application layer of the defence in this lesson, so the "retries live in one layer" rule applies to it exactly as it does to your own resilience.py. Second, libraries and gateways compose: the Vercel AI SDK defaults to a gateway, and Otari uses any-llm for its provider calls. Choosing a library is a decision about where the client code lives, and choosing a gateway is a decision about where policy lives.

9.3 Build, buy or gateway — the decision#

03.11, 1.4 already framed this; the system-level version:

  • Own thin wrapper (03.11 client + resilience.py): 2–4 providers, text/tools/JSON are 90% of calls, team wants to read every byte. Cheapest in dependencies, most work in features.
  • Gateway (LiteLLM proxy, Portkey, Kong, Bifrost, Agent Router): several services/teams/languages need central keys, budgets, logging and policy server-side; a platform team exists to run it. Adds a critical hop you must operate and patch.
  • Hosted aggregator/gateway (OpenRouter, Cloudflare, Vercel, Helicone cloud): speed and breadth over control; a third party sees your prompts (a data processor — 02.9, 9.3); fees apply.
  • Cloud-provider gateway (Azure APIM, Google Apigee, Amazon Bedrock AgentCore Gateway): when you're already all-in on one cloud, its managed gateway keeps keys, policy and observability inside your existing tenancy — AgentCore Gateway is the AWS answer, fronting Bedrock plus OpenAI/Anthropic/OpenAI-compatible inference targets behind one endpoint with credential abstraction and Guardrails, but it's AWS-only, and its fallback chains (gateway rules, October 2026) and rate limits (August 2026) are newer and narrower than LiteLLM's or Portkey's.
  • Newer self-hosted gateways and the library tier: Bifrost has the same shape as LiteLLM's proxy (self-hosted, Apache-2.0, virtual keys, budgets, ordered fallbacks) in Go instead of Python, which makes it a candidate when you want central control without a Python dependency tree; weigh which features sit in its enterprise tier, remember that retries default to off, and treat its overhead numbers as the vendor's own. TensorZero is a different shape (gateway plus observability, evaluations and A/B experiments, with provider routing, variant retries and fallbacks), but its repository was archived in June 2026, so use it as a reference design or a fork-and-own decision, not as a default for new production. The five libraries in 9.2b skip the hop entirely and suit single-language apps; move to a gateway when a second team or language needs shared keys, budgets and rate-limit state, and keep the library for the call itself.
  • Composed: the common production answer — app-level resilience.py for per-request policy and a gateway for central keys/budgets, with retries owned by exactly one layer. What changes inside your client once a gateway sits in front of it (model aliases, which layer retries, where usage and cost are read) is listed in 03.11, 13.8b.

9.4 Config examples#

LiteLLM proxy config.yaml (reference, unrun — verify current keys on the docs):

yaml
# LiteLLM proxy config.yaml — reference, unrun. Keys drift between versions;
# verify against docs.litellm.ai/docs/proxy/configs before copying.
model_list:
  # Two deployments may share a model_name -> the router load-balances and
  # cools down individual deployments inside the group.
  - model_name: fast-chat
    litellm_params:
      model: anthropic/claude-haiku-5-5
      api_key: "os.environ/ANTHROPIC_API_KEY"
  # A DIFFERENT model_name is a different model group: fallbacks map groups.
  - model_name: fast-chat-backup
    litellm_params:
      model: openai/gpt-6-luna
      api_key: "os.environ/OPENAI_API_KEY"
      rpm: 500
litellm_settings:
  num_retries: 2            # LiteLLM's own retry loop (router-wide default)
  request_timeout: 60
router_settings:            # router behaviour lives HERE, not in litellm_settings
  routing_strategy: least-busy                  # or latency-based-routing, usage-based-routing
  fallbacks: [{"fast-chat": ["fast-chat-backup"]}]   # group -> fallback group(s), in order
  allowed_fails: 3           # cool a deployment down after >3 fails
  cooldown_time: 30          # seconds in cooldown (writing these under
                             # litellm_settings silently does nothing)
general_settings:
  master_key: "os.environ/LITELLM_MASTER_KEY"

The sample routes Claude first and fails over to OpenAI; swap the two model: lines to fail over in the other direction, with OpenAI first.

Two distinct mechanisms are visible here: deployments sharing model_name: fast-chat fail over between each other via load balancing + cooldowns, while fallbacks moves the whole request to a different model group — and, with the OpenAI deployment, a different provider. Which layer retries matters: LiteLLM's num_retries is its own loop, and the provider SDKs' retries are pinned off so one request can't become (1 + N)² upstream calls.

OpenRouter server-side fallback (optional gateway) (already in 02.9, 5.4; shown for the reliability layer): send extra_body={"models": [...]} and the gateway retries the next model before committing to a response — but remember it can fall back on any error including moderation, and failover stops once streaming starts.

Minimal FastAPI gateway skeleton (reference, unrun): a thin OpenAI-compatible proxy that adds auth, a shared rate limiter and a fallback chain — the "self-built" option:

python
# gateway/app.py — minimal LLM gateway skeleton (reference, unrun).
# One OpenAI-compatible endpoint; resilience.py does the heavy lifting.
from fastapi import FastAPI, Request
from pydantic import BaseModel
import httpx, os

from llm_service.resilience import CircuitBreaker, FallbackChain, Route

app = FastAPI()
breaker = CircuitBreaker()

class ChatIn(BaseModel):
    model: str
    messages: list[dict]

@app.post("/v1/chat/completions")
async def chat(body: ChatIn, request: Request):
    # auth, rate limit, budget check happen here (dependencies)
    async def call_provider(model: str):
        async with httpx.AsyncClient(timeout=60) as c:
            r = await c.post(f"{os.environ['PROVIDER_BASE']}/chat/completions",
                             json={"model": model, "messages": body.messages},
                             headers={"Authorization": f"Bearer {os.environ['PROVIDER_KEY']}"})
            r.raise_for_status()
            return r.json()
    # Fallback across providers: try body.model, then the configured backup
    chain = FallbackChain(
        [Route(body.model, lambda: call_provider(body.model)),
         Route("backup-model", lambda: call_provider("backup-model"), is_fallback=True)],
        breaker=breaker,
        may_fall_back=lambda e: isinstance(e, (httpx.TimeoutException, httpx.ConnectError)))
    result, route = await chain.run()
    return {"choices": result["choices"], "served_by": route.name}

9.5 Gateway risks — the honest list#

Risk Mitigation
Added hop latency & failure mode The gateway is now a dependency: health-check it, alert on it, and keep a direct-provider escape hatch in config
Double retries Exactly one layer retries. If the gateway retries, your client sets max_retries=0 and its fallback only triggers on errors the gateway surfaces
Supply-chain / patching burden LiteLLM's March 2026 compromise is the canonical warning: pin versions, hash-lock, review upgrades, keep secrets out of the gateway's env where possible (03.11, 13.9, Module 12)
Another thing that sees your prompts Self-hosted gateway keeps data in your network; hosted gateway/aggregator is a data processor — check the data-flow diagram
Feature dilution Gateways normalise to the lowest common denominator; provider-specific features (Anthropic cache breakpoints, OpenAI background mode) may not pass through — verify per feature
Config drift Gateway config (fallbacks, budgets, keys) is production config: version it, review changes, and test it in staging like code

Part 10: Multi-region failover and what providers promise#

Reference

10.1 What providers actually promise#

The uncomfortable truth of LLM reliability: the SLA is thin. Verified against official terms/pages in November 2026:

Provider / route Published availability commitment Notes
OpenAI 99.9% uptime SLA — Scale Tier / Fast mode, Enterprise agreements only No public uptime definition, measurement period, credit schedule or claim window; the standard Services Agreement offers no availability SLA at all ("as is"). PAYG customers get best-effort
Anthropic None published Commercial terms disclaim uninterrupted service; ZDR/enterprise agreements are where commitments would live
Gemini API (AI Studio) None published Additional Terms define paid services and data use but no uptime figure; enterprise buyers are pointed to Vertex AI
Vertex AI / Gemini Enterprise 99.5% monthly uptime for Gemini Online Inference (95% for "shorter availability" models); Google Cloud "Gemini for Google Cloud" 99.9% The Vertex AI generative AI SLA page (read 9 November 2026) also lists a 99% uptime SLO for Provisioned Throughput and latency SLOs with service credits; the 99.9% "Gemini for Google Cloud" figure comes from a different Google Cloud SLA and was not re-checked
OpenRouter No meaningful published SLA An aggregator's SLA would be only as strong as its weakest upstream; treat as best-effort
Self-hosted Yours Your SLA is your hardware + your on-call

What this means for you: do not put "the provider's SLA" in your own SLO math. Your availability SLO must be built on your redundancy — fallbacks, multi-region, degradation — not on a vendor promise that mostly doesn't exist at PAYG tiers. If you need a contractual commitment, it's an enterprise-agreement conversation, and the commitment lives in your contract, not a public page.

10.2 Status pages and provider health#

Every major provider publishes a status page — status.openai.com, status.anthropic.com, status.cloud.google.com, plus per-service pages for Azure and AWS. Use them two ways:

  • Reactive correlation: when your error rate spikes, check the provider's status before declaring an incident — a known upstream incident changes the response from "debug our code" to "wait it out / failover".
  • Proactive awareness: subscribe to status-page notifications (email/RSS/webhook) so a planned maintenance window or emerging incident reaches on-call before users complain. Some providers expose status APIs; where they don't, a lightweight scheduled scrape of the status page into your alerting is a reasonable poor-man's integration.

10.3 Failover across regions and providers#

Multi-region failover for LLMs is harder than for stateless CRUD because of data residency and model parity:

  • Same model, different region: OpenAI and Google offer regional endpoints (often at a surcharge — 02.9, 6.7); Anthropic has inference_geo options. Failover within a provider to another region is usually policy-safe if both regions satisfy your residency commitment.
  • Different provider entirely: the fallback must satisfy the same data policy (6.4) — and it is a different model, so quality parity is not guaranteed.
  • The degraded alternative: when no policy-compliant route is available, the honest degraded path is queue and retry later, not "send it to the US anyway". A batch job can wait an hour; a chat request can't — which is why the degradation ladder exists.

A practical failover order for a residency-constrained feature: primary region → secondary region (same provider, same model) → alternate provider only if it meets residency → queue/degrade → honest error. Never silently widen the data boundary.

10.4 Error budgets and game days#

Reliability mechanisms exist to protect an error budget — the 11A.2 SLO concept applied here: if your availability SLO is 99.9%, you have ~43 min/month of downtime budget; spend it on real incidents, not on retry storms you caused. When the budget burns fast, the response is reduce change (freeze deploys, avoid risky migrations), not add retries. Game days (8.4) rehearse the human side; post-incident reviews are 11C.4's.


Part 11: Quality reliability — the silent failures#

Availability machinery can't catch the failure mode that should worry you most: the model changed and nobody deployed anything. Three defences:

  1. Pin versions, not aliases. A floating alias (-latest, gpt-6 without a snapshot) can change behaviour when the provider updates it. Pin dated snapshots in production config and treat alias moves as deliberate, evaluated changes (02.9, Part 8, 11B.5).
  2. Scheduled canary evals. Run your eval set (or the tiny model canary from 8.1) on a schedule against every production route — including fallback routes, which are the most likely to drift unnoticed. A scheduled eval that alerts on a quality delta is the only reliable detector of silent regression; link the eval harness to Module 10A and the CI gate to 11C.2.
  3. Validators as reliability tools. Schema validation, semantic checks and business-rule validators (03.4, Part 6) are not just correctness — they're detectors. A spike in validation failures is an early warning that the provider changed something; wire validator-failure rate into your alerting (11A.2).

Part 12: llm_service/resilience.py — the complete file#

Reference

Everything above lives in one module. This is the full file — copy it into llm_service/resilience.py and the demos/tests in this lesson run against it. Stdlib only.

python
# llm_service/resilience.py — production resilience primitives for LLM services.
# Circuit breaker, bulkheads, fallback chain, shared rate limiter, deadline.
# Stdlib only. Provider-agnostic: everything wraps callables you supply.
from __future__ import annotations

import asyncio
import heapq
import random
import time
from collections import deque
from contextlib import asynccontextmanager
from dataclasses import dataclass, field
from enum import Enum
from typing import Any, AsyncIterator, Awaitable, Callable, Protocol, TypeVar

T = TypeVar("T")


# --------------------------------------------------------------------------- errors
class CircuitOpenError(Exception):
    """Raised fast while the breaker is open. Carries when it may be probed."""

    def __init__(self, key: str, retry_at: float):
        super().__init__(f"circuit open for {key!r}; probe after {retry_at:.1f}")
        self.key = key
        self.retry_at = retry_at


class BulkheadFullError(Exception):
    """Raised immediately when a bulkhead has no free slots."""

    def __init__(self, key: str, limit: int):
        super().__init__(f"bulkhead {key!r} full ({limit} in flight)")
        self.key = key
        self.limit = limit


class DeadlineExceededError(Exception):
    pass


# --------------------------------------------------------------------------- circuit breaker
class BreakerState(str, Enum):
    CLOSED = "closed"
    OPEN = "open"
    HALF_OPEN = "half_open"


@dataclass
class BreakerConfig:
    window: int = 20            # outcomes kept per key (calls, not seconds)
    min_calls: int = 5          # don't judge before this many outcomes
    failure_rate: float = 0.5   # open when failures / outcomes >= this
    cooldown_s: float = 30.0    # first open duration
    max_cooldown_s: float = 300.0
    cooldown_growth: float = 2.0  # exponential backoff per consecutive open
    probe_timeout_s: float | None = None  # cap a half-open probe (None = caller's timeout)

    def __post_init__(self) -> None:
        # A misconfigured breaker fails silently: with min_calls > window the
        # outcome window can never reach min_calls, so it would never trip.
        if not (isinstance(self.window, int) and isinstance(self.min_calls, int)
                and 1 <= self.min_calls <= self.window):
            raise ValueError("need integers 1 <= min_calls <= window")
        if not 0 < self.failure_rate <= 1:
            raise ValueError("failure_rate must be in (0, 1]")
        if not (0 <= self.cooldown_s <= self.max_cooldown_s and self.cooldown_growth >= 1):
            raise ValueError("need 0 <= cooldown_s <= max_cooldown_s and cooldown_growth >= 1")
        if self.probe_timeout_s is not None and not self.probe_timeout_s > 0:
            raise ValueError("probe_timeout_s must be positive or None")


@dataclass
class _Window:
    outcomes: deque[bool] = field(default_factory=lambda: deque(maxlen=20))
    opened_at: float | None = None
    consecutive_opens: int = 0
    cooldown_s: float = 30.0


class CircuitBreaker:
    """Async circuit breaker, keyed by dependency (e.g. 'openai/gpt-6-luna').

    `is_failure(exc)` decides which exceptions count; the default counts
    everything, so pass the predicate your fallback policy uses (03.8 kinds).
    clock/sleep/rng are injectable for deterministic tests.
    """

    def __init__(
        self,
        config: BreakerConfig | None = None,
        *,
        is_failure: Callable[[BaseException], bool] | None = None,
        clock: Callable[[], float] = time.monotonic,
        sleep: Callable[[float], Awaitable[None]] = asyncio.sleep,
        rng: random.Random | None = None,
    ) -> None:
        self.config = config or BreakerConfig()
        self.is_failure = is_failure or (lambda exc: True)
        self._clock = clock
        self._sleep = sleep
        self._rng = rng or random.Random()
        self._windows: dict[str, _Window] = {}
        self._half_open_inflight: set[str] = set()

    # -- state -----------------------------------------------------------------
    def state(self, key: str) -> BreakerState:
        w = self._windows.get(key)
        if w is None or w.opened_at is None:
            return BreakerState.CLOSED
        if self._clock() - w.opened_at >= w.cooldown_s and key not in self._half_open_inflight:
            return BreakerState.HALF_OPEN
        return BreakerState.OPEN

    def _window(self, key: str) -> _Window:
        if key not in self._windows:
            self._windows[key] = _Window(outcomes=deque(maxlen=self.config.window),
                                         cooldown_s=self.config.cooldown_s)
        return self._windows[key]

    # -- the call ---------------------------------------------------------------
    async def call(self, key: str, fn: Callable[[], Awaitable[T]]) -> T:
        """Run fn() under the breaker for `key`. Raises CircuitOpenError fast
        when open; lets exactly one probe through in half-open."""
        st = self.state(key)
        if st is BreakerState.OPEN:
            raise CircuitOpenError(key, self._probe_at(key))
        if st is BreakerState.HALF_OPEN:
            if key in self._half_open_inflight:
                raise CircuitOpenError(key, self._probe_at(key))
            self._half_open_inflight.add(key)
        try:
            if st is BreakerState.HALF_OPEN and self.config.probe_timeout_s is not None:
                # A probe that never returns would hold the one probe slot for ever.
                result = await asyncio.wait_for(fn(), self.config.probe_timeout_s)
            else:
                result = await fn()
        except asyncio.CancelledError:
            # Client disconnect / task cancellation is not evidence the provider
            # is down — never count it toward the failure window.
            raise
        except Exception as exc:
            try:
                failed = bool(self.is_failure(exc))
            except Exception:       # a broken predicate must not hide an outage
                failed = True
            # Free the probe slot BEFORE recording so state() inside _record
            # sees HALF_OPEN: the probe's outcome then closes or re-opens the
            # breaker instead of being discarded as "already open".
            self._half_open_inflight.discard(key)
            self._record(key, failed)
            raise
        else:
            self._half_open_inflight.discard(key)
            self._record(key, False)
            return result
        finally:
            self._half_open_inflight.discard(key)

    # -- bookkeeping -------------------------------------------------------------
    def _probe_at(self, key: str) -> float:
        w = self._windows[key]
        jitter = self._rng.uniform(0, w.cooldown_s * 0.1)
        return w.opened_at + w.cooldown_s + jitter

    def _record(self, key: str, failed: bool) -> None:
        w = self._window(key)
        w.outcomes.append(failed)
        st = self.state(key)
        if st is BreakerState.HALF_OPEN:
            # A probe result decides immediately: success closes, failure re-opens longer.
            if failed:
                self._open(key, w)
            else:
                w.opened_at = None
                w.consecutive_opens = 0
                w.cooldown_s = self.config.cooldown_s
            return
        if st is BreakerState.OPEN:
            return  # already open; outcome of a probe that raced is ignored
        if len(w.outcomes) >= self.config.min_calls:
            rate = sum(w.outcomes) / len(w.outcomes)
            if rate >= self.config.failure_rate:
                self._open(key, w)

    def _open(self, key: str, w: _Window) -> None:
        w.opened_at = self._clock()
        w.consecutive_opens += 1
        # The exponent is capped: 2.0 ** 1100 raises OverflowError, which would
        # surface from the failing call after about 1,000 consecutive re-opens.
        growth = self.config.cooldown_growth ** min(w.consecutive_opens - 1, 64)
        w.cooldown_s = min(self.config.cooldown_s * growth, self.config.max_cooldown_s)
        w.outcomes.clear()          # start the next window clean


# --------------------------------------------------------------------------- bulkheads (queue-based)
class Bulkheads:
    """Per-key bounded concurrency using asyncio.Queue slots. Keys are yours:
    'tenant:acme', 'feature:chat', 'route:reasoning'. acquire() fails fast;
    acquire(wait_s=...) queues up to that long, then BulkheadFullError."""

    def __init__(self, default_limit: int = 8, limits: dict[str, int] | None = None) -> None:
        self._default, self._limits = default_limit, limits or {}
        self._slots: dict[str, asyncio.Queue] = {}
        self._limits_seen: dict[str, int] = {}

    def _queue(self, key: str) -> tuple[asyncio.Queue, int]:
        if key not in self._slots:
            limit = self._limits.get(key, self._default)
            q = asyncio.Queue(maxsize=limit)
            for _ in range(limit):          # pre-fill with `limit` slot tokens
                q.put_nowait(None)
            self._slots[key] = q
            self._limits_seen[key] = limit
        return self._slots[key], self._limits_seen[key]

    @asynccontextmanager
    async def acquire(self, key: str, *, wait_s: float | None = None) -> AsyncIterator[None]:
        """Hold one slot for `key`. wait_s=None -> fail fast when full;
        wait_s>0 -> queue up to that long, then BulkheadFullError."""
        q, limit = self._queue(key)
        try:
            if wait_s is None:
                q.get_nowait()              # documented non-blocking acquire
            else:
                await asyncio.wait_for(q.get(), timeout=wait_s)
        except (asyncio.QueueEmpty, TimeoutError) as exc:
            raise BulkheadFullError(key, limit) from exc
        try:
            yield
        finally:
            q.put_nowait(None)              # return the slot


# --------------------------------------------------------------------------- deadline
@dataclass
class Deadline:
    budget_s: float
    clock: Callable[[], float] = time.monotonic
    _start: float = 0.0

    def __post_init__(self) -> None:
        self._start = self.clock()

    @property
    def remaining(self) -> float:
        return max(0.0, self.budget_s - (self.clock() - self._start))

    def stage_budget(self, fraction: float) -> float:
        return self.remaining * fraction

    def check(self) -> None:
        if self.remaining <= 0:
            raise DeadlineExceededError(f"deadline of {self.budget_s}s exhausted")

    def timeout_for(self, provider_default_s: float) -> float:
        return min(provider_default_s, self.remaining)


# --------------------------------------------------------------------------- fallback chain
@dataclass
class Route:
    """One entry in a fallback chain: a name and the callable that serves it."""
    name: str                                  # 'openai/gpt-6-luna', 'anthropic/claude-haiku-5-5'
    call: Callable[[], Awaitable[Any]]
    is_fallback: bool = False
    data_policy_ok: bool = True                # does this route satisfy the request's data policy?


class FallbackChain:
    """Try routes in order; move to the next on an allowed failure.

    `may_fall_back(exc)` is the policy hook — in production it inspects the
    03.11 `LLMError` class (or 03.8 `Failure.kind`). The shipped default fails
    CLOSED (never falls back): override it, but only to *widen* fallback to
    the transient classes in 6.2 — quota/auth/bad-request must not fall back.
    `breaker` is consulted before each route so an open circuit skips it fast.
    """

    def __init__(self, routes: list[Route], *, breaker: "CircuitBreaker | None" = None,
                 may_fall_back: Callable[[BaseException], bool] | None = None,
                 deadline: "Deadline | None" = None) -> None:
        self.routes = routes
        self.breaker = breaker
        self.may_fall_back = may_fall_back or (lambda exc: False)
        self.deadline = deadline
        self.attempts: list[dict] = []

    async def run(self) -> tuple[Any, Route]:
        """Returns (result, serving_route). Raises the last error if all fail;
        if every route was skipped instead, raises DeadlineExceededError (no
        time left) or the last CircuitOpenError. Build one chain per request:
        `attempts` accumulates across run() calls."""
        last_exc: BaseException | None = None
        open_exc: CircuitOpenError | None = None
        out_of_time = False
        for route in self.routes:
            # Every route is checked, the primary included: a route that may not
            # receive this request's data must never be called, whatever its position.
            if not route.data_policy_ok:
                self.attempts.append({"route": route.name, "skipped": "data_policy"})
                continue
            # The breaker enforces open/half-open inside call(); an open
            # circuit surfaces as CircuitOpenError below — no pre-check needed.
            if self.deadline is not None and self.deadline.remaining <= 0.5:
                self.attempts.append({"route": route.name, "skipped": "deadline"})
                out_of_time = True
                break
            try:
                if self.breaker is not None:
                    result = await self.breaker.call(route.name, route.call)
                else:
                    result = await route.call()
                self.attempts.append({"route": route.name, "ok": True})
                return result, route
            except CircuitOpenError as exc:
                self.attempts.append({"route": route.name, "skipped": "circuit_open"})
                open_exc = exc
                continue
            except Exception as exc:
                # Exception, not BaseException: asyncio.CancelledError (client
                # disconnect), KeyboardInterrupt and SystemExit must propagate —
                # a cancellation is not a fallback trigger and must not pay for
                # an answer nobody will read.
                self.attempts.append({"route": route.name, "error": type(exc).__name__})
                last_exc = exc
                if not self.may_fall_back(exc):
                    raise                       # permanent: don't try the next route
                continue
        if last_exc is not None:
            raise last_exc
        if out_of_time:
            raise DeadlineExceededError("no time left to try another route")
        if open_exc is not None:
            raise open_exc
        raise RuntimeError("fallback chain empty or every route skipped by data policy")


# --------------------------------------------------------------------------- shared rate limiter
class TokenStore(Protocol):
    """Atomic check-and-debit plus shared 429 backoff state (Redis+Lua in prod)."""
    async def try_acquire(self, key: str, cost: float, capacity: float, refill_per_s: float) -> bool: ...
    async def refund(self, key: str, cost: float) -> None: ...
    async def set_backoff(self, key: str, until: float) -> None: ...
    async def backoff_until(self, key: str) -> float: ...


class InMemoryTokenStore:
    def __init__(self) -> None:
        self._buckets: dict[str, tuple[float, float]] = {}
        self._backoff: dict[str, float] = {}
        self._lock = asyncio.Lock()

    async def try_acquire(self, key: str, cost: float, capacity: float, refill_per_s: float) -> bool:
        async with self._lock:
            tokens, last = self._buckets.get(key, (capacity, time.monotonic()))
            now = time.monotonic()
            tokens = min(capacity, tokens + (now - last) * refill_per_s)
            if tokens < cost:
                self._buckets[key] = (tokens, now)
                return False
            self._buckets[key] = (tokens - cost, now)
            return True

    async def refund(self, key: str, cost: float) -> None:
        async with self._lock:
            tokens, _ = self._buckets.get(key, (0.0, time.monotonic()))
            self._buckets[key] = (min(1e9, tokens + cost), time.monotonic())

    async def set_backoff(self, key: str, until: float) -> None:
        async with self._lock:
            self._backoff[key] = max(self._backoff.get(key, 0.0), until)

    async def backoff_until(self, key: str) -> float:
        async with self._lock:
            return self._backoff.get(key, 0.0)


@dataclass
class RateLimitConfig:
    tokens_per_min: float
    max_burst: float = 0.0        # 0 -> capacity = tokens_per_min/60 * 10 (10 s of burst)

    def __post_init__(self) -> None:
        # A NaN or non-positive rate makes every comparison in the bucket false:
        # the limiter would admit everything (or nothing) without saying so.
        if not 0 < self.tokens_per_min < float("inf") or not 0 <= self.max_burst < float("inf"):
            raise ValueError("tokens_per_min must be positive and max_burst >= 0, both finite")


class SharedRateLimiter:
    """Token-bucket limiter backed by a shared store.

    The configure() key IS the bucket key — configure per provider *and* per
    model route ('openai', 'openai/gpt-6-luna', 'tenant:acme'). Charge estimated
    tokens before the call (acquire), reconcile against actual usage after
    (settle), and report 429s (report_429) — the backoff deadline lives in the
    shared store, so every instance slows down, not just the one that saw it.
    """

    def __init__(self, store: TokenStore) -> None:
        self.store = store
        self._configs: dict[str, RateLimitConfig] = {}

    def configure(self, key: str, cfg: RateLimitConfig) -> None:
        self._configs[key] = cfg

    def _capacity(self, cfg: RateLimitConfig) -> float:
        return cfg.max_burst or (cfg.tokens_per_min / 60.0) * 10.0

    async def acquire(self, key: str, est_tokens: float) -> bool:
        """Returns True if the call may proceed. False -> wait or shed."""
        # A negative estimate would mint tokens and NaN would debit nothing.
        if not 0 <= est_tokens < float("inf"):
            raise ValueError(f"est_tokens must be finite and >= 0, got {est_tokens!r}")
        cfg = self._configs.get(key)
        if cfg is None:
            return True                                # unconfigured = unlimited
        if await self.store.backoff_until(key) > time.monotonic():
            return False                               # shared 429 backoff: whole fleet holds
        return await self.store.try_acquire(key, est_tokens,
                                            self._capacity(cfg), cfg.tokens_per_min / 60.0)

    async def settle(self, key: str, charged: float, actual: float) -> None:
        """Reconcile the pre-call estimate against real usage: refund
        over-estimates; debit under-estimates (best-effort — if the bucket is
        already empty the next 429 corrects course)."""
        if not (0 <= actual < float("inf") and 0 <= charged < float("inf")):
            raise ValueError("charged and actual must be finite and >= 0")
        cfg = self._configs.get(key)
        if cfg is None or charged == actual:
            return
        if charged > actual:
            await self.store.refund(key, charged - actual)
        else:
            await self.store.try_acquire(key, actual - charged,
                                         self._capacity(cfg), cfg.tokens_per_min / 60.0)

    async def report_429(self, key: str, retry_after_s: float | None) -> None:
        """Called on a 429: write a shared backoff deadline so the whole
        fleet slows down — every instance reads the same store."""
        if key not in self._configs:
            return
        # Retry-After comes from the provider: clamp it to [0, 60] (max() turns NaN into 0).
        wait = min(max(0.0, retry_after_s) if retry_after_s is not None else 5.0, 60.0)
        await self.store.set_backoff(key, time.monotonic() + wait)


# --------------------------------------------------------------------------- priority shed queue
@dataclass(order=True)
class _Item:
    priority: int
    seq: int = field(compare=False)
    payload: Any = field(compare=False, default=None)


class PriorityQueue:
    def __init__(self, maxsize: int) -> None:
        if isinstance(maxsize, bool) or not isinstance(maxsize, int) or maxsize < 1:
            raise ValueError("maxsize must be an integer >= 1")
        self._q: list[_Item] = []
        self._max, self._seq, self.shed_count = maxsize, 0, 0

    def put(self, payload: Any, priority: int = 100) -> bool:
        item = _Item(priority=priority, seq=self._seq, payload=payload)
        self._seq += 1
        if len(self._q) < self._max:
            heapq.heappush(self._q, item)
            return True
        worst = max(range(len(self._q)), key=lambda i: (self._q[i].priority, -self._q[i].seq))
        self.shed_count += 1
        if item.priority < self._q[worst].priority:
            self._q.pop(worst)
            heapq.heapify(self._q)
            heapq.heappush(self._q, item)
            return True
        return False

The chaos suite from 8.3 (tests/test_chaos.py) is the verification harness: it runs the whole stack against scripted failures with no provider, no keys and no network.


Common misconceptions#

Misconception Reality
"Retries fix outages." Retries fix blips. Against a sustained outage they amplify load and delay the fallback that would have helped. One layer owns retries; a breaker stops paying the failure cost
"A fallback is free reliability." A fallback is an untested model until you eval it: different quality, refusals, tokenizer, cost and data policy. Silent degradation is the cardinal sin — mark every degraded response
"A 429 always means slow down." A 429 can mean "out of money" — credit_balance_exhausted, spend caps, quotas. Retrying those can never work; check the error code, not just the status (03.8, 4.2)
"The provider's SLA covers us." Mostly not: OpenAI's 99.9% SLA is enterprise-only; Anthropic and the Gemini API publish none. Build your SLO on your own redundancy
"A gateway removes the need for app-level resilience." It adds a central place for keys/budgets/policy but is another hop and another dependency — and it can't know your per-feature priorities. Compose, don't substitute; one layer owns retries
"Circuit breakers are only for databases." They're for any flaky dependency — and LLM providers are among the flakiest. Per-route keys, failure-rate windows and one-probe half-open are the production shape
"More retries = more reliable." Past a point, retries reduce reliability (retry storms, thundering herd, double billing) and delay honest degradation. Bound attempts, time and cost
"Failover to another region is always safe." Only if the region satisfies your data-residency policy. When no compliant route exists, the honest degraded path is queue-and-retry, not sending data across the boundary
"A cached answer is a good fallback." Only for low-stakes, TTL-bounded cases — and it must be labelled. A stale answer presented as fresh is worse than an honest error
"Chaos tests prove reliability." They prove the mechanisms fire. Whether the system is reliable also depends on tuning, alerts, runbooks and humans — that's game days and SLOs (11A.2, 11C.4)
"If it returns 200, it's fine." LLM "successful failures" — refusals, truncation, errors inside a 200, silent quality regressions — need outcome checks and evals, not just status codes

Key takeaways#

  • Reliability for LLM features is three promises — availability, latency and quality — defended by a layered stack: validation → rate limiting/load shedding → timeouts/deadlines → retries (one owner) → circuit breakers → fallback chains → graceful degradation → idempotency on your side effects (03.8, Part 11: none of the four inference APIs deduplicates a retried call).
  • Circuit breakers count a failure rate over a sliding window per provider+model route, open on threshold, cool down exponentially, and admit exactly one jittered probe in half-open. resilience.py implements it with an injectable clock for deterministic tests.
  • Bulkheads bound concurrency per feature/tenant so one group's surge can't starve everyone; a full bulkhead triggers a product decision (fail fast, queue with deadline, degrade, or shed by priority) — never an unbounded queue.
  • Deadlines propagate: one absolute budget shared by every stage, with remaining checked before each expensive step, and disconnect-watching so you stop paying for tokens nobody reads.
  • Fallbacks are policy, not panic: fall back on transient classes and open circuits; never on quota/auth/bad-request/refusals (unless deliberately opted in); check data_policy_ok per route; mark every degraded response; eval every fallback before it's needed.
  • Streams fail differently: before the first chunk a fallback is invisible; after it you must either surface the break (keep the partial, label it) or restart with a visible reset, and never restart past an executed tool call. Count broken streams as failures in breakers and metrics.
  • The degradation ladder — fallback model → smaller model → cached → retrieval-only → queue → honest error — is the honest answer when the chain is exhausted; silent degradation is the cardinal sin.
  • Rate limits count tokens: a shared limiter (Redis-backed in production, atomic via Lua) coordinates the whole fleet; per-tenant sub-limits give fairness; 429s trigger coordinated backoff.
  • Gateways (LiteLLM proxy, Portkey, OpenRouter, Cloudflare, Vercel, Kong, Helicone, Bifrost, TensorZero, Azure APIM, Apigee, Agent Router, or self-built) centralise keys/budgets/policy but add a hop and a dependency; the build/buy/gateway decision and the one-layer-owns-retries rule govern the choice. Library-level options (Vercel AI SDK, any-llm, aisuite, LangChain init_chat_model, Pydantic AI) add no hop but carry the policy in every service, and TensorZero's repository was archived in June 2026.
  • Provider SLAs are thin — your availability SLO rests on your own redundancy; status pages aid correlation, and failover must respect data residency (queue-and-retry beats crossing the boundary).
  • Quality reliability is separate: pin versions, run scheduled canary evals on every route (especially fallbacks), and treat validator-failure spikes as early-warning detectors.

Terms introduced in this lesson#

Term One-line definition
Circuit breaker A per-route state machine (closed/open/half-open) that fails fast while a dependency looks dead and probes for recovery
Half-open probe The single trial call allowed through after a breaker's cooldown to test recovery
Bulkhead A bounded concurrency pool per caller class (feature/tenant/route) isolating blast radius
Load shedding Rejecting or queueing work when saturated, by priority, rather than accumulating unboundedly
Deadline An absolute time budget shared by all stages of one request
Deadline propagation Passing the remaining budget down so each stage gets min(need, remaining × fraction)
Fallback chain An ordered list of routes tried when the primary fails for an allowed reason
Degradation ladder The ordered honest fallbacks when the chain is exhausted: smaller model → cache → retrieval-only → queue → error
Silent degradation Serving a worse answer that looks identical to a good one — the cardinal reliability sin
Graceful degradation Deliberately serving a reduced-function answer, labelled, instead of failing outright
Shared rate limiter A token-bucket limiter in shared storage (Redis) so all instances see one quota
Token-aware throttling Rate limiting by estimated/actual tokens, not just request count
Tenant fairness Per-tenant sub-limits so one noisy tenant can't exhaust the shared pool
Model canary A tiny scheduled eval run against each route to detect silent quality drift
Stream reset / broken stream A started stream that is restarted on another route (the UI must clear what it showed) / one that failed after the first chunk and is surfaced with its partial text
Chaos test Deliberate fault injection (timeouts, 429s, malformed output) to verify resilience mechanisms fire
Game day A scheduled rehearsal of an outage scenario to test humans and runbooks, not just code
LLM gateway A proxy centralising routing, retries, fallbacks, budgets, keys and logging across providers
Library-level option A client library that unifies providers inside your own process (no proxy), so keys, budgets and shared state stay your responsibility
Virtual key A gateway-issued scoped credential standing in for real provider keys
Data policy / data residency Constraints on where prompt data may be processed — a fallback must not violate them
Error budget The allowable unreliability under an SLO; spend it on real incidents, not self-inflicted storms

All terms are also collected in the glossary.


Exercises#

  1. Breaker tuning (3.4, 3.5): in s3_breaker_demo.py, set FlakyProvider(fail_rate=0.6) and BreakerConfig(window=10, min_calls=4, failure_rate=0.5). Predict whether the breaker opens; run it; explain the outcome using the failure-rate window.
  2. Half-open stampede (3.2): write a test that fires 20 concurrent breaker.call() invocations the instant the cooldown elapses. Assert exactly one reaches the provider and the rest get CircuitOpenError. What does this prove about probe design?
  3. Fallback policy (6.2): extend may_fall_back in s6_chain_demo.py to also reject a custom QuotaError. Run the chain in both directions (OpenAI primary with Claude as backup, then Claude primary with OpenAI as backup) and show the same policy holds each way. Then add a third route (Gemini is an optional choice) and show the chain skipping it for a quota failure but using it for a timeout.
  4. Deadline budget (5.3): give answer() in 5.1 a Deadline(budget_s=10) and a fake retrieve that sleeps 8 s. Show that generate receives a timeout_for of at most ~2 s and that deadline.check() raises if retrieval overruns.
  5. Shared limiter (7.2): implement a RedisTokenStore sketch using redis.asyncio + an EVAL Lua script for atomic try_acquire. Write the Lua so read-refill-check-debit is one round trip. (Reference only — don't run it without Redis.)
  6. Chaos mutation (8.3): remove the breaker.call wrapper in FallbackChain.run and re-run test_chaos_breaker_opens_and_skips_dead_route. Confirm it fails — that's the mutation check proving the test tests something.
  7. Gateway config (9.4): write a config.yaml for LiteLLM proxy with two deployments of the same model alias, num_retries: 2, allowed_fails: 3, cooldown_time: 30, and a fallback to a different provider (OpenAI to Claude, then swap them to fail over the other way). Explain what each key does and where the double-retry risk would be if your app also retried.
  8. Data-policy failover (6.4, 10.3): your primary route is "Anthropic US, ZDR". List three fallback routes and mark each data_policy_ok true/false with a one-line reason. Which degraded path remains when all are false?
  9. SLA reality check (10.1): draft the availability section of your service's SLO document assuming no provider SLA — only your own redundancy. What availability can you honestly claim, and what would move it?
  10. Silent regression (11): design a scheduled canary eval for a structured-output feature: 5 prompts, the checks (schema validates, required fields present, no refusal), the schedule, and the alert threshold. Which route is most likely to drift unnoticed, and why?
  11. Streams (6.7): in demo_stream.py make the backup also fail after one chunk. What does each of the three cases print now, and which exception reaches the caller in case 3? Then add a fourth route and show the chain reaching it.
Hints for the exercises
  1. With the demo's seed the outcomes are fail, fail, ok, fail: three failures in four calls is a 75% rate, above the 0.5 threshold once min_calls=4 is reached, so the breaker opens after call 3 and calls 4-7 fail fast. The single success does not save it, because the rate window counts proportions, not streaks.
  2. After advancing the fake clock past the cooldown, await asyncio.gather(*[breaker.call(key, fn) for _ in range(20)], return_exceptions=True). The first call adds the key to _half_open_inflight before any await, so the other 19 see OPEN and raise CircuitOpenError: the provider gets exactly 1 call. That is the whole point of one probe.
  3. Define class QuotaError(Exception); a may_fall_back that returns True only for TimeoutError/ConnectionError already rejects it. The chain re-raises on a quota failure and moves to route 3 on a timeout.
  4. Retrieval consumes 8 s of 10, so deadline.timeout_for(60.0) returns about 2.0; if retrieval overran to 11 s, deadline.check() raises DeadlineExceededError.
  5. The Lua script reads the bucket hash (tokens, ts), refills by (now - ts) * refill_per_s capped at capacity, compares with cost, writes back the new tokens on success and returns 1 or 0, all in one EVAL.
  6. Without breaker.call the dead route is invoked on every run(), so dead.calls grows and the assertion dead.calls == calls_before fails.
  7. num_retries is LiteLLM's own loop; if your app (or the SDK underneath it) also retries, one failure becomes (1 + app retries) x (1 + 2) upstream calls.
  8. Typical answer: the same provider's EU endpoint (true if EU-resident under the same terms), another provider's non-ZDR endpoint (false), an aggregator route without zdr: true (false). With all false, queue-and-retry or an honest error remains.
  9. State only what you control: number of independent routes, breaker/fallback behaviour and degradation; do not multiply provider SLAs.
  10. Pin a snapshot, run the five prompts every 15 minutes, alert when two consecutive runs fail a check; fallback routes drift unnoticed because they rarely serve real traffic.
  11. Case 1: the primary fails before any chunk, the backup then breaks after "Refunds ", so StreamBrokenError (route backup, partial 'Refunds ') reaches the caller. Case 2: unchanged, StreamBrokenError from the primary. Case 3: the UI is told to clear once (primary to backup), the backup breaks after one chunk, there is no next route, so the last ConnectionError is re-raised and the caller must handle a fully failed stream. With a third healthy route case 3 clears twice and then prints the full 14-day answer.

Check yourself#

  1. Name the three promises an LLM feature makes and why quality is the hardest to measure.
  2. Which failure classes should never trigger a fallback, and why?
  3. What are the three circuit-breaker states, and what does half-open allow?
  4. Why is a failure-rate window better than a consecutive-failure count for LLM routes?
  5. What's the difference between a bulkhead and a rate limiter?
  6. When a bulkhead is full, what are the four honest responses — and which is the worst anti-pattern?
  7. Why must a deadline be propagated rather than re-created per stage?
  8. What does cancelling a request on client disconnect save, and what does it not save?
  9. List three things that must be true before a fallback model serves production traffic.
  10. Why is silent degradation worse than an honest error for an LLM feature?
  11. Why do LLM rate limits need token-aware throttling rather than request counting?
  12. What makes a shared limiter safe across multiple instances, and what breaks it?
  13. Name three kinds of health check and which one catches silent model drift.
  14. List the chaos-injection faults specific to LLM dependencies and what each proves.
  15. What is the single most important rule about which layer owns retries?
  16. Give two reasons a hosted gateway (OpenRouter, Cloudflare, Vercel) changes your data-protection posture.
  17. Which providers publish a meaningful PAYG availability SLA as of November 2026, and what does that imply for your own SLO?
  18. Why must a failover to another region check data-residency policy before routing?
  19. A stream fails after the user has seen two sentences. Why can't the chain simply fall back as it would for a failed request, and what are the two honest options?

Further resources#


← 11C.2 — CI/CD for Prompts, Models and Evals | Module 11C overview | 11C.4 — Operating LLM Systems: Governance, Incidents and the Production Checklist →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close