Skip to content

LLM failover: retries, fallbacks, and circuit breakers

LLM failover is what runs after a model call fails. Which errors to retry, the order to add fallbacks and circuit breakers, and what each one costs.

Published
Reading time
14 min read

In short

  • LLM failover is what a client or gateway does after a model call fails: classify the error, retry if the failure can clear, and otherwise move the request to another key, region, provider, or model.
  • Classify before you retry. A rate limit and an exhausted spend cap both return 429, a refusal returns 200, and an invalid request fails on every target you send it to.
  • Every rung has a price. A fallback lands on a cold prompt cache and pays full input price, a different model needs its own evals, and retries add load to a provider that is already overloaded.
  • Once tokens have reached the user, failover can no longer be hidden. Set a time-to-first-token timeout, hold the start of the stream, and decide in advance what the client sees when a stream dies partway.

LLM failover is what a client or gateway does after a model call has failed: classify the error, retry if the failure can clear, and otherwise send the request to another key, region, provider, or model. LLM routing picks a target before the call. Failover decides what happens when that target does not answer.

Each mechanism trades a failed request for a cost somewhere else: a longer wait, a cold prompt cache, an answer from a model nobody evaluated, or extra load on an overloaded provider.

How an LLM call fails, and which failures to retry

An LLM call fails in at least nine distinguishable ways, and only rate limits, overload, and server errors are worth sending to the same target again. The codes below are from the Anthropic, OpenAI, Amazon Bedrock, and Azure OpenAI references as of November 2026.

FailureWhat you receiveResponse
Rate limit429: rate_limit_error on Anthropic, ThrottlingException on BedrockWait as told, or use another key
Spend cap429: organization_spend_limit_exceeded on OpenAI, no retry-after on Anthropic's tier capDo not retry. Fail over or return the error
Overload529 overloaded_error on Anthropic, 503 server_is_overloaded on OpenAI, 503 ServiceUnavailableException on BedrockRetry with backoff, then fail over
Server error500: api_error on Anthropic, InternalServerException on BedrockRetry with backoff
Timeout504 timeout_error on Anthropic, 408 ModelTimeoutException on Bedrock, or your own deadlineFail over
Stream errorAn error event inside a 200: overloaded_error on Anthropic, modelStreamErrorException on BedrockDepends on what the user has seen
Content filter200 with stop_reason: "refusal" on Anthropic, 400 content_filter on Azure OpenAINever retry. Another model is a policy decision
Context length400 "prompt is too long" on Anthropic, context_length_exceeded on OpenAINever retry. Shorten the input or pick a larger window
Bad request or key400, 401, 403, 404Do not retry. Fix the request or the key

Two failures share 429. A rate limit clears in seconds and a spend cap clears next month, and on Anthropic only error.details.error_code, set to enforced_spend_limit_reached, tells them apart. Classify on the code in the body. Virtual keys covers the same ambiguity from the budget side.

A 429 can also arrive under every limit. OpenAI returns slow_down when traffic rises too quickly, and suggests that above 1 million input tokens per minute you raise it by no more than 50% every 15 minutes. Anthropic's ramp limits report ramp_limit_exceeded. Moving a provider's whole traffic onto a fallback at once is the increase those limits reject.

Two rows return 200. A layer that reads only status codes misses refusals and mid-stream errors.

The order to add failover mechanisms

Add mechanisms in order of what they cost: retries first, then other keys and regions, then the same model on another provider, then a different model. Circuit breakers and hedged requests come last, because they pay off only once the chain exists.

TARGETS IN ORDER TRIEDRequestONE CALL INFailover chainONE REQUEST · FOUR RUNGS1Retry on the same key5XX · BACKOFF + JITTER2Rotate to another key429 · NEW ACCOUNT OR REGION3Same model, next providerWHEN THE PROVIDER IS SPENT4Fallback modelLAST · NEEDS ITS OWN EVALSProvider A, key 1503 · RETRY · 429Provider A, key 2503 · RETRIES SPENTProvider BCIRCUIT OPEN, SKIPPEDProvider CFALLBACK MODEL · 200
One request moves down the chain only when the rung above is spent. The open circuit skips Provider B without a call, and a fallback model on Provider C serves the request.

Each rung keeps less of what the request started with. A retry keeps the model, the account, and the prompt cache. A new key keeps the model. A new provider keeps most of the model's behavior. A new model keeps only the request.

Retries with backoff, jitter, and retry-after

Retry a transient failure on the same target once or twice, waiting a random, growing interval that is never shorter than the provider's retry-after.

In the AWS Architecture Blog's backoff and jitter simulation, exponential backoff alone still produced clusters of calls, because clients that failed together retried together. Adding jitter cut the number of calls by more than half with 100 contending clients. The variant the post calls full jitter waits a random time between zero and the capped exponential value.

The retry-after header sets the floor. Anthropic's rate limit docs warn that earlier retries might fail, and OpenAI's rate limit guide says to wait at least that long plus a small random delay. If the wait is longer than the caller's deadline, skip it and move to the next target.

retry.ts
const RETRYABLE = new Set([429, 500, 502, 503, 504, 529]);
const BASE_MS = 500;
const CAP_MS = 8_000;
 
export async function withRetry(send: () => Promise<Response>, maxAttempts = 3): Promise<Response> {
  for (let attempt = 0; ; attempt++) {
    const res = await send();
    const isLast = attempt === maxAttempts - 1;
    if (res.ok || isLast || !RETRYABLE.has(res.status)) return res;
 
    await res.body?.cancel(); // release the connection before waiting
 
    // retry-after is in seconds and is a minimum. Jitter goes on top of it.
    const hintMs = Number(res.headers.get("retry-after") ?? 0) * 1000 || 0;
    const jitterMs = Math.random() * Math.min(CAP_MS, BASE_MS * 2 ** attempt);
    await new Promise((resolve) => setTimeout(resolve, hintMs + jitterMs));
  }
}

A production version also reads the error body, so that a spend-cap 429 is not retried, and enforces a total deadline.

Retry in one layer only. The Amazon Builders' Library works through a stack five services deep in which every layer retries three times, and load on the bottom service is multiplied by 243. An LLM stack has the same shape: provider SDKs retry by default (Anthropic's twice), a gateway retries, and an agent framework retries the step. Pick one layer, usually the gateway, and set the others to zero.

Rotate keys and regions before changing provider

A second key or region serves the same model with the same behavior, so it is the cheapest move after a retry. It helps only when the failure belongs to the key, the account, or the region.

Anthropic sets rate limits at the organization level and OpenAI per organization and project, so two keys from one organization draw on one allowance. Rotation raises the ceiling only across organizations, projects with their own limits, or cloud accounts. Capacity often belongs to the region. For a 503, Amazon Bedrock's troubleshooting guide suggests another AWS Region or cross-Region inference.

The price is the prompt cache, and sometimes compliance. Anthropic isolates caches by organization and, on the Claude API, by workspace, and OpenAI's caches cannot be reused across regional processing boundaries. A region change can also break a data-residency commitment.

Fallbacks: the same model elsewhere first, a different model last

When a provider has used its retries, send the request to another platform that hosts the same model, and switch models only when no such target is left.

The same model on another platform, such as a Claude model on Amazon Bedrock instead of the Claude API, keeps prompts, output formats, and evaluation results valid. Beta features arrive on different dates, and limits, error formats, and cache isolation differ. Before listing a fallback target, send it one request for each feature you depend on.

A different model is a different product. It formats output differently, calls tools differently, refuses different requests, and has its own context window and tokenizer. Treat it as a second production configuration, with its own prompt adjustments and its own run of the evaluation suite.

A refusal sent to a model with different filters changes your content policy, so make that choice on purpose.

Circuit breakers: skip a target that is known to be down

A circuit breaker records that a target is failing and skips it for a cooldown, so new requests stop paying for attempts that are known to fail. Without one, every request during an LLM provider outage waits out its retries on the failed primary before reaching the fallback.

The pattern, popularized by Michael Nygard and described by Martin Fowler, has three states: closed passes calls and counts failures, open rejects them at once, and half-open lets a trial call through to test recovery.

For an LLM circuit breaker, scope, trip signal, and cooldown decide whether it helps:

  • Scope. Keep one breaker per provider, model, and key or region. A rate-limited key must not open the circuit for a healthy one.
  • Trip signal. Count overload, server errors, and timeouts. Leave out 400s and refusals, which are the caller's.
  • Cooldown. Use the provider's retry-after when present, and a fixed interval otherwise.

The Builders' Library notes that circuit breakers add modal behavior that is hard to test and can lengthen recovery. An open breaker moves all traffic to the fallback at once, when cold caches and the fallback's ramp limits arrive together.

Hedged requests for tail latency

A hedged request sends a second copy of a slow request to another target and uses whichever answers first. "The Tail at Scale" describes waiting until the first request has been outstanding longer than the 95th-percentile latency, which limits the extra load to about 5%.

The paper's hedge was a cheap read. An LLM hedge sends the whole prompt to a second target that may bill for it even when the answer is discarded. Hedge on time to first token, cancel the loser when one stream starts, and cap hedges at a few percent of traffic, because in a provider-wide slowdown every request crosses the threshold at once. Add hedging last, where tail latency is the measured problem.

What LLM failover costs

Failover replaces an error with an answer that is slower, more expensive, or different, and each rung adds its own cost.

MechanismWhat it buysWhat it costs
Retry with backoffSurvives a brief failure on the same model and cacheLatency, and load on a failing provider
Key or region rotationMore quota for the same modelA cold prompt cache, a possible change of region
Same model, another providerSurvives a provider outageA cold cache, feature gaps, the fallback's ramp limit
Different modelSurvives a model-wide outageDifferent answers that need their own evals
Circuit breakerNo attempts wasted on a failed targetA second mode to test, all traffic moving at once
Hedged requestA shorter latency tailDuplicate token spend

Prompt caching bills a repeated prefix at a fraction of the input price, and Anthropic's fallback credit docs state that prompt caches are per model. On Anthropic's multipliers, a cache read costs 0.1 times the base input price on most models and a five-minute write 1.25 times, so the first request after a fallback pays 12.5 times what a cache hit would have cost for the prefix, at the same base price. Once a session has moved, keep it on the fallback, because moving it back buys a second cold start.

A fallback model changes answers without raising an error. Run the evaluation suite against it on a schedule, with production prompts, and tag every response with the model that served it.

Agents add side effects. A gateway can resend a model call, which changes nothing, but a tool call may have run even though it timed out. The Builders' Library's rule is that APIs with side effects are not safe to retry unless they are idempotent. The danger is a framework that retries a whole agent step, tool execution included. Give write tools an idempotency key built from the run and the tool call, as the agent loop article describes. MCP tools can carry an idempotentHint, a hint from the server and no guarantee.

Streaming: what failover can do after the first token

Before the first token reaches the user, a streamed request can be retried or moved like any other call. After it, the user has seen output that a second attempt will not reproduce.

In that first window, set a time-to-first-token timeout shorter than the total timeout, and treat a miss as a failover event. Hold the stream's opening events until real output arrives. A provider can send 200 and then an error event before any content, and a layer that has already forwarded the headers can no longer retry.

After the first token there are three options, all visible to the user. Surface the error with the partial answer marked as interrupted, which is the default because it does not alter the answer. Continue from the partial text with a new call, where a seam in long prose is acceptable. Or restart and replace the text, if the interface is built for that.

Anthropic's streaming docs describe continuation as resending the partial response with an instruction to continue, and say that tool use and thinking blocks cannot be partially recovered. Never act on a tool call from an unfinished stream. Tool arguments arrive as partial JSON and are valid only once the block closes.

How a gateway implements the failover chain

A gateway implements the chain as a failure classifier, a retry budget per provider, and an ordered fallback list. Bifrost, an open-source AI gateway by Maxim AI, is a useful worked example, because its retries and fallbacks classify a failure before acting on it.

In the open-source gateway, a transient failure (a network error or a 500, 502, 503, 504, or 529) is retried on the same key with exponential backoff and jitter. A 429 rotates to another key and still backs off, since account quotas can be shared across keys. A 400 is not retried. Retries are off by default and are set per provider.

config.json
{
  "providers": {
    "openai": {
      "keys": [
        { "name": "openai-key-1", "value": "env.OPENAI_KEY_1", "models": ["*"], "weight": 1.0 },
        { "name": "openai-key-2", "value": "env.OPENAI_KEY_2", "models": ["*"], "weight": 1.0 }
      ],
      "network_config": {
        "max_retries": 2,
        "retry_backoff_initial": 500,
        "retry_backoff_max": 5000
      }
    }
  }
}

Fallbacks are a list of provider/model entries on the request or on a routing rule, tried in order after the primary's retries. Each entry gets its own retry budget, so a primary and two fallbacks at max_retries: 3 can make 12 attempts. For streams, ttft_timeout_ms on a rule moves an attempt with no first token to the next fallback without a retry. The retry loop records the provider's retry-after hint but waits by its own backoff formula, and fallbacks named by a caller or a rule also run after a request error such as a 400.

Two features are in Bifrost Enterprise, not in the open-source core. Adaptive routing ranks providers and keys by errors, latency, and load on live traffic, and holds a key that a provider refuses out of rotation on every node. The circuit breaker trips on response headers you choose, per provider and model, and stays open for a cooldown that defaults to 30 seconds.

How to test LLM failover

Test failover by injecting each failure on purpose and on a schedule, because the fallback path otherwise runs for the first time during an outage.

Point the gateway at a stub upstream and, for each case, assert the number of attempts, the total latency, the target that served, and what the client received.

  1. 429 with retry-after: 20. The client waits about 20 seconds or moves to another key.
  2. 429 with a spend-cap body and no header. No retry on that account.
  3. 529 on every call. Attempts stop at the budget and the fallback serves.
  4. 200, then an error event before any content. The client sees one clean stream from the next target.
  5. 200, some tokens, then a dropped connection. The client receives an explicit error.
  6. 400. One attempt, no fallback.

Then, against real providers, open the breaker for the primary in production for ten minutes at low traffic to measure the cold-cache cost, the fallback's ramp limits, and answer quality on the fallback model. Stop a model stream during an agent's tool call and confirm that no tool ran twice.

What to alert on

Alert on the fallback rate first, because failover that works hides the incident that triggered it.

  • Fallback rate per primary target. A rise shows the primary degrading before it is down.
  • Attempts per request, as a mean and a 99th percentile. This measures retry amplification directly.
  • Error rate by class and target. Rate limits, spend caps, overload, and timeouts each need a different response.
  • Requests that exhausted the chain. These are the failures users saw.
  • Mid-stream errors, which a status-code dashboard never counts.

Record an attempt trail on every request: each target tried, the status and error class it returned, and the wait before the next attempt. What to record on every request covers the other fields. For gateways that can run this chain, start with the LiteLLM alternatives comparison.

Frequently asked questions

What is LLM failover?

LLM failover is the logic that runs after a model call fails. It classifies the error, retries failures that can clear, and sends the rest to another key, region, provider, or model.

Should you retry a 429 rate limit error?

Retry a 429 only after checking which kind it is. When a temporary rate limit carries a retry-after header, wait at least that long plus a small random delay, or use a key on another account. A 429 from a spend cap fails until someone raises the limit, so return the error or fail over.

What is an LLM circuit breaker?

An LLM circuit breaker tracks failures per provider, model, and key, and stops sending requests to a target once failures cross a threshold. While the circuit is open, requests go straight to the next target without waiting through retries. After a cooldown, a trial request checks whether the target has recovered.

Does LLM failover work with streaming responses?

LLM failover works fully until the first token is forwarded to the user. Before that, a gateway can retry a stream or move it to another provider without the client noticing. After that, the user has seen partial output, so the choices are to surface an error, continue from the partial text, or replace the answer.

How do you choose an LLM fallback model?

Prefer the same model on another platform, because prompts and evaluation results carry over. If you need a different model, pick one that supports every feature the request uses, such as tool calling, structured output, and a large enough context window. Run your evaluation suite against it before it takes traffic.

Sources

  1. 01ErrorsClaude API docs
  2. 02Rate limitsClaude API docs
  3. 03Streaming messagesClaude API docs
  4. 04Error codesOpenAI API docs
  5. 05Rate limitsOpenAI API docs
  6. 06Troubleshooting Amazon Bedrock API error codesAWS docs
  7. 07Exponential Backoff and JitterAWS Architecture Blog
  8. 08Timeouts, retries, and backoff with jitterAmazon Builders' Library
  9. 09The Tail at ScaleCommunications of the ACM
  10. 10Retries and fallbacksBifrost docs
  11. 11Adaptive routingBifrost docs
  12. 12Circuit breakerBifrost docs