LLM Fallback Circuit Breaker in Node.js: A Tested Design

LLM fallback circuit breaker for Node.js: disable hidden SDK retries, classify 429 and 529 errors, and cut calls to a failing provider from 3,554 to 7.

TL;DR

  • What: An LLM fallback circuit breaker stops calling a failing model provider and routes requests to a backup.
  • Why it matters: SDK default retries hit a failing provider three times per request before your fallback runs.
  • What to do: Set maxRetries: 0, classify errors, trip on 5 consecutive failures, cap the open timer.
  • Key stat: In our simulated 60-second outage, calls to the failing provider fell from 3,554 to 7.

An LLM fallback circuit breaker wraps each model provider in a closed/open/half-open state machine. Turn off SDK retries, count only provider-health errors (429 throttling, 5xx, 529, timeouts), trip after a few consecutive failures, send traffic to the next provider while open, and probe with one request before closing again.

A circuit breaker is a proxy that monitors failures of a remote call and, past a threshold, fails fast instead of calling the dependency, then tests recovery with limited trial requests (Azure Architecture Center). An LLM fallback circuit breaker applies one breaker per model provider and routes rejected calls to the next provider in a preference list.

An LLM fallback circuit breaker is the piece most multi-provider setups skip. Teams add a second provider, wrap the call in try/catch, and assume failover works. Then the primary returns 529 overloaded_error, which Anthropic says can happen “when the API experiences high traffic across all users”, and every user request waits through hidden SDK retries before the fallback even starts. The Anthropic SDK retries a failed request up to two times (three attempts in all) by default, and OpenAI’s Node SDK uses the same default of 2 retries. So your fallback code runs late, and your failing provider receives triple the traffic while it is trying to recover.

This guide builds a small, tested design in Node.js: an error classifier, a per-provider breaker and a router. We ran it against a simulated outage to measure what each choice costs. It also covers the gotcha the top tutorials miss: the two official SDKs treat a long Retry-After header differently.

What is an LLM fallback circuit breaker and when do you need one?

An LLM fallback circuit breaker is a per-provider state machine that decides whether a request should go to that provider at all. You need one as soon as you have two providers and real traffic. Without it, every request rediscovers the outage on its own.

The pattern has three states, as described by Microsoft’s Circuit Breaker pattern and Martin Fowler’s bliki entry:

  1. Closed: requests flow; the breaker counts recent failures in a time-based window.
  2. Open: requests fail fast; the router skips this provider until a timer expires.
  3. Half-open: a limited number of trial requests pass; success closes the breaker, any failure reopens it.

Azure’s guidance also names two ideas that matter for LLMs. “Resource differentiation” means one breaker per independent provider, never one shared breaker. “Accelerated circuit breaking” means an error that already tells you to wait should trip the breaker immediately.

My recommendation: skip the breaker only if you have a single provider and nowhere to fail over. Then plain retries with backoff and a budget, covered in our retry storm prevention guide, are enough.

Why do SDK default retries delay LLM failover?

SDK default retries delay failover because they run inside the client call, so your router sees nothing until all attempts are exhausted. Both official Node SDKs retry connection errors, timeouts, 408, 409, 429 and 5xx responses by default.

What we found in the SDK source

We read client.js in @anthropic-ai/sdk 1.14.0 and openai 7.65.0, the current npm releases on the day of writing. Both set DEFAULT_TIMEOUT = 600000, which is 10 minutes per attempt. Both compute backoff as min(0.5 × 2n, 8) seconds with up to 25% jitter. With 3 attempts and a 10-minute timeout, a hung provider can hold one request for 30 minutes before your fallback sees an error.

The two SDKs then diverge on Retry-After:

  • The OpenAI SDK ignores a server-requested delay over 60 seconds and uses its own backoff instead.
  • The Anthropic SDK honors any positive delay up to 231−1 ms, the largest value one timer can hold.

So the same “retry after 120 seconds” response produces a fast retry in one SDK and a two-minute sleep in the other. Neither is wrong. But inside a fallback router, both are the wrong layer to decide. Set maxRetries: 0 on each client and let the router own retry, wait and failover decisions.

Which LLM API errors should trip the breaker?

Only errors that describe provider health should trip the breaker. Errors caused by your request must not. A 400 for a malformed request fails the same way on every provider, so failing over just doubles the cost of a bug.

LLM API errors and how a fallback circuit breaker should treat them
Error What the provider says Breaker action
Anthropic 529 overloaded_error Temporarily overloaded, across all users Transient: count it, fail over
OpenAI 503 server_is_overloaded Model temporarily overloaded Transient: count it, fail over
OpenAI 429 slow_down Rate increased too quickly, even within RPM/TPM limits Transient: count it, honor Retry-After as open time
Anthropic 429 enforced_spend_limit_reached Spend cap; no retry-after, keeps failing Hard: open for the maximum time
OpenAI 429 spend, usage or credit codes Retrying won’t restore API access Hard: open for the maximum time
Anthropic 500 api_error Retry only if x-should-retry isn’t false Transient
400, 401, 403, 404, 413 Problem with your request or key Caller: surface it, no failover

OpenAI’s ramp-rate guidance is worth reading before you blame the provider: once traffic reaches 1 million input tokens per minute, increase it by no more than 50% every 15 minutes. Shaping your own traffic, as in our rate limiter system design guide, prevents many of these 429s.

The streaming blind spot

A streamed response can fail after the API has already returned HTTP 200. Anthropic’s docs state that in this case error handling “doesn’t follow these standard mechanisms” and that the SDK doesn’t retry an error in a stream. A breaker that only inspects status codes never sees these failures. Record a mid-stream error event as a transient failure, and only fail over if you have not yet sent tokens to the user.

How do you build an LLM fallback circuit breaker in Node.js?

Build it in three small modules: a breaker per provider, a classifier, and a router that walks the provider list. The code below ran on Node.js 22.23.5. You could use opossum instead; its README documents a 50% error threshold and a rolling window of 10 seconds in 10 buckets. We wrote our own because LLM errors need three outcomes, not two.

Step 1: the breaker and classifier

The breaker trips on either an error rate over a rolling window or a streak of consecutive failures. Each re-trip doubles the open time, capped by maxOpenMs. Azure’s guidance suggests this increasing time-out timer for faults that persist.

// Per-provider circuit breaker with a rolling window (time is injected so we can simulate).
export class ProviderBreaker {
  constructor({ consecutive = Infinity, windowMs = 10_000, minVolume = 10, errorRate = 0.5, openMs = 15_000, maxOpenMs = 120_000, now = Date.now } = {}) {
    Object.assign(this, { consecutive, windowMs, minVolume, errorRate, openMs, maxOpenMs, now });
    this.events = []; this.state = 'closed'; this.openUntil = 0; this.trips = 0; this.probeInFlight = false; this.streak = 0;
  }
  canRequest() {
    const t = this.now();
    if (this.state === 'open' && t >= this.openUntil) this.state = 'half-open';
    if (this.state === 'half-open') {
      if (this.probeInFlight) return false;
      this.probeInFlight = true; return true;          // exactly one trial request
    }
    return this.state === 'closed';
  }
  record(outcome, { retryAfterMs } = {}) {             // outcome: 'ok' | 'transient' | 'hard'
    const t = this.now();
    if (this.state === 'half-open') {
      this.probeInFlight = false;
      if (outcome === 'ok') { this.state = 'closed'; this.events = []; this.trips = 0; this.streak = 0; return; }
      return this.trip(retryAfterMs);
    }
    if (outcome === 'hard') return this.trip(retryAfterMs ?? this.maxOpenMs); // quota/spend cap: no point probing soon
    this.streak = outcome === 'ok' ? 0 : this.streak + 1;
    if (this.streak >= this.consecutive) return this.trip(retryAfterMs); // fast path: N failures in a row
    this.events.push({ t, bad: outcome !== 'ok' });
    this.events = this.events.filter(e => t - e.t <= this.windowMs);
    const bad = this.events.filter(e => e.bad).length;
    if (this.events.length >= this.minVolume && bad / this.events.length >= this.errorRate) this.trip(retryAfterMs);
  }
  trip(retryAfterMs) {
    this.trips++; this.totalTrips = (this.totalTrips ?? 0) + 1;
    const backoff = Math.min(this.openMs * 2 ** (this.trips - 1), this.maxOpenMs); // open longer each time it re-trips
    this.streak = 0; this.state = 'open'; this.openUntil = this.now() + Math.max(backoff, retryAfterMs ?? 0); this.events = [];
  }
}

// Map provider errors to breaker outcomes. 4xx caller bugs are NOT provider health signals.
export function classify(err) {
  const s = err.status;
  if (s === 429 && /spend|quota|credit|billing|usage_limit/i.test(err.code ?? '')) return 'hard';
  if (s === 408 || s === 409 || s === 429 || s >= 500 || err.name === 'TimeoutError' || s === undefined) return 'transient';
  return 'caller';   // 400/401/403/404/413: fix the request, don't fail over
}

Step 2: the router

The router asks each breaker for permission, calls the provider with a timeout, and records the outcome. Caller errors are rethrown at once. A Retry-After header becomes the minimum open time, which is Azure’s “accelerated circuit breaking” in practice.

import { ProviderBreaker, classify } from './breaker.mjs';

// providers: [{ name, call: (req, { signal }) => Promise<string> }] in preference order
export function createRouter(providers, { timeoutMs = 30_000, breakerOpts = {} } = {}) {
  const breakers = new Map(providers.map(p => [p.name, new ProviderBreaker({ consecutive: 5, maxOpenMs: 30_000, ...breakerOpts })]));
  return async function complete(req) {
    const tried = [];
    for (const p of providers) {
      const breaker = breakers.get(p.name);
      if (!breaker.canRequest()) { tried.push(`${p.name}:open`); continue; }
      try {
        const text = await p.call(req, { signal: AbortSignal.timeout(timeoutMs) });
        breaker.record('ok');
        return { provider: p.name, text, tried };
      } catch (err) {
        const kind = classify({ ...err, status: err.status, code: err.errorCode ?? err.code, name: err.name });
        if (kind === 'caller') { breaker.record('ok'); throw err; }   // provider answered; the request is wrong and would fail everywhere
        const ra = Number(err.headers?.get?.('retry-after'));
        breaker.record(kind, { retryAfterMs: Number.isFinite(ra) && ra > 0 ? ra * 1000 : undefined });
        tried.push(`${p.name}:${err.status ?? err.name}`);
      }
    }
    const e = new Error(`All LLM providers failed: ${tried.join(', ')}`); e.status = 503; throw e;
  };
}

Step 3: wire the real SDKs

Each provider gets its own client with retries disabled. The model names come from environment variables, so you can swap models without a deploy.

import Anthropic from '@anthropic-ai/sdk';
import OpenAI from 'openai';
import { createRouter } from './router.mjs';

// maxRetries: 0 — the router owns retry/failover; SDK retries would hide failures from the breaker.
const anthropic = new Anthropic({ maxRetries: 0, timeout: 30_000 });
const openai = new OpenAI({ maxRetries: 0, timeout: 30_000 });

export const complete = createRouter([
  { name: 'anthropic', call: async ({ prompt }, { signal }) => {
      const msg = await anthropic.messages.create(
        { model: process.env.PRIMARY_MODEL, max_tokens: 1024, messages: [{ role: 'user', content: prompt }] },
        { signal });
      return msg.content.filter(b => b.type === 'text').map(b => b.text).join('');
  } },
  { name: 'openai', call: async ({ prompt }, { signal }) => {
      const res = await openai.responses.create({ model: process.env.FALLBACK_MODEL, input: prompt }, { signal });
      return res.output_text;
  } },
]);

We loaded this file against the real SDK packages to confirm the imports and constructors work. We did not send live API calls; the behavior tests used stub providers.

How did the LLM fallback circuit breaker perform in a simulated outage?

The LLM fallback circuit breaker cut calls to the failing provider by 99.8% in our simulation, from 3,554 to 7. We ran a deterministic, virtual-clock simulation in Node.js 22.23.5: 20 requests per second for 120 seconds, with the primary returning 529 from second 10 to second 70.

Modelled latencies were 1,500 ms for a primary success, 200 ms for a primary failure and 1,800 ms for a fallback success. The sdk-defaults row uses the SDKs’ own backoff formula with 3 attempts. Command: node sim.mjs.

┌───────────────────────────────────┬──────────────────────────┬───────────────┬─────────────┬─────────────┐
│ strategy                          │ primaryCallsDuringOutage │ fallbackCalls │ outageP50ms │ outageP95ms │
├───────────────────────────────────┼──────────────────────────┼───────────────┼─────────────┼─────────────┤
│ 'sdk-defaults'                    │ 3554                     │ 1166          │ 3707        │ 3839        │
│ 'breaker maxOpen=120s'            │ 116                      │ 2200          │ 1800        │ 2000        │
│ 'breaker maxOpen=30s'             │ 116                      │ 1625          │ 1800        │ 2000        │
│ 'breaker maxOpen=30s +5-in-a-row' │ 7                        │ 1516          │ 1800        │ 1800        │
└───────────────────────────────────┴──────────────────────────┴───────────────┴─────────────┴─────────────┘

Three findings matter more than the headline:

  1. SDK defaults roughly tripled load on the sick provider. That matches Marc Brooker’s analysis that with N retries at a 100% failure rate the system does 1+N times as much work. Median latency during the outage was 3,707 ms against 1,800 ms with a breaker.
  2. A rate-only breaker tripped late. It took 116 calls, about 5.7 seconds, because the 10-second window was still full of earlier successes. Adding a 5-in-a-row trigger cut that to 7 calls.
  3. A long open timer overshoots recovery. With a 120-second cap the breaker stayed open long after the outage ended, sending 2,200 requests to the fallback. A 30-second cap sent 1,625; adding the streak trigger sent 1,516. The ideal was 1,200, the number of requests inside the outage.

These are simulated numbers, not production measurements. Change the constants at the top of sim.mjs to match your own traffic and latencies before choosing thresholds.

Should breaker state live in Redis or in each Node.js process?

Start with per-process state, and move to shared state only when you run many small instances. Per-process breakers need no network call and cannot fail on their own.

The catch is accuracy. Brooker simulated 100 independent clients and found client-side breakers started tripping at around half the expected rate, because each client sees only a small sample. He notes this is “especially important in serverless and container-based architectures”. Shared state fixes that, but he also warns it would “significantly increase the complexity of the system”.

A practical middle ground: keep the breaker local, and add a consecutive-failure trigger, which works well even with small samples. Azure’s guidance also recommends a manual override so an operator can force a provider open or closed during an incident. An environment flag read by the router covers that.

What breaks when an LLM fallback circuit breaker switches models?

Output shape and limits break first. A fallback model has a different context window, different tool-call behavior and different refusal style, so “success” from the fallback can still be a failure for your feature.

  • Context limits: a prompt that fits the primary can exceed the fallback. Count and trim per model, as in our LLM context length exceeded fix. That error is a caller error, so it must not trip the fallback’s breaker.
  • Structured output: validate JSON from every provider with the same schema. Do not trust that both follow it the same way.
  • A cheaper last resort: when every breaker is open, a cached answer may beat an error. Our semantic caching guide explains the thresholds and risks.

Log which provider answered each request. The router above returns provider and tried, so you can alert when fallback share rises.

Failover strategies compared (simulated outage and SDK source)
Strategy Calls to failing provider Outage p50 latency Fallback calls Main risk
SDK defaults + try/catch 3,554 3,707 ms 1,166 Up to 3 × 10-minute attempts per request on a hang
Rate breaker, 120 s max open 116 1,800 ms 2,200 Stays on fallback long after recovery
Rate breaker, 30 s max open 116 1,800 ms 1,625 Trips late when window holds old successes
Rate + 5-in-a-row, 30 s max open 7 1,800 ms 1,516 Can trip on a short burst of errors

The NexGismo verdict: an LLM fallback circuit breaker is worth its 70 lines the day you add a second provider. Turn off SDK retries, classify errors into transient, hard and caller, trip on a short streak as well as a rate, and cap the open timer near 30 seconds. I’d keep breaker state per process until the fleet is large enough that a consecutive-failure trigger alone stops being reliable.

  • The Anthropic and OpenAI Node SDKs both retry a failed request twice by default, so a failing provider gets three attempts per request.
  • Both SDKs default to a 10-minute timeout per attempt, so a hung provider can delay failover for up to 30 minutes per request.
  • OpenAI’s Node SDK ignores Retry-After values over 60 seconds, while Anthropic’s honors them, so retry timing differs between providers.
  • Spend-cap and quota 429 errors never clear on retry and should open the breaker for its maximum time.
  • Client errors such as 400 and 401 should be surfaced, not failed over, because they fail on every provider.
  • In a simulated 60-second outage, a breaker with a five-failure streak trigger sent 7 calls to the failing provider instead of 3,554.

Frequently Asked Questions

What is the difference between retry and circuit breaker?

Retry repeats an operation on the assumption that a transient fault will clear. A circuit breaker stops calling a dependency that is likely to fail and checks later whether it has recovered. Microsoft’s Azure guidance says the two can be combined, but retry logic should stop when the breaker signals that a fault is not transient.

Should I disable retries in the OpenAI or Anthropic SDK?

Disable them when your own router handles failover. Both Node SDKs retry twice by default, so a failing provider is called three times before your code sees the error. Set maxRetries to 0 on the client and let one layer, the router, decide whether to retry, wait or fail over.

Should a 429 error trigger a fallback to another LLM provider?

It depends on the error code. A throughput 429 is transient, so counting it toward the breaker and failing over is reasonable. A spend-cap or quota 429 keeps failing until someone changes billing or limits, so open the breaker for a long time and fail over immediately instead of retrying.

What is the half-open state in a circuit breaker?

Half-open is the state after the open timer expires. The breaker lets a limited number of trial requests through. If they succeed it closes and resets its counters; if any fails it reopens and restarts the timer. Azure’s guidance says this protects a recovering service from a sudden flood of requests.

Where should circuit breaker state be stored with multiple Node.js instances?

Start with per-process state; it needs no extra infrastructure. Marc Brooker’s simulations show that many small independent clients misjudge the true failure rate, so large serverless fleets may need shared state, for example in Redis, at the cost of an extra network dependency on every request.

A multi-provider setup only helps if failover is fast and selective. The design here is small: one breaker per provider, a three-way error classifier and a router that owns every retry decision. Copy breaker.mjs, run sim.mjs with your own latencies, and tune the streak and open-timer values before an outage tunes them for you. If you already run a gateway, check that it disables SDK retries and treats spend-cap 429s as hard failures.

Next, read our guide to retry budgets and jitter, which covers the single-provider side of the same problem. Have a failover pattern that worked better? Tell us in the comments.

Sources