Build an LLM fallback chain in 10 minutes

By LLMTest Lab · Apr 21, 2026 · 5 min read infrafallbackreliabilityopenrouter
On this page

On this page

  1. The four failure modes you're probably not handling
  2. LiteLLM: one config, automatic retries
  3. OpenRouter: one extra body parameter
  4. Plain SDKs: availability fallback plus a quality gate
  5. Three things none of them handle by default
  6. Which approach fits your setup

Your AI feature went down last night. Not because your code was wrong. The model API returned a 503, your retry logic hit the rate limit on the second attempt, and by the time you woke up, half your users had seen an error modal. A fallback chain would have caught all of that without you doing anything.

Here's how to build one in three flavors: LiteLLM for Python shops, OpenRouter for any stack, and plain provider SDKs for when you need a quality gate on top of availability.

The four failure modes you're probably not handling

Most retry logic only catches one of these.

Hard errors (4xx/5xx HTTP status): The API rejects the call outright. Rate limits (429), server errors (500/503), timeouts. Easy to detect, straightforward to retry.

Soft failures (200 OK, garbage output): The API returns HTTP 200 but the response is malformed JSON, an empty string, a refusal, or a hallucinated structure. You try to parse it, crash, and only then find out something went wrong.

Quality degradation: The model answers, but quality has dropped. Maybe the provider is running on overloaded hardware, maybe there was a silent rollback on their end. You won't catch this without running quality checks on each response.

Model retirement: The model ID you're calling got deprecated. Usually there's a grace period with a warning header, but not always.

A fallback chain handles at least the first two. Adding a quality check to the chain covers the third, and a model-ID check on startup covers the fourth.

LiteLLM: one config, automatic retries

LiteLLM's Router is the fastest path to fallback for Python apps:

import asyncio
from litellm import Router

router = Router(
    model_list=[
        {
            "model_name": "primary",
            "litellm_params": {
                "model": "openai/gpt-5",
                "api_key": "sk-...",
            },
        },
        {
            "model_name": "primary",
            "litellm_params": {
                "model": "anthropic/claude-opus-4-7",
                "api_key": "sk-ant-...",
            },
        },
        {
            "model_name": "primary",
            "litellm_params": {
                "model": "google/gemini-2.5-pro",
                "api_key": "...",
            },
        },
    ],
    fallbacks=[{"primary": ["primary", "primary"]}],
    retry_after=1,
    num_retries=2,
)


async def call_model(messages):
    return await router.acompletion(model="primary", messages=messages)


asyncio.run(call_model([{"role": "user", "content": "Hello"}]))

This handles rate limits and 5xx errors automatically. One gap: soft failures pass through. If GPT-5 returns malformed JSON, LiteLLM treats it as a successful call and hands you the broken output. Add your own validation wrapper if you're doing structured extraction.

Also worth checking before you add fallback candidates: models from different providers have different usable context window sizes. If your prompts are long, a fallback with a smaller context budget might silently truncate what the primary handled fine.

LiteLLM's Router also supports traffic splitting by weight, latency-aware selection, and per-provider spend caps. For those patterns with the complete YAML, see LiteLLM routing in 2026.

OpenRouter: one extra body parameter

If you're already calling OpenRouter as a gateway, fallback is one parameter away:

// openrouter-fallback.js
async function callWithFallback(messages) {
  const res = await fetch("https://openrouter.ai/api/v1/chat/completions", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${process.env.OPENROUTER_API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      model: "openai/gpt-5",
      messages,
      route: "fallback",
      models: [
        "openai/gpt-5",
        "anthropic/claude-opus-4-7",
        "google/gemini-2.5-pro",
      ],
    }),
  });
  return res.json();
}

The route: "fallback" field tells OpenRouter to try each model in models order on a hard failure. Zero code overhead if you're already using OpenRouter as your gateway. The limits are the same as LiteLLM: soft failures still land in your app as successful 200s.

For a step-by-step Node.js walkthrough covering the models array, response.model billing attribution, and the streaming edge cases that trip you up on week two, see our OpenRouter fallback tutorial in Node.js. To skip the gateway entirely and call two providers directly from a Next.js App Router handler, the direct two-provider fallback in Next.js 2026 covers the 25-line implementation, error detection, and the latency cost of switching mid-request.

Plain SDKs: availability fallback plus a quality gate

The two approaches above route around hard availability failures. To also handle the "200 OK with garbage" case, add a quality check in your own code and treat a failed check like an error. With the provider SDKs directly, that is a short loop:

// fallback-with-gate.js
import OpenAI from "openai";
import Anthropic from "@anthropic-ai/sdk";

const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
const anthropic = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });

const providers = [
  async (messages) => {
    const res = await openai.chat.completions.create({ model: "gpt-5", messages });
    return res.choices[0].message.content;
  },
  async (messages) => {
    const res = await anthropic.messages.create({
      model: "claude-opus-4-7",
      max_tokens: 1024,
      messages,
    });
    return res.content[0].text;
  },
];

// Replace with a check that fits your task: parse JSON, test length, detect refusals.
function passesGate(text) {
  if (!text || text.trim().length === 0) return false;
  try {
    JSON.parse(text);
    return true;
  } catch {
    return false;
  }
}

async function callWithGate(messages) {
  for (const call of providers) {
    try {
      const text = await call(messages);
      if (passesGate(text)) return text;
    } catch {
      // hard failure: fall through to the next provider
    }
  }
  throw new Error("All providers failed or returned output that failed the gate");
}

The gate can be as simple as a JSON parse and a length check, or a second model scoring the answer against a rubric. A judge pass costs an extra call per request, so reserve it for output where a bad answer does real damage.

Three things none of them handle by default

Regardless of which approach you choose, these still need handling on your side:

Billing soft-caps. Some providers silently return shorter or lower-quality responses when you approach a spending limit. There's no HTTP signal for this. You catch it by monitoring output quality or length over time. It's the same category of hidden cost as the three LLM costs nobody talks about: the ones that don't surface in dashboards until they become incidents.

Refusals inside a 200. If a model refuses a request ("I can't help with that"), the HTTP status is still 200. None of the three approaches above treat a refusal as a fallback-triggerable failure unless you add a refusal-detection wrapper to your parsing layer.

Cascading retries. If all models in your chain are failing simultaneously (provider-wide incident, or they all share the same upstream), a naive retry loop will exhaust every option before giving up. Cap total attempts across the entire chain, not per-model. Handling rate limits at the call level with circuit breakers and token budget pre-checks makes cascading failures less likely to reach the fallback layer at all.

Which approach fits your setup

LiteLLM: Python stack, just need availability fallback. The Router handles it with minimal config and no additional service to run.

OpenRouter: Any language, already using OpenRouter, need failover with no extra infra. One body parameter away.

Plain SDKs with a quality gate: Customer-facing output, structured extraction, or anything where a degraded model response causes real downstream damage. The gate catches what the other two miss.

For what happens when a provider keeps failing, see circuit breakers for LLM calls in production.

Related articles

How to add LLM circuit breakers in Node.js in 2026
Per-provider LLM circuit breakers stop cascade failures early. Closed, open, half-open state machine with auto-reset: working Node.js code.
How to add LLM fallback in Next.js in 2026: two providers, 25 lines
Wire Anthropic and OpenAI into one Next.js API route: primary call, automatic provider switch on 429 or 5xx, and the real latency cost of switching mid-request.