Skip to main content
Back to all articles
AI Engineering 13 min readUpdated October 28, 2026

Your Backup Model Is Not a Failover Plan.

When the primary model provider degrades, production agents need more than retries. Add failure classification, circuit breakers, eval-gated fallbacks, durable workflow state, idempotent side effects, backpressure, and explicit degradation modes.

By Salman Butt · Senior Full-Stack & Generative AI Engineer
#AI Agents#Reliability#Provider Failover#Circuit Breakers#Graceful Degradation#LLM Infrastructure#TypeScript#Python#Production AI
On this page

At 2:17 PM, a support agent is halfway through a refund case.

It has already loaded the customer, read the order, and checked the current refund policy.

The next model call needs to decide whether the case can be handled automatically or must go to a human.

The primary model provider starts returning a mix of timeouts, 429s, and 503s.

The first implementation does what many systems do:

Text
call primary→ fail→ retry→ fail→ retry harder→ fail→ switch model→ restart the agent

That sounds resilient until you look at what the workflow has already done.

Maybe the agent created a case note before the provider failed. Maybe it requested approval. Maybe a refund call returned a timeout after the payment system actually committed it. Maybe the fallback model interprets the tool schema differently from the primary.

Now the outage is no longer just an inference problem.

It is a workflow-state problem, a retry problem, a side-effect problem, and a behavioral-compatibility problem at the same time.

That is why I do not think this is a failover plan:

TypeScript
try {  return await primaryModel(input);} catch {  return await backupModel(input);}

It is a useful primitive.

It is not the architecture.

A backup model becomes a failover target only after you have proved that it can satisfy the same runtime contract.

Failover starts by classifying the failure

Not every failed model request should trigger the same recovery path.

A temporary overload, an invalid API key, a malformed request, an exhausted spend limit, and a caller cancellation are all failures. They are not the same failure.

OpenAI's current API guidance makes this distinction important even inside the same HTTP status family. A temporary 429 can mean a rate-limit or traffic-ramp condition and may include Retry-After. Other 429 errors can represent credit, spend, or usage limits that will not recover because you retried three seconds later. Temporary model overload currently uses 503 with server_is_overloaded.

Anthropic makes a similar distinction: 429 can represent rate-limit or spend-cap conditions, while 529 is a temporary overload response. Its SDKs retry transient failures automatically by default, which also means your application should understand the SDK's retry behavior before wrapping it in another retry loop.

I want that reasoning encoded once, outside the model.

TypeScript
type FailureClass =  | "transient_rate_limit"  | "provider_overload"  | "provider_unavailable"  | "timeout"  | "connection"  | "invalid_request"  | "authentication"  | "permission"  | "billing_or_quota"  | "cancelled"  | "unknown";​type Recovery =  | "retry"  | "failover"  | "defer"  | "stop";​type ClassifiedFailure = {  kind: FailureClass;  recovery: Recovery;  retryAfterMs?: number;};

An adapter for one provider can translate provider-specific errors into the application's failure vocabulary.

TypeScript
function classifyOpenAIError(error: {  status?: number;  code?: string;  retryAfterMs?: number;}): ClassifiedFailure {  // Quota or billing failures must not enter a transient retry loop.  if (new Set([    "insufficient_quota", "credit_balance_exhausted",    "organization_spend_limit_exceeded",    "project_spend_limit_exceeded",    "organization_usage_limit_exceeded",  ]).has(error.code ?? "")) {    return { kind: "billing_or_quota", recovery: "stop" };  }​  if (error.status === 429) {    return {      kind: "transient_rate_limit",      recovery: "retry",      retryAfterMs: error.retryAfterMs,    };  }​  if (error.status === 503 || error.status === 529) {    return { kind: "provider_overload", recovery: "failover" };  }​  if (error.status === 401) {    return {      kind: "authentication",      recovery: "stop",    };  }​  if (error.status === 403) {    return { kind: "permission", recovery: "stop" };  }​  if (error.status === 400 || error.status === 422) {    return {      kind: "invalid_request",      recovery: "stop",    };  }​  if (error.status && error.status >= 500) {    return { kind: "provider_unavailable", recovery: "failover" };  }​  return {    kind: "unknown",    recovery: "stop",  };}

The exact mapping belongs in the provider adapter because APIs evolve.

The important property is that the rest of the agent does not say:

Text
HTTP error → retry

It receives a recovery decision based on what actually failed.

Retry and failover solve different problems

A retry says:

I believe this operation may succeed if I try the same dependency again after a bounded delay.

Failover says:

I believe this dependency is unhealthy enough that another already-approved route is now preferable.

Those are different decisions.

Microsoft's Circuit Breaker guidance draws the same boundary: retry is for faults expected to recover shortly, while a circuit breaker stops repeatedly calling a dependency that is likely to keep failing.

For temporary conditions, I follow the provider's Retry-After when available. Otherwise I use exponential backoff with jitter.

TypeScript
function backoffMs(  attempt: number,  baseMs = 250,  maxMs = 8_000,): number {  const exponential = Math.min(    maxMs,    baseMs * 2 ** attempt,  );​  const jitter = Math.random() * exponential * 0.25;​  return Math.min(maxMs, exponential + jitter);}

But there are two budgets:

Text
attempt budgetandtotal retry-time budget

If the request has already burned eight seconds retrying, I do not want one more retry simply because maxAttempts says there is one left.

TypeScript
type RetryBudget = {  maxAttempts: number;  deadlineAt: number;};​function mayRetry(  attempt: number,  delayMs: number,  budget: RetryBudget,): boolean {  return (    attempt < budget.maxAttempts &&    Date.now() + delayMs < budget.deadlineAt  );}

A retry loop without a time budget can turn a short provider incident into your own latency incident.

The circuit breaker is there to stop outage amplification

Suppose a provider is returning 503s for most requests.

Without a breaker, every new user request can perform this sequence:

Text
primaryretryretryretryfallback

Now multiply that by a thousand concurrent requests.

The provider is already unhealthy, and your application is sending it more work because it is unhealthy.

That is outage amplification.

A circuit breaker gives the dependency three states:

Text
closed  normal requests are allowed​open  requests fail fast or route elsewhere​half-open  a small number of probes test recovery

I keep the breaker outside the LLM orchestration logic.

TypeScript
type BreakerState = "closed" | "open" | "half_open";type ProbePermit = Readonly<{ id: number; epoch: number; probe: boolean }>;​class CircuitBreaker {  private state: BreakerState = "closed";  private failures = 0;  private openedAt = 0;  private epoch = 0;  private probesInFlight = 0;  private successfulProbes = 0;  private nextPermitId = 0;  private readonly unsettled = new Set<number>();​  constructor(    private readonly failureThreshold = 5,    private readonly openForMs = 20_000,    private readonly halfOpenLimit = 2,  ) {    if (failureThreshold < 1 || openForMs < 1 || halfOpenLimit < 1) {      throw new RangeError("Invalid circuit breaker policy");    }  }​  begin(): ProbePermit | null {    if (this.state === "open") {      if (Date.now() - this.openedAt < this.openForMs) return null;      this.state = "half_open";    }    if (this.state === "half_open") {      if (this.probesInFlight >= this.halfOpenLimit ||          this.successfulProbes + this.probesInFlight >= this.halfOpenLimit) {        return null;      }      this.probesInFlight++;      const permit = { id: ++this.nextPermitId, epoch: this.epoch, probe: true };      this.unsettled.add(permit.id);      return permit;    }    const permit = { id: ++this.nextPermitId, epoch: this.epoch, probe: false };    this.unsettled.add(permit.id);    return permit;  }​  success(permit: ProbePermit): void {    if (permit.epoch !== this.epoch ||        !this.unsettled.delete(permit.id)) return; // Old or duplicate result.    if (this.state === "half_open" && permit.probe) {      this.probesInFlight--;      this.successfulProbes++;      if (this.successfulProbes >= this.halfOpenLimit &&          this.probesInFlight === 0) {        this.state = "closed";        this.failures = 0;        this.epoch++; // Invalidate all old permits.        this.unsettled.clear();      }      return;    }    if (this.state === "closed" && !permit.probe) this.failures = 0;  }​  failure(permit: ProbePermit): void {    if (permit.epoch !== this.epoch ||        !this.unsettled.delete(permit.id)) return;    if (this.state === "half_open" && permit.probe) {      this.open();      return;    }    if (this.state !== "closed" || permit.probe) return;    if (++this.failures >= this.failureThreshold) this.open();  }​  private open(): void {    this.state = "open";    this.openedAt = Date.now();    this.epoch++; // Ignore late callbacks from an older state.    this.failures = 0;    this.probesInFlight = 0;    this.successfulProbes = 0;    this.unsettled.clear();  }}

Here, begin() returns a permit that must accompany the corresponding success(permit) or failure(permit). Late responses from an older breaker epoch cannot close a newly opened breaker. Duplicate completion callbacks also cannot be counted twice; each permit is settled at most once. Half-open mode must collect the configured number of successful probes before reopening normal traffic; the caller must always settle an admitted permit, including on cancellation and timeout.

This is illustrative. A production breaker normally uses rolling windows, shared or replica-aware health, metrics, and more careful concurrency control. The in-memory demo does not coordinate across server replicas.

What matters is the behavior: once the dependency is clearly unhealthy, stop making every user rediscover that fact through a timeout.

Half-open mode also matters. When a provider recovers, I do not want the full backlog to hit it simultaneously. A small number of probes should earn the transition back to normal traffic.

Provider failover and model fallback are not the same thing

There are two useful layers of fallback.

Same model, another provider route

If the same model is available through more than one approved hosting route, failing over between providers can preserve more of the behavior contract.

It is still not automatically identical. Provider wrappers can differ in supported options, rate limits, tool semantics, caching, latency, and regional behavior.

But this is operationally different from changing the model itself.

Different model

A different model is a behavioral change.

It may produce valid HTTP responses and still differ in:

Text
tool selectionstructured outputcontext limitsreasoning behaviorrefusal behaviormultimodal supportparallel tool callinglatencycost

Vercel AI Gateway exposes both ideas explicitly: provider ordering can try another host, while model fallbacks can move to another model if the preferred model cannot serve the request.

The routing feature is useful.

It does not remove the need to decide whether the fallback model is safe for *your* workflow.

I treat every fallback model as a pre-approved release candidate.

This is the same principle from my model migration article: API compatibility is not behavioral compatibility.

Before a model enters the fallback set, it should pass the application's eval suite for the workloads it may inherit.

TypeScript
type ModelRoute = {  id: string;  provider: string;  model: string;  capabilities: Set<string>;  evalReleaseId: string;  allowedRisk: "low" | "medium" | "high";};​function canServe(  route: ModelRoute,  request: {    requiredCapabilities: string[];    risk: "low" | "medium" | "high";  },): boolean {  const hasCapabilities = request.requiredCapabilities.every(    (capability) => route.capabilities.has(capability),  );​  const riskOrder = {    low: 0,    medium: 1,    high: 2,  } as const;​  return (    hasCapabilities &&    riskOrder[route.allowedRisk] >= riskOrder[request.risk]  );}

Now fallback is not:

Text
whatever model is alive

It is:

Text
an already-evaluated route that is allowed to handle this capability and risk tier

That is a much stronger production contract.

The workflow should survive the provider change

This is the part that matters most for agents.

A provider outage may happen on model call number seven of a twenty-step task.

I do not want failover to mean:

Text
restart task from step 1

The workflow state should survive the inference process.

TypeScript
type WorkflowCheckpoint = {  runId: string;  version: number;  state: "running" | "waiting" | "degraded" | "complete";  completedSteps: string[];  currentStep: string;  evidenceVersion: string;  policyVersion: string;  sideEffects: Array<{    action: string;    idempotencyKey: string;    status: "not_started" | "unknown" | "completed";  }>;};

Persist that state before and after consequential boundaries.

The model provider should be replaceable while the workflow remains the same workflow.

Text
agent run 8421  checkpoint v8  evidence already collected  approval already recorded  side effect not yet started  next step = decision

If the primary model becomes unavailable, the fallback model resumes from checkpoint v8.

It does not re-fetch everything by default.

It does not request the same approval again.

It does not invent a new run ID.

And it does not replay prior writes just because the inference backend changed.

A timeout after a side effect is the dangerous boundary

Suppose the agent calls:

Text
issue_refund(idempotency_key=refund_8421)

The payment system commits the refund.

The response is lost.

Then the model provider times out while the agent is deciding what to do next.

If failover restarts the workflow and calls issue_refund again with a new key, your resilience layer has created a duplicate refund.

This is why provider failover has to compose with idempotent side-effect execution.

The persisted state should say:

Text
refund_8421 = unknown

Unknown does not mean failed.

Before retrying the write, reconcile it.

TypeScript
async function recoverUnknownRefund(  checkpoint: WorkflowCheckpoint,  lookup: (key: string) => Promise<"missing" | "completed">,) {  const refund = checkpoint.sideEffects.find(    (item) => item.action === "issue_refund",  );​  if (!refund || refund.status !== "unknown") {    return;  }​  const remote = await lookup(refund.idempotencyKey);​  if (remote === "completed") {    refund.status = "completed";    return;  }​  // Only the trusted executor may decide whether retry is now safe.}

The fallback model should never be handed an ambiguous side-effect state and asked:

Do you think we should just try again?

That decision belongs at the executor boundary.

The architecture I would ship

The model router is only one part of the recovery path.

Provider failover architecture for production agents

The order matters.

First classify the failure.

Then decide whether a bounded retry is justified.

If the dependency is persistently unhealthy, trip the breaker and stop sending it normal traffic.

Use only a pre-evaluated fallback route.

Resume the durable workflow rather than restarting it.

And keep side effects behind an idempotent executor that can reconcile unknown outcomes.

If no safe route exists, degrade deliberately.

Graceful degradation is part of the feature

The worst fallback is often a lower-quality model silently pretending that the full product is still available.

Sometimes the correct degraded mode is smaller.

For example:

Text
normal mode  answer + tools + writes​provider degraded  read-only answers from verified sources​all inference unavailable  queue task for later  or hand off to human​high-risk workflow without compatible fallback  stop safely

I like making that mode explicit in application state.

TypeScript
type DegradedMode =  | "none"  | "read_only"  | "queue"  | "human";​type RouteDecision =  | {      kind: "model";      route: ModelRoute;    }  | {      kind: "degraded";      mode: DegradedMode;      reason: string;    };

A customer-support assistant might continue answering FAQ questions while temporarily disabling refunds.

A coding assistant might keep read-only code explanation but stop creating pull requests.

An infrastructure agent might stop all mutations and surface the current incident context to an operator.

That is not a failed failover.

That is a system preserving its safety contract while a dependency is unavailable.

Backpressure matters when every provider is unhealthy

Provider outages create queues.

Queues create latency.

Latency creates retries from impatient clients.

Those retries create more queues.

If the application accepts unlimited new work while all model routes are unhealthy, a ten-minute provider incident can become a forty-minute recovery problem because the system spends the next half hour draining stale requests.

I want admission control.

TypeScript
type AdmissionPolicy = {  maxQueueDepth: number;  maxQueueAgeMs: number;};​function admit(  queueDepth: number,  oldestAgeMs: number,  policy: AdmissionPolicy,): "accept" | "reject" {  if (    queueDepth >= policy.maxQueueDepth ||    oldestAgeMs >= policy.maxQueueAgeMs  ) {    return "reject";  }​  return "accept";}

Rejecting or deferring work can feel less resilient than accepting everything.

During an outage, it is often the opposite.

A bounded queue protects recovery.

I would rather tell a user:

Text
This task is temporarily queued.

than keep a request alive for ninety seconds, retry three providers, and fail anyway.

Hedging is powerful and easy to misuse

For latency-sensitive inference, you may be tempted to send the same request to two providers and take whichever returns first.

That is request hedging.

It can reduce tail latency.

It can also double cost, duplicate data exposure, consume scarce provider quota, and create two active agent trajectories if the model call is allowed to execute tools.

My default policy is:

Text
hedge pure inference only

For example, a read-only classification call with no tools and no side effects can be a reasonable candidate.

A live agent turn that can call issue_refund is not.

If I hedge a model call at all, I keep the competing requests behind a boundary where neither can commit an external action. The winning model output can then enter the normal trusted executor.

Also remember that cancellation is not billing rollback. Vercel's current provider-timeout guidance notes that some providers may still charge for a timed-out request if stream cancellation is not supported.

A hedge should have a measured latency benefit large enough to justify that cost and privacy surface.

Streaming failures need a separate recovery rule

A failover gateway is easiest when the request fails before output begins.

Streaming changes that.

The user may already have seen:

Text
Your refund is eligible because...

Then the stream dies.

OpenAI's current rate-limit guidance explicitly notes that errors can occur after streaming begins and that you should not automatically replay a request after consuming output. Anthropic likewise documents that SSE streams can emit errors after the initial 200 response.

I do not want to silently append a second model's continuation to the first model's partial output as if one model wrote the whole thing.

For user-visible text, choose an explicit policy:

Text
before first output token  failover transparently​after output has been committed to user  mark turn interrupted  retry as a new generation if safe  or ask the user to retry

For agent-internal structured inference, it is often simpler: do not commit partial structured state until the response has validated completely.

Streaming is a presentation optimization.

It should not create partially trusted workflow state.

Revalidate after a long outage

A workflow can sit in degraded mode for twenty minutes and then resume.

The checkpoint is durable.

Reality may not be.

Before a consequential action, revalidate volatile assumptions:

Text
Is the user still authorized?Is the evidence still current?Did another worker already complete the action?Did the policy change during the outage?Is the approval still valid for these exact arguments?

A durable checkpoint preserves what the workflow knew.

It does not guarantee that knowledge is still current.

This is the same gap I care about after human review: resumability should preserve work without freezing the outside world.

Python version of the recovery policy

The same architecture is straightforward to express without tying it to one framework.

Python
from dataclasses import dataclassfrom enum import Enumfrom typing import Literal​​class BreakerState(str, Enum):    CLOSED = "closed"    OPEN = "open"    HALF_OPEN = "half_open"​​Recovery = Literal[    "retry",    "failover",    "defer",    "stop",]​​@dataclass(frozen=True)class Failure:    kind: str    recovery: Recovery    retry_after_seconds: float | None = None​​@dataclass(frozen=True)class Route:    provider: str    model: str    eval_release_id: str    capabilities: frozenset[str]    allowed_risk: Literal["low", "medium", "high"]​​def compatible(    route: Route,    *,    capabilities: set[str],    risk: Literal["low", "medium", "high"],) -> bool:    risk_order = {        "low": 0,        "medium": 1,        "high": 2,    }​    return (        capabilities.issubset(route.capabilities)        and risk_order[route.allowed_risk] >= risk_order[risk]    )

The router can then stay small:

Python
async def choose_route(    *,    primary: Route,    fallbacks: list[Route],    breaker,    required_capabilities: set[str],    risk: str,):    if breaker.allow() and compatible(        primary,        capabilities=required_capabilities,        risk=risk,    ):        return primary​    for route in fallbacks:        if compatible(            route,            capabilities=required_capabilities,            risk=risk,        ):            return route​    return None

None is not an invitation for the model to improvise another provider.

It means the application moves into its declared degraded mode.

Test the outage path before you need it

A fallback that has never been exercised is a configuration value, not a reliability mechanism.

I want failure injection in the eval suite.

FailureExpected behavior
Temporary rate limit with Retry-AfterBounded retry, no burst
Repeated provider overloadBreaker opens, failover begins
Authentication failureStop; do not hammer fallback routes blindly
Billing/spend limitStop or operator action; not infinite retry
Primary fails before any side effectResume same checkpoint on compatible fallback
Write may have committed before timeoutReconcile by idempotency key before retry
Fallback emits incompatible tool argumentsEval/release gate fails
Both providers unavailableEnter declared degraded mode
Half-open probe succeedsRestore traffic gradually
Half-open probe failsReopen breaker
User already received partial streamDo not transparently replay the whole turn
Backlog exceeds policyApply admission control

The important test is not:

Text
Can provider B answer a prompt?

It is:

Text
Can the complete workflow preserve its invariants when inference moves from route A to route B at an inconvenient point?

That is a much harder test.

It is also the one production will eventually run for you.

Add failover behavior to trajectory evals

The previous article in this series focused on evaluating the agent's execution trajectory.

Provider recovery belongs in that trace too.

A healthy failover path might look like:

Text
checkpoint v8primary timeoutretry-after honoredsecond failurebreaker openfallback selected: release fallback-v4checkpoint v8 loadedpolicy revalidatedinference succeedsidempotent executor runs action Kresult verifiedcheckpoint v9

A bad path might be:

Text
primary timeoutrestart workflowrequest approval againissue action with new idempotency keyswitch modelissue action again

The final answer could still be correct.

The path is unacceptable.

This is exactly why resilience behavior should be part of agent evals rather than treated as an infrastructure-only concern.

Run shadow failover without duplicating real actions

Before sending live traffic to a new fallback, I like a shadow phase.

The primary route serves the user.

The candidate fallback receives equivalent inputs and produces a trajectory for comparison.

But its side effects must be disabled, sandboxed, or converted into proposed actions.

Text
primary  → real tools  → real response​fallback shadow  → read-only tools / mocks  → proposed actions only  → eval

Compare:

Text
final task qualitytool selectionargument validityabstention behaviortrajectory invariantslatencycost

Then canary the fallback policy before declaring it production-ready.

Do not wait for a real provider outage to discover that your backup model cannot produce a required structured tool call.

Monitor the recovery system, not just provider uptime

A status page can tell me the provider is degraded.

It cannot tell me whether *my failover path* is healthy.

I want application metrics:

Text
primary success rateprimary 429 / overload / timeout rateretry attempts per requestretry amplificationcircuit-open durationhalf-open success ratefailover activation ratefallback task success ratefallback schema/tool validation failuresdegraded-mode ratequeue deptholdest queued task ageadmission rejection rateduplicate side-effect rateunknown-side-effect reconciliation ratep95 / p99 latency during failovercost per recovered task

I also record which route actually served the inference.

Vercel AI Gateway exposes attempt/provider metadata for this reason: a response that succeeded after failover should not look operationally identical to a response that succeeded on the first route.

Success after three failed providers is useful information.

So is success that cost four times as much as normal.

Provider diversity is not always failure diversity

Two provider names do not automatically give you two independent systems.

They may share:

Text
cloud regionmodel familyupstream infrastructurenetwork pathidentity dependencybilling accountDNS or gateway layer

The same is true for your own architecture.

If both providers are behind one internal gateway and that gateway fails, provider diversity did nothing.

If both routes depend on the same unavailable secrets service, they are not operationally independent either.

When the workflow is important enough to justify multi-provider resilience, map the dependency graph.

Ask:

Text
What failure does this fallback actually isolate?

Sometimes the answer is provider capacity.

Sometimes it is region loss.

Sometimes it is only a model-specific overload.

Know which one you bought.

When I would not fail over

There are cases where the safest response is to stop.

I would not automatically move a high-risk workflow to a model that has never passed its authorization/tool-use evals.

I would not fail over a malformed request to five providers hoping one is more tolerant.

I would not route around an authentication failure without first knowing whether the alternate credential path is intended.

I would not replay an already-partially-consumed stream as though nothing happened.

And I would not switch providers if data residency, contractual, or privacy policy excludes the fallback destination for this request.

Resilience does not mean:

Text
always produce an answer

It means:

Text
preserve the service's important guarantees while dependencies fail

Sometimes the only way to preserve those guarantees is a clean degraded response.

The production rule I would keep

I do want multiple model routes for important agent systems.

I just do not want failover reduced to a list of provider names.

A production failover plan needs the surrounding control system:

Text
classify failureshonor retry hintsbound retries by attempts and timeopen the circuit on persistent failuresend only a small number of recovery probesuse only eval-gated fallback routespreserve durable workflow checkpointsreconcile unknown side effectsreuse idempotency keysapply backpressure when capacity disappearsrevalidate stale evidence before resumingexpose a deliberate degraded modemeasure the failover path itself

That is more work than adding a second model ID.

It is also what makes the second model useful during an actual incident.

Failover is not `try provider B`. It is a policy for preserving task semantics, safety, and side-effect state while inference is degraded.

And the test I care about is not whether the backup model is online.

It is whether the user can survive the provider outage without your agent forgetting what it already did, doing anything twice, or quietly becoming a different product.

References

KEEP READING

Related engineering notes