# Your Fallback Is an Untested Deploy: Provider Failover in Django (Part 10)

A lot of LLM features have a fallback that is one line in a config file: if the primary model errors, call this other one. Often nobody has run that other model against the feature's eval set, or checked how it handles a prompt written for a different model. It waits until the primary is down, then goes live for 100% of traffic with no shadow, no canary and no rollback.

That's a deploy. It's an untested one, and it happens during an incident.

This is Part 10 of **Shipping AI Agents in Django**. [Part 9](https://aidevpro.hashnode.dev/llm-prompt-model-changes-shadow-canary-rollback-django) treated every prompt or model change as a deploy: version it in code, shadow it, replay evals, canary it, roll it back automatically. This part applies the same rule to the fallback path. A fallback gets its own prompt version, pinned to its own model id, and it doesn't get enabled until it has a passing eval run and enough shadow traffic behind it.

> **Short version**
>
> - Classify every failure before you react. Timeouts, 5xx and a 429 *with* `retry-after` can be retried. A 429 *without* `retry-after` may be a spend cap, so fail over instead. A 400 means your request is wrong, so stop and alert. A refusal or schema-invalid output isn't an outage.
> - Each step in the chain is a prompt version (provider, pinned model, prompt text) with a fingerprint. A fallback whose fingerprint is missing a passing eval run or a shadow record can't be enabled.
> - One deadline covers the whole request. Each attempt gets the smaller of its cap and the time left, and a `retry-after` longer than the time left means fail over now.
> - A per-provider circuit breaker with a single half-open probe stops you hammering a provider that's down.
> - Model calls have no side effects. You act once, on one answer, keyed by an idempotency key.
> - Log which provider and prompt version served every request.

The demo is a Django 5.2 app that extends Part 9's code. It has 59 passing pytest tests (25 carried over from Part 9, 34 new). The providers are scripted fakes, so nothing touches a network.

## Outages are normal, so the fallback path will run

On November 23, Anthropic's status page reported elevated errors from 09:39 to 09:56 UTC on "Claude Mythos 5.2, Claude Fable 5.2, Claude Opus 5.5, Claude Sonnet 5.5, Claude Haiku 5.5, and other Claude models" ([status.claude.com](https://status.claude.com/)). The next day Haiku 5.5 alone had an 18-minute incident. Both were short and resolved, and no vendor is special here: a third-party tracker, [UptimeRankings](https://uptimerankings.com/reports/2026-11/llm-api-providers), counts 89 incidents across the 16 LLM API providers it follows so far this November.

Two things follow. First, the fallback path is a production code path, so it needs the same evidence as the primary. Second, look at the Nov 23 incident again. It hit several model families at the same provider at the same time. A fallback to another model at the same provider would have hit the same errors. OpenAI's [November 2023 write-up](https://status.openai.com/incidents/01JMYB602A6H2E04Y1497J434X/write-up) describes a database failure in a service that "provides user authentication and service-to-service authentication across the entire OpenAI stack." When the shared layer goes, every model behind it goes too.

## Why "just add a fallback model" goes wrong

Gateways make the fallback easy. LiteLLM's [fallback docs](https://docs.litellm.ai/docs/proxy/reliability) describe it as: "If a call fails after num_retries, LiteLLM falls back to another model group." OpenRouter's [`models` parameter](https://openrouter.ai/docs/guides/routing/model-fallbacks) tries the next model "if the primary model's providers are down, rate-limited, or refuse to reply due to content moderation." Neither knows whether your prompt works on the second model.

**The prompt was tuned for one model.** Part 9 pinned model ids because prompting behaviour changes between snapshots. Between *providers* the gap is wider. The same system prompt on a different vendor's model is a new prompt version, whatever the config calls it.

**Structured output and refusals look different.** OpenAI's [structured outputs guide](https://developers.openai.com/api/docs/guides/structured-outputs) says the schema constrains "completed, non-refusal model output," and that your application "still needs to handle refusals, incomplete responses, and API errors." There a refusal arrives as a content item of type `refusal`. On Anthropic's newer models a classifier decline is ["a normal response, not an error, with `stop_reason: "refusal"`"](https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback). Your parser and your evals need both.

**Defaults fail over on things you might not want.** OpenRouter documents that "by default, any error can trigger the use of a fallback model," including context length validation errors and moderation flags. For a moderation feature, a refusal on a self-harm post is a signal for a human, not something to quietly retry elsewhere.

**Cost changes with the model.** OpenRouter bills "using the model that was ultimately used." LiteLLM notes that its budget check runs "against the model the caller asked for. The fallback target is picked afterwards." The proxy now re-checks each fallback target, but "It reads spend without reserving funds, so concurrent fallbacks can cross the cap." Anthropic's refusal docs add that a refused request can be billed in addition to the fallback, and that a fallback can miss the prompt cache.

**The fallback list can contain moving aliases.** OpenRouter's examples use `~anthropic/claude-sonnet-latest`. Part 9's registry rejects `-latest` names at import because they change without your deploy. A fallback that points at an alias is untested by definition.

None of this means don't fail over. It means the fallback goes through the same pipeline as everything else.

## Step 1: every fallback is a prompt version with its own fingerprint

Part 9's `PromptVersion` already held the id, pinned model, system prompt and params, hashed into a fingerprint. Part 10 adds one field, `provider`, which names the API client or account that serves it, and includes it in the hash:

```python
@dataclass(frozen=True)
class PromptVersion:
    id: str
    model: str
    system: str
    params: tuple = field(default=())
    schema: str = "verdict.v1"
    provider: str = "primary"

    @property
    def fingerprint(self) -> str:
        blob = json.dumps([self.provider, self.model, self.system,
                           list(self.params), self.schema])
        return hashlib.sha256(blob.encode()).hexdigest()[:12]


register(PromptVersion("moderation-b@1", "other-model-2026-09-01",
                       POLICY + "\nReturn the JSON object only. No prose before or after it.",
                       (("max_tokens", 300),), provider="secondary"))
```

The fallback isn't "moderation@3 on another provider." It's `moderation-b@1`: the same policy, worded for the model it runs on. (Model ids are placeholders.) Edit it and the fingerprint changes, so the old evidence no longer counts.

## Step 2: a gate that refuses untested fallbacks

A fallback is enabled by writing a `FallbackStep` row, and only `enable_fallback()` writes enabled rows. It checks the same evidence Part 9 required for a canary, with slightly different thresholds:

```python
@dataclass(frozen=True)
class FallbackGates:
    min_shadow_pairs: int = 200
    min_agreement: float = 0.90     # may word things differently from live...
    max_loosened: int = 0           # ...but may not allow what live held or hid
    max_eval_gap: float = 0.05      # may trail live's eval pass rate by this much
    max_eval_age_days: int = 30


def fallback_gate(feature, pv, gates=FallbackGates(), reviewed=frozenset()):
    live = registry.get(Rollout.objects.get(feature=feature).live_version)
    ev, live_ev = latest_eval(pv), latest_eval(live)
    reasons = []
    if ev is None:   # latest_eval() matches id AND fingerprint
        reasons.append(f"no eval run for {pv.id} ({pv.fingerprint})")
    else:
        ...  # also refuse runs older than max_eval_age_days
        if ev.must_pass_failed:
            reasons.append(f"must-pass eval cases failed: {ev.must_pass_failed}")
        if live_ev and ev.pass_rate < live_ev.pass_rate - gates.max_eval_gap:
            reasons.append(f"eval pass rate {ev.pass_rate:.0%} vs live {live_ev.pass_rate:.0%}")
    since = timezone.now() - timedelta(days=30)
    rep = compare_versions(feature, pv.id, since, fingerprint=pv.fingerprint)
    unreviewed = [k for k in rep.loosened if k not in reviewed]
    if rep.pairs < gates.min_shadow_pairs:
        reasons.append(f"only {rep.pairs} shadow pairs (need {gates.min_shadow_pairs})")
    elif rep.agreement < gates.min_agreement:
        reasons.append(f"agreement {rep.agreement:.2%} < {gates.min_agreement:.0%}")
    if len(unreviewed) > gates.max_loosened:
        reasons.append(f"{len(unreviewed)} unreviewed loosened decisions")
    ...
```

`compare_versions` is Part 9's shadow report with the feature, version and time window passed in, so the fallback is shadowed with the same machinery: `start_shadow("moderation", "moderation-b@1", 10, ...)` runs it next to live on a sample of real traffic and throws its answers away. A refusal is logged as a `gate_failed` event. A success writes the step with the evaluated fingerprint and a `fallback_enabled` event.

Two choices here are deliberate.

The agreement bar is lower than a canary's (90% vs 95%; both illustrative). A fallback serves for minutes during an incident, and a different model will call borderline cases differently. The **loosened** bar stays at zero, though. A fallback that allows what your primary would hold is a policy change shipped by accident during an outage.

At serving time, the chain only includes steps whose stored fingerprint still matches the registry:

```python
def build_chain(feature, primary):
    chain = [primary]
    for step in FallbackStep.objects.filter(feature=feature, enabled=True).order_by("position"):
        pv = registry.REGISTRY.get(step.prompt_version)
        if pv is None or pv.fingerprint != step.fingerprint:
            log.error("fallback %s differs from what was approved; skipping", step.prompt_version)
            continue
        if pv.id != primary.id:
            chain.append(pv)
    return chain
```

## Step 3: classify the failure before deciding what to do

There are three things you can do after a failed call: retry the same step, fail over to the next one, or stop and use the feature's safe default. Which one depends on what failed:

```python
def classify_exception(exc: Exception) -> Failure:
    if isinstance(exc, (ProviderTimeout, TimeoutError, ConnectionError)):
        return Failure("timeout", Next.RETRY)
    if isinstance(exc, ProviderError):
        s = exc.status or 0
        if s == 429 and exc.retry_after is not None:
            return Failure("rate_limited", Next.RETRY, retry_after=exc.retry_after)
        if s == 429:
            return Failure("quota", Next.FAILOVER)
        if s in (408, 409) or s >= 500:          # includes 529 overloaded
            return Failure("server", Next.RETRY)
        return Failure("bad_request", Next.STOP, trips_breaker=False)
    return Failure("unknown", Next.STOP, trips_breaker=False)


def classify_status(status: str, failover_on_refusal: bool) -> Failure:
    if status == "refusal":
        return Failure("refusal", Next.FAILOVER if failover_on_refusal else Next.STOP,
                       trips_breaker=False)
    return Failure(status, Next.FAILOVER, trips_breaker=False)   # invalid / length
```

The two 429 branches come from Anthropic's [error docs](https://platform.claude.com/docs/en/api/errors): "A tier spend-cap 429 has no `retry-after` header and keeps failing until access resumes." Retrying that just burns your deadline, so fail over and open the breaker for longer. That rule is Anthropic's; check how your providers signal quota.

A 400 stops the chain on purpose. Anthropic's docs list a 400 when "usage reaches an organization or workspace spend limit you set," and Part 9 covered parameters that newer API versions reject with a 400. Either way the provider is healthy and your request or account is the problem. Failing over hides a bug you need to see, so the demo holds the post, logs `stopped:bad_request` and leaves the breaker alone.

Refusals and invalid output don't trip the breaker either: the provider answered, just not usefully. Whether a refusal fails over is a per-feature policy (`failover_on_refusal`), off by default for moderation.

One trap: your SDK may already retry. Anthropic's SDK retries "connection errors, rate limits, and 5xx server errors with exponential backoff, twice by default." Stack that under your retries and a gateway's and one request becomes nine calls. Pick one layer to own retries; the demo assumes `max_retries=0` on the client.

## Step 4: one deadline, and every attempt spends from it

LiteLLM's docs make the point well: per-attempt timeouts "are per-attempt budgets, not a total request deadline. An ingress or client timeout that expires first prevents the application from benefiting from fallback." If your load balancer gives up at 10 seconds and your primary gets two 4-second attempts plus backoff, the fallback never runs.

So the chain carries one `Deadline` for the whole request. `attempt_timeout(cap)` returns the smaller of the per-attempt cap and the time left, or `None` when less than half a second remains. Here's the loop that walks the chain, trimmed slightly:

```python
for pv in chain:
    if not breaker.allow(pv.provider):
        _record(..., status="skipped", error_kind="circuit_open")
        continue
    for retry in range(policy.retries_per_step + 1):
        if attempts >= policy.max_attempts:
            return None, None, "max_attempts", attempts
        timeout = deadline.attempt_timeout(policy.attempt_timeout_s)
        if timeout is None:
            return None, None, "deadline", attempts
        attempts += 1
        try:
            verdict, status = classify(providers[pv.provider], pv, text, timeout=timeout)
            failure = None if status == "ok" else classify_status(status, policy.failover_on_refusal)
        except Exception as exc:
            verdict, status, failure = None, "error", classify_exception(exc)
        _record(..., provider=pv.provider, attempt=attempts, error_kind=...)
        if failure is None:
            breaker.record_success(pv.provider)
            return verdict, pv, "ok", attempts
        if failure.trips_breaker:
            breaker.record_failure(pv.provider, failure.kind)
        if failure.next is Next.STOP:
            return None, None, f"stopped:{failure.kind}", attempts
        if failure.next is Next.FAILOVER or breaker.state(pv.provider) != "closed":
            break
        if retry == policy.retries_per_step:
            break
        wait = failure.retry_after if failure.retry_after is not None else \
            policy.backoff_s * 2 ** retry * random.uniform(0.5, 1.0)
        if wait >= deadline.remaining() - 0.5:
            break          # waiting would eat the fallback's time: fail over now
        sleep(wait)
```

`max_attempts` is the cost ceiling: model calls per request, across every provider. The demo's policy for moderation is an 8-second deadline, a 4-second cap per attempt, at most three calls and one retry per step. When nobody answers, the action is `hold`, so a human looks.

## Step 5: a circuit breaker with one half-open probe

Without a breaker, every request during an outage pays for a failed attempt or two on the primary before failing over: latency for users, load for a provider trying to recover. The breaker keeps per-provider state in the Django cache, so with Redis behind it all your workers share it:

```python
def state(provider) -> str:
    opened_until = cache.get(_k(provider, "open_until"))
    if opened_until is None:
        return "closed"
    return "open" if clock() < opened_until else "half_open"


def allow(provider) -> bool:
    s = state(provider)
    if s == "closed":
        return True
    if s == "open":
        return False
    # Half-open: exactly one caller gets to probe. cache.add is atomic on Redis/Memcached.
    return cache.add(_k(provider, "probe"), 1, timeout=60)


def record_failure(provider, kind, policy=BreakerPolicy()):
    if state(provider) == "half_open" or kind == "quota":
        return _open(provider, policy.quota_open_for_s if kind == "quota" else policy.open_for_s)
    ...  # count failures in a sliding window; open after failures_to_open
```

Five failures in 30 seconds open it for 30 seconds; a quota 429 opens it for ten minutes at once. When the timer runs out, one request probes the primary. Success closes the breaker, failure reopens it. LiteLLM's version of this is a cooldown: `allowed_fails: 3` with `cooldown_time: 30` in their example. With a gateway, use its cooldowns and keep the gate and idempotency in Django.

The failure counter is a read-modify-write, so under heavy concurrency a few increments get lost. That only delays opening slightly.

## Step 6: act once, whoever answered

The primary times out on your side but finishes on theirs. You fail over, the secondary answers, and if the model call triggered the side effect (hide the post, email the author), it happens twice.

So model calls are pure: they return a verdict and nothing else. The side effect happens once, after the chain picks one answer, keyed by an idempotency key:

```python
def decide(feature, text, key, unit=None, providers=None, policy=None,
           now=time.monotonic, sleep=time.sleep) -> Served:
    done = Decision.objects.filter(idempotency_key=key).first()
    if done:
        return Served(done.action, done.prompt_version, done.provider, done.reason,
                      replayed=True)
    ...
    verdict, pv, reason, attempts = _run_chain(...)
    action = verdict.action if verdict else policy.safe_action

    with transaction.atomic():
        decision, created = Decision.objects.get_or_create(idempotency_key=key, defaults=dict(
            feature=feature, action=action, prompt_version=pv.id if pv else "",
            provider=pv.provider if pv else "", reason=reason, attempts=attempts))
        if created:
            PostAction.objects.create(post_key=key, action=decision.action)
    log.info("llm.decision feature=%s key=%s served_by=%s version=%s reason=%s attempts=%s",
             feature, key, decision.provider or "-", decision.prompt_version or "-",
             decision.reason, decision.attempts)
```

A client retrying after a slow response gets the stored decision back with no provider call. Two truly concurrent requests for one key can both run the chain (paying twice), but the unique constraint allows one `Decision` and one side effect. To avoid paying twice, claim the key first with a pending row.

For agents whose tools write in the middle of the loop, the same rule applies one level down: pass the idempotency key into every write tool. LiteLLM gives the streaming version of the warning: "Do not assume a fallback can transparently restart a response after the client has consumed partial output."

## Step 7: log who served every request

Every attempt is an `Inference` row with `provider`, `attempt`, `error_kind` and `latency_ms`. The primary's first attempt is role `serve`, so Part 9's canary stats still see its errors; later attempts are role `fallback`. The view adds headers for your traces (Part 6):

```python
resp["X-Prompt-Version"] = served.prompt_version or "none"
resp["X-Served-By"] = served.provider or "safe-default"
```

After an incident you'll want to know how many requests the fallback served, how many fell through to `hold`, and whether hold rates moved. LiteLLM records the same fact in its spend logs as `attempted_fallbacks` and `original_model_group`. Whatever you use, make "served by fallback" queryable.

## Keeping a fallback evaluated is a running cost

A fallback that passed in September can rot: serving changes, live moves on, the eval set grows. `recheck_fallbacks()` re-runs evals for live and every enabled fallback and disables any fallback that no longer passes, with a `fallback_disabled` event. A `check_fallbacks` management command runs it from cron. The gate also needs recent shadow pairs (30-day window), so either keep a small shadow sample running on the fallback or plan to re-shadow it before re-enabling.

That costs money every week: shadow calls on a second provider, eval runs on two models, a second account's rate limits to keep sized. Anthropic's refusal docs make the sizing point for their own fallback feature: "Size the fallback model's rate limits for the refusals you expect." The same goes for outages. If your fallback account has a tenth of your primary's rate limit, the first minute of an outage will look like a second outage. Worth it or not depends on what the feature does when nobody answers.

## Trade-offs I'd flag in review

**Fail closed or degrade.** For moderation, failing closed means `hold`: nothing publishes unreviewed, and the review queue fills during an outage. Degrading means serving a weaker but evaluated fallback. For summarisation, "no summary right now" is often fine and cheaper than a second provider. Decide per feature, as `safe_action`.

**Same provider in another region, or another provider.** Another region or deployment of the same model keeps your prompt, tokenizer, refusal behaviour and pricing identical, so the fallback is nearly free to evaluate. It doesn't help when the provider's shared layer fails, as in the November 23 incident above or the 2023 write-up. Another provider covers that case but needs its own prompt version, evals and shadow traffic. You can run both: region first, provider second.

**Refusal failover.** Anthropic's server-side fallback retries only classifier declines; "a rate limit, overload, or server error on the requested model is returned to you as-is." OpenRouter's default fails over on moderation refusals too. Retrying a refusal elsewhere can be right for a coding assistant and wrong for a safety feature, where the refusal is the information.

**Gateway or app code.** A gateway gives every service fallbacks, cooldowns and spend logs at once, but can't know your eval results or which side effects are safe to repeat. My split: transport in the gateway, the evidence gate and idempotency in the app.

## What the tests prove

`pytest -q`: 59 passed (Python 3.13.5, Django 5.2.19, pydantic 2.14.3, pytest 9.2.0, pytest-django 4.14.0). The 34 new tests cover the classification table; the gate refusing a fallback with no eval run, no shadow pairs, a failed must-pass case, loosened decisions or an edited prompt; an unapproved fallback never being called; retry-then-failover with every attempt logged; a 400 stopping without tripping the breaker; refusal policy; `retry-after` longer and shorter than the deadline; shrinking attempt timeouts; `max_attempts`; the breaker's open, skip, single probe and reopen; the ten-minute quota open; repeated keys and failovers running the side effect once; the log line and header; and `recheck_fallbacks` disabling a regressed fallback.

The providers and the clock are scripted. These tests prove the plumbing: what gets called, when, how often and what gets recorded. They say nothing about whether any real model is a good fallback for your feature. Only your eval set and shadow traffic can tell you that, which is the whole point of the gate.

## The series so far

1. [Human-in-the-loop AI agents in Django: approval gates](https://aidevpro.hashnode.dev/human-in-the-loop-ai-agents-django-approval-gates)
2. [Least-privilege agent identity in Django](https://aidevpro.hashnode.dev/ai-agent-least-privilege-identity-django)
3. [Your MCP server is a second API](https://aidevpro.hashnode.dev/mcp-server-django-row-level-permissions-agents)
4. [Permission-aware RAG without post-filters](https://aidevpro.hashnode.dev/permission-aware-rag-django-prefilter)
5. [Cost per successful workflow](https://aidevpro.hashnode.dev/llm-cost-per-successful-workflow-django)
6. [Tracing agent runs with OpenTelemetry](https://aidevpro.hashnode.dev/opentelemetry-tracing-ai-agents-django)
7. [Structured outputs that don't break](https://aidevpro.hashnode.dev/structured-llm-outputs-pydantic-django)
8. [AI moderation helpers with appeals](https://aidevpro.hashnode.dev/ai-content-moderation-django-appeals)
9. [Shipping prompt and model changes safely](https://aidevpro.hashnode.dev/llm-prompt-model-changes-shadow-canary-rollback-django)
10. Provider fallbacks without surprises (this post)

**Next, Part 11:** per-tenant rate limits and token budgets. One noisy customer shouldn't be able to burn your shared provider quota and push everyone onto the fallback.

The demo is the Part 9 app plus `errors.py`, `deadline.py`, `breaker.py`, `chain.py`, `serve.py`, `fallback_gates.py`, a `check_fallbacks` command and `tests/test_fallback.py`.

## Open question for readers

The trade-off I keep going back and forth on: **should a fallback be allowed to be worse than the primary, and by how much?** The demo lets a fallback trail live's eval pass rate by five points and agree with live on 90% of shadow traffic, but never loosen a decision. That's a judgement call. A stricter bar means fewer teams will ever enable a fallback, and they'll fail closed instead. A looser one means your outage behaviour is a different product.

Where do you draw that line? And do you fail over across providers, or only across regions of the same one? I'd like to hear what's worked for you.
