Calling model providers directly from product handlers works for a prototype and fails in production. An upstream rate limit, a stalled regional endpoint, or an unbounded agent loop quickly cascades into dropped user requests and unexpected invoices. A dedicated AI gateway separates application logic from provider mechanics so one control plane owns authentication, routing, fallback policy, prompt cache affinity, stream safety, and spending caps.

That boundary mirrors the outer control plane described in our production AI agent architecture. Application services send a normalized request envelope with a tenant identifier, workload tier, deadline, and budget scope, while the gateway handles provider selection and recovery without leaking vendor-specific retry rules into business code.

Separating transient failures from deterministic errors

Retries only help when the underlying failure is transient. Treating every non-200 status code as retryable turns a deterministic bug into three wasted round trips and triple the latency.

Failure signal Classification Gateway action
HTTP 429 with rate limit headers Transient saturation Honor Retry-After or route to healthy secondary deployment
HTTP 502, 503, 529, pre-byte reset Transient upstream fault Exponential backoff with jitter, then fail over if budget remains
HTTP 408 or connect timeout Ambiguous pre-response Fail over safely only before the upstream stream emits bytes
HTTP 400 context overflow or schema Deterministic client error Never retry verbatim; return typed error for upstream compaction
HTTP 401, 403, or safety refusal Policy or credential block Stop immediately and surface structured cause without fallback

Always inspect provider headers before scheduling a retry. When an endpoint returns 429 alongside retry-after or x-ratelimit-reset-tokens, retrying on the same deployment after 50 milliseconds only burns your concurrency slots. Route the retry to a secondary region or fallback model family instead, and subtract every attempt's duration from the caller's remaining wall-clock deadline so retries never outlive the HTTP request.

Circuit breakers and hedged timeouts

Backoff alone fails when a regional provider endpoint degrades into slow 30-second timeouts rather than fast 503 errors. Without a circuit breaker, incoming traffic piles up on stalled sockets until your gateway exhausts file descriptors and worker memory.

Track circuit state per (provider, region, model) tuple rather than globally. A regional claude-sonnet outage should trip only that deployment while leaving alternative regions and smaller triage models open. Use a sliding time window that counts 5xx responses, 429 saturation spikes, and socket timeouts, while excluding caller-caused 400 errors so a malformed user payload never trips a healthy backend.

When the failure ratio crosses a threshold over a minimum sample size, transition the deployment to open for a cooldown period, then allow a single probe request in half-open state before restoring traffic. Pair this with hedged timeouts for non-streaming or pre-first-token calls: if the primary deployment has not produced headers or its first token within the historical p95 time-to-first-token (for example, 1800 ms), start a hedged request to a warm secondary deployment and cancel whichever finishes second via AbortController. Never fire hedged requests when the primary pool is already rejecting with 429, because hedging under quota exhaustion doubles token pressure and worsens saturation.

Why naive round-robin destroys prompt cache hit rates

Multi-account and multi-region gateways often default to round-robin or random load balancing. That choice quietly erases up to 80-90 percent of input token savings on agent workloads that share large system prompts, tool catalogs, and retrieval preambles.

Both Anthropic and OpenAI store KV cache prefixes locally to specific backend clusters, accounts, or cache partitions. As documented in the Anthropic prompt caching documentation, cache hits depend on matching exact leading token prefixes arriving at the same cache scope within the TTL window. Spraying sequential turns from the same tenant across five deployments turns five warm prefixes into zero hits and pays full input token pricing on every turn.

Routing strategy Cache hit rate Tail latency Overload handling Cost predictability
Naive round-robin Very low across nodes Moderate on idle pools Even spread, no hotspot Poor due to cache misses
Least-connections or latency Low during load shifts Good under even mix Adapts to slow backends Unstable prefix reuse
Consistent hash on prefix High for stable tenants Low TTFT on warm hits Requires spillover ring High and measurable
Sticky hash with spillover High under normal load Resilient under spikes Spills only on 429 or open breaker Optimal balance at scale

Hash a canonical affinity key built from (tenantId, modelTier, promptPrefixHash) onto an ordered ring of healthy deployments. The promptPrefixHash should cover your static system instructions and sorted tool schemas rather than volatile user messages. Under normal health, every turn for that tenant and workflow hits the same primary deployment and reuses its warm KV cache. Only when that primary deployment trips its circuit breaker or returns 429 does the router walk to the next healthy node on the ring.

Mid-stream SSE failure handling

Server-Sent Events create a sharp boundary between pre-stream and mid-stream failures. Before the gateway flushes the first content delta to the caller, the request is uncommitted: you can catch a 503 or connection timeout, fail over to a backup model, and stream the replacement response seamlessly.

Once a single token or tool-call chunk has been written to the downstream socket, transparent fallback is broken. Concatenating half a JSON argument block from Model A with a fresh completion from Model B corrupts syntax, mixes reasoning styles, and breaks token accounting. Do not attempt mid-stream cross-provider stitching.

Instead, handle post-first-byte drops explicitly:

  1. Track a firstTokenEmitted boolean and accumulate partialText plus any reported partialUsage inside the stream adapter.
  2. When the upstream stream errors or hits the hard wall-clock timeout after firstTokenEmitted is true, emit a single structured SSE error frame containing code, retryable, requestId, and receivedChars.
  3. Close the downstream stream cleanly and reconcile the partial token estimate in your budget store rather than leaving the full reservation locked.
  4. Let the upstream orchestrator decide whether to ask the user to retry or restart the turn cleanly using durable state.

Correlating these partial stream aborts with span events is essential for debugging tail errors; see our guide on observability for AI agents for trace attributes that keep stream diagnostics lightweight without logging sensitive payloads.

Atomic Redis token-budget accounting

Checking a tenant's spending limit with a standard GET followed by an asynchronous INCRBY after the response arrives fails under parallel tool calls. An agent that launches eight concurrent sub-calls when 1,000 tokens remain in a tenant's budget will pass all eight GET checks and overrun the cap eightfold.

Solve concurrency races with a two-phase reservation and reconciliation protocol executed inside atomic Redis Lua scripts:

  1. Reserve before dispatch: Estimate worst-case input tokens from byte length plus maxOutputTokens (or dollar microcents). A Lua script checks spent + reserved + estimate <= limit, increments reserved, stores a short-lived reservation key tied to requestId, and returns whether dispatch is permitted.
  2. Reconcile on completion: Whether the provider succeeds, fails mid-stream, or throws a 400, a finally block executes a second Lua script that deletes the reservation key, decrements reserved by the original estimate, and increments spent by the actual billed usage (or zero if no upstream work occurred).

Using requestId as an idempotency token inside the Lua script guarantees that worker retries or duplicate cleanup handlers never subtract a reservation twice or double-count actual tokens. Set a TTL on reservation keys slightly longer than your maximum gateway request timeout so a crashed Node.js process cannot permanently leak reserved quota.

Production TypeScript gateway core

The following self-contained TypeScript module demonstrates error classification, consistent-hash sticky routing with circuit breakers, pre-stream vs mid-stream SSE safety, and atomic Redis budget reservation.

type ErrorKind = "transient_rate_limit" | "transient_upstream" | "deterministic_client";

interface ClassifiedError {
  kind: ErrorKind;
  status: number;
  retryAfterMs?: number;
  message: string;
}

interface Deployment {
  id: string;
  provider: "anthropic" | "openai";
  region: string;
  model: string;
  invokeStream: (
    prompt: string,
    signal: AbortSignal,
  ) => AsyncIterable<{ delta?: string; inputTokens?: number; outputTokens?: number }>;
}

interface BudgetStore {
  reserve(tenantKey: string, requestId: string, estimate: number, limit: number): Promise<boolean>;
  reconcile(tenantKey: string, requestId: string, actual: number): Promise<void>;
}

export function classifyProviderError(status: number, headers: Headers, message: string): ClassifiedError {
  const retryHeader = headers.get("retry-after");
  const retryAfterMs = retryHeader ? Math.max(0, Number(retryHeader) * 1000) : undefined;
  if (status === 429) {
    return { kind: "transient_rate_limit", status, retryAfterMs, message };
  }
  if (status === 408 || status === 502 || status === 503 || status === 529) {
    return { kind: "transient_upstream", status, retryAfterMs, message };
  }
  return { kind: "deterministic_client", status, message };
}

export class CircuitBreaker {
  private failures = 0;
  private openUntil = 0;

  constructor(
    private readonly failureThreshold = 5,
    private readonly cooldownMs = 15_000,
  ) {}

  isAvailable(now = Date.now()): boolean {
    return now >= this.openUntil;
  }

  recordSuccess(): void {
    this.failures = 0;
    this.openUntil = 0;
  }

  recordFailure(kind: ErrorKind, now = Date.now()): void {
    if (kind === "deterministic_client") return;
    this.failures += 1;
    if (this.failures >= this.failureThreshold) {
      this.openUntil = now + this.cooldownMs;
    }
  }
}

function fnv1a(input: string): number {
  let hash = 0x811c9dc5;
  for (let i = 0; i < input.length; i += 1) {
    hash ^= input.charCodeAt(i);
    hash = Math.imul(hash, 0x01000193);
  }
  return hash >>> 0;
}

export class StickyRouter {
  private readonly breakers = new Map<string, CircuitBreaker>();

  constructor(private readonly deployments: readonly Deployment[]) {
    for (const deployment of deployments) {
      this.breakers.set(deployment.id, new CircuitBreaker());
    }
  }

  selectCandidates(affinityKey: string): Deployment[] {
    const scored = this.deployments
      .filter((d) => this.breakers.get(d.id)?.isAvailable())
      .map((d) => ({
        deployment: d,
        score: fnv1a(`${affinityKey}:${d.id}`),
      }))
      .sort((a, b) => b.score - a.score);
    return scored.map((entry) => entry.deployment);
  }

  report(deploymentId: string, ok: boolean, kind?: ErrorKind): void {
    const breaker = this.breakers.get(deploymentId);
    if (!breaker) return;
    if (ok) breaker.recordSuccess();
    else if (kind) breaker.recordFailure(kind);
  }
}

export const RESERVE_LUA = `
local budgetKey = KEYS[1]
local resKey = KEYS[2]
local reqId = ARGV[1]
local estimate = tonumber(ARGV[2])
local limit = tonumber(ARGV[3])
local ttl = tonumber(ARGV[4])

if redis.call("HEXISTS", resKey, reqId) == 1 then
  return 1
end

local spent = tonumber(redis.call("HGET", budgetKey, "spent") or "0")
local reserved = tonumber(redis.call("HGET", budgetKey, "reserved") or "0")
if spent + reserved + estimate > limit then
  return 0
end

redis.call("HINCRBY", budgetKey, "reserved", estimate)
redis.call("HSET", resKey, reqId, estimate)
redis.call("EXPIRE", resKey, ttl)
return 1
`;

export const RECONCILE_LUA = `
local budgetKey = KEYS[1]
local resKey = KEYS[2]
local reqId = ARGV[1]
local actual = tonumber(ARGV[2])

local estimate = redis.call("HGET", resKey, reqId)
if not estimate then
  return 0
end

redis.call("HDEL", resKey, reqId)
redis.call("HINCRBY", budgetKey, "reserved", -tonumber(estimate))
redis.call("HINCRBY", budgetKey, "spent", actual)
return 1
`;

export async function* streamWithSafeFallback(params: {
  router: StickyRouter;
  budget: BudgetStore;
  tenantKey: string;
  requestId: string;
  affinityKey: string;
  prompt: string;
  estimatedTokens: number;
  limitTokens: number;
  timeoutMs: number;
}): AsyncGenerator<string> {
  const permitted = await params.budget.reserve(
    params.tenantKey,
    params.requestId,
    params.estimatedTokens,
    params.limitTokens,
  );
  if (!permitted) {
    yield `event: error\ndata: ${JSON.stringify({ code: "budget_exceeded", retryable: false })}\n\n`;
    return;
  }

  let actualTokens = 0;
  let firstTokenEmitted = false;
  const candidates = params.router.selectCandidates(params.affinityKey);

  try {
    for (const candidate of candidates) {
      const controller = new AbortController();
      const timer = setTimeout(() => controller.abort(), params.timeoutMs);
      try {
        for await (const chunk of candidate.invokeStream(params.prompt, controller.signal)) {
          if (chunk.inputTokens) actualTokens += chunk.inputTokens;
          if (chunk.outputTokens) actualTokens += chunk.outputTokens;
          if (chunk.delta) {
            firstTokenEmitted = true;
            yield `event: delta\ndata: ${JSON.stringify({ text: chunk.delta })}\n\n`;
          }
        }
        params.router.report(candidate.id, true);
        yield `event: done\ndata: ${JSON.stringify({ requestId: params.requestId, tokens: actualTokens })}\n\n`;
        return;
      } catch (error: unknown) {
        const status = typeof (error as { status?: unknown })?.status === "number"
          ? (error as { status: number }).status
          : 503;
        const headers = (error as { headers?: Headers })?.headers ?? new Headers();
        const classified = classifyProviderError(status, headers, String(error));
        params.router.report(candidate.id, false, classified.kind);

        if (firstTokenEmitted) {
          yield `event: error\ndata: ${JSON.stringify({ code: "mid_stream_abort", retryable: false, requestId: params.requestId })}\n\n`;
          return;
        }
        if (classified.kind === "deterministic_client") {
          yield `event: error\ndata: ${JSON.stringify({ code: "invalid_request", retryable: false, status })}\n\n`;
          return;
        }
      } finally {
        clearTimeout(timer);
      }
    }
    yield `event: error\ndata: ${JSON.stringify({ code: "all_providers_exhausted", retryable: true })}\n\n`;
  } finally {
    await params.budget.reconcile(params.tenantKey, params.requestId, actualTokens);
  }
}

When connecting this gateway layer to tool-using clients, pair the streamWithSafeFallback output parser with typed client adapters such as those covered in AI SDK 6 and TypeScript tools. Keep the gateway thin, deterministic, and easy to bypass in unit tests so routing policies can evolve without rewriting downstream agents.

Operational checklist

Before putting a gateway in front of production traffic, verify five invariants in staging:

  1. Every 400 and 401 error from an upstream provider short-circuits immediately without hitting backup providers.
  2. Sequential turns for the same tenant and system prompt hit the same primary deployment and record non-zero cached input tokens.
  3. Killing an upstream TCP connection after the second SSE chunk emits a typed error event and releases the unused Redis reservation.
  4. Ten concurrent requests against a near-empty tenant budget allow only the subset covered by remaining tokens and reject the rest before upstream dispatch.
  5. Every upstream attempt writes a span with deployment ID, cache status, TTFT, and token delta to your tracing backend.