Backend & API Engineering8 min readUpdated: 2025-01-25

Handling Rate Limits, Provider Timeouts, and Graceful Fallback in AI Gateways

Patterns for building production-grade LLM routing with circuit breakers, exponential backoff, and grounded fallback responses.

ResilienceLLM RoutingCircuit BreakerError HandlingTypeScript

Core Takeaway

Upstream LLM APIs are notorious for unpredictable latency distributions: a request that usually takes 800ms may occasionally stall for 12 seconds or return HTTP 429 quota errors. Without defensive routing, these stalls cause cascading thread pool exhaustion in client apps. This note details resilient routing strategies.

Problem Statement & Context

When building interactive user applications (such as a travel planner or portfolio assistant), users will not wait 15 seconds for a response. Furthermore, provider-side outages or rate limit spikes should never crash your application. Services must degrade gracefully to secondary models, semantic caches, or grounded fallback engines.

Architectural Concepts & Implementation

1. Hard Timeouts with AbortController

Never issue an HTTP request to an upstream LLM without an explicit, non-negotiable timeout. Use AbortController to cancel hanging connections after a sensible threshold (e.g., 7.5 seconds for interactive chat).

Timeout and Multi-Provider Fallback Dispatcher
export async function callLLMWithFallback(
  prompt: string,
  timeoutMs = 7500
): Promise<string> {
  const providers = [
    { name: 'primary-gemini', call: () => callGemini(prompt) },
    { name: 'secondary-openai', call: () => callOpenAI(prompt) },
  ];

  for (const provider of providers) {
    const controller = new AbortController();
    const timer = setTimeout(() => controller.abort(), timeoutMs);

    try {
      const response = await provider.call();
      clearTimeout(timer);
      return response;
    } catch (err: any) {
      clearTimeout(timer);
      console.warn('Provider ' + provider.name + ' failed: ' + err.message + '. Trying next provider...');
      // Continue to next provider in fallback array
    }
  }

  // Graceful degradation when all upstream models are unavailable
  return getGroundedFallbackResponse(prompt);
}

2. Circuit Breakers to Prevent Downstream Thundering Herds

If an upstream provider returns 5 consecutive HTTP 500 or 429 responses within 30 seconds, trip a circuit breaker. For the next 60 seconds, fail fast immediately and serve cached or grounded fallback responses rather than hammering the failing upstream API.

3. Grounded Local Fallback Engine

For domain-specific assistants, maintain an offline, structured knowledge base. If all remote LLMs fail, query this local knowledge base using keyword or local vector matching to return a factual, pre-verified response rather than an empty error screen.

Common Pitfalls & Trade-offs

  • !Pitfall: Falling back to a different model family without prompt adjustment. Prompts optimized for Gemini may trigger unexpected behavior on Claude or GPT models if system prompt nuances differ.
  • !Trade-off: Cost of secondary provider standby. Maintaining accounts and configurations across two LLM vendors requires extra setup, but provides 99.9% uptime guarantees.

Production Verification Checklist

  • Set strict timeouts (5s to 8s) on all user-facing synchronous LLM invocations.
  • Implement circuit breakers to protect against provider cascading failures.
  • Ensure secondary model fallbacks adhere to matching output schema contracts.
  • Always provide a user-friendly, grounded fallback message on total provider outage.
Back to all engineering notes