@HamzaM to AI & LLMEnglish • 6 days ago

How do you design a unified LLM fallback router that switches from OpenAI to Anthropic or Gemini on 503 errors?

message-square
0
1
How do you design a unified LLM fallback router that switches from OpenAI to Anthropic or Gemini on 503 errors?
@HamzaM to AI & LLMEnglish • 6 days ago

How a Unified LLM Fallback Router Works

When an LLM provider runs short on capacity, it returns a transient overload error—typically HTTP 503 (server_is_overloaded on OpenAI, UNAVAILABLE on Gemini) or HTTP 529 (overloaded_error on Anthropic). Instead of letting your app fail or stall waiting on a single overloaded provider, a unified router wraps OpenAI, Anthropic, and Gemini behind one common interface and automatically fails over to the next healthy provider.

  • Normalize requests and responses: Define one internal input/output shape (system prompt, message array, max tokens, and returned text) and translate it inside thin provider adapters.
  • Distinguish failover errors from caller bugs: Only switch providers on transient capacity/server failures (503, 529, 502, 504, or network timeouts)—do not fail over on 400 bad request errors caused by your own invalid payload.
  • Disable hidden SDK retry loops: Set maxRetries: 0 on individual SDK clients when your router owns the fallback loop so a slow primary provider does not burn 30+ seconds retrying before switching.
  • Track provider health (circuit breaker): If OpenAI returns 503 several times in a row, temporarily mark it unhealthy (for example, 30–60 seconds) so new requests go straight to Anthropic or Gemini without paying the timeout penalty on every call.

Step-by-Step Router Architecture

  1. Standardize the request contract: Accept { system, messages, maxTokens } in your router function.
  2. Build thin provider adapters: Convert the standard messages into each SDK’s format (openai, @anthropic-ai/sdk, @google/genai) and extract plain text + usage metrics uniformly.
  3. Classify retryable/failover errors: Check HTTP status codes (503, 529, 500, 502, 504) and timeout/connection errors.
  4. Loop through the ordered provider chain: Try the primary provider with a strict per-request timeout; on a failover-eligible error, record the failure in a lightweight circuit breaker and immediately invoke the next provider.

Node.js Example: Unified Router (OpenAI -> Anthropic -> Gemini)

import OpenAI from "openai";
import Anthropic from "@anthropic-ai/sdk";
import { GoogleGenAI } from "@google/genai";

// Disable built-in SDK retries so the router fails over immediately on 503/529
const openai = new OpenAI({ maxRetries: 0, timeout: 15000 });
const anthropic = new Anthropic({ maxRetries: 0, timeout: 15000 });
const gemini = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });

// Simple in-memory circuit breaker to skip degraded providers briefly
const circuitState = new Map();
const COOLDOWN_MS = 30_000;

function isProviderHealthy(name) {
  const openUntil = circuitState.get(name);
  if (!openUntil) return true;
  if (Date.now() > openUntil) {
    circuitState.delete(name);
    return true;
  }
  return false;
}

function markProviderUnhealthy(name) {
  circuitState.set(name, Date.now() + COOLDOWN_MS);
}

function shouldFailover(err) {
  const status = err?.status ?? err?.statusCode ?? err?.response?.status;
  // 503 (OpenAI/Gemini overload), 529 (Anthropic overload), 502/504 gateway errors
  if ([502, 503, 504, 529].includes(status)) return true;

  const code = String(err?.code || err?.name || "");
  return ["ETIMEDOUT", "ECONNRESET", "APIConnectionTimeoutError", "AbortError"].includes(code);
}

// Provider Adapters
async function callOpenAI({ system, messages, maxTokens }) {
  const formatted = system
    ? [{ role: "system", content: system }, ...messages]
    : messages;

  const res = await openai.chat.completions.create({
    model: "gpt-4o-mini",
    max_tokens: maxTokens,
    messages: formatted,
  });

  return {
    provider: "openai",
    text: res.choices[0]?.message?.content ?? "",
  };
}

async function callAnthropic({ system, messages, maxTokens }) {
  const res = await anthropic.messages.create({
    model: "claude-sonnet-4-6",
    max_tokens: maxTokens,
    ...(system ? { system } : {}),
    messages: messages.map((m) => ({
      role: m.role === "assistant" ? "assistant" : "user",
      content: m.content,
    })),
  });

  const text = res.content
    .filter((block) => block.type === "text")
    .map((block) => block.text)
    .join("");

  return { provider: "anthropic", text };
}

async function callGemini({ system, messages, maxTokens }) {
  const contents = messages.map((m) => ({
    role: m.role === "assistant" ? "model" : "user",
    parts: [{ text: m.content }],
  }));

  const res = await gemini.models.generateContent({
    model: "gemini-3-flash-preview",
    contents,
    config: {
      maxOutputTokens: maxTokens,
      ...(system ? { systemInstruction: system } : {}),
    },
  });

  return { provider: "gemini", text: res.text ?? "" };
}

// Unified Router
const PROVIDERS = [
  { name: "openai", run: callOpenAI },
  { name: "anthropic", run: callAnthropic },
  { name: "gemini", run: callGemini },
];

export async function generateWithFallback({
  system = "",
  messages,
  maxTokens = 1024,
}) {
  const errors = [];

  for (const provider of PROVIDERS) {
    if (!isProviderHealthy(provider.name)) {
      continue;
    }

    try {
      return await provider.run({ system, messages, maxTokens });
    } catch (err) {
      errors.push({ provider: provider.name, status: err?.status, message: err?.message });

      if (!shouldFailover(err)) {
        // Non-transient error (e.g., 400 invalid input or 401 bad key): surface immediately
        throw err;
      }

      markProviderUnhealthy(provider.name);
    }
  }

  // Last-resort pass if every provider was in cooldown
  throw new AggregateError(
    errors.map((e) => new Error(`\${e.provider} (${e.status ?? "net"}): ${e.message}`)),
    "All LLM providers failed or are temporarily unavailable"
  );
}

// Example usage
const reply = await generateWithFallback({
  system: "Be concise.",
  messages: [{ role: "user", content: "Explain circuit breakers in one sentence." }],
});
console.log(reply);

Helpful Tips for Production Routers

  • Keep prompts provider-neutral: Avoid provider-specific features (such as OpenAI-only flags) in shared fallback routes, or translate schemas/tools cleanly inside each adapter.
  • Include a half-open probe or fallback pass: If all providers enter cooldown during a regional outage, allow a probe call through so traffic recovers automatically as soon as the first provider comes back online.
  • Log which provider served each request: Recording provider, latency, and failover reasons makes it easy to spot upstream outages and track spend across vendors.