Multi-Provider AI Fallback Router: High Availability on Free Tiers

Build a lightweight TypeScript/JS router with cooldown circuit breakers, capability tiers, and local fallbacks so a single 429 never breaks your app.

2026-11-16 · FreeTokenBox Editorial · Review method · Token Calculator

No free AI API comes with a production SLA. Upstream congestion, exhausted daily allowances, and sudden model deprecations happen routinely. Rather than scattering ad-hoc try/catch blocks across your codebase, centralize calls behind a compact Multi-Provider Fallback Router.

Three Architecture Rules

  1. Group by Equivalent Capability: Put models with matching JSON/tool-calling reliability in the same tier (for example, a fast-json tier combining Groq, Gemini Flash, and local Qwen 7B). Never fall back from a strict structured-output model to one that ignores JSON constraints.
  2. Use Cooldown Circuit Breakers: When a provider reports a 429 or repeated 5xx timeouts, mark it in cooldown (for 60 seconds or until its reset window) so subsequent users do not suffer stacked timeouts.
  3. Hard Budget Guardrails: Never silently place an uncapped paid provider at the end of a free fallback chain. Gate any paid fallback behind a strict daily token counter.

Minimal Router Implementation (Node.js / Cloudflare Workers)

const cooldownUntil = new Map()

export async function routeChat(providers, payload) {
  const now = Date.now()
  const errors = []

  for (const p of providers) {
    if ((cooldownUntil.get(p.id) || 0) > now) continue
    try {
      const res = await fetch(p.endpoint, {
        method: 'POST',
        signal: AbortSignal.timeout(p.timeoutMs || 15000),
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${p.apiKey}`,
        },
        body: JSON.stringify({ ...payload, model: p.model }),
      })
      if (res.ok) return { provider: p.id, data: await res.json() }
      const coolMs = res.status === 429
        ? Math.min((Number(res.headers.get('retry-after')) || 60) * 1000, 3600_000)
        : 60_000
      cooldownUntil.set(p.id, now + coolMs)
      errors.push(`${p.id}:HTTP_${res.status}`)
    } catch (err) {
      cooldownUntil.set(p.id, now + 45_000)
      errors.push(`${p.id}:${err.name || 'ERR'}`)
    }
  }
  throw new Error('All providers unavailable: ' + errors.join(', '))
}

Task-Based Routing Multiplies Effective Free Capacity

Route short classification calls to high-RPM or edge tiers (Groq, Cloudflare Workers AI), long-context summaries to wide-window tiers (Gemini Flash), and sensitive internal batch jobs to a local Ollama instance. Log the winning provider ID, latency, and fallback reason on every call so you can spot quota bottlenecks early.