LLM gateways and routing, LiteLLM, OpenRouter and fallbacks
Once an application uses more than one model, or more than one provider for the same model, calling vendor SDKs directly from business code turns into a tangle of keys, retry loops and if-statements. An LLM gateway is a thin layer that every model call goes through. It gives you one API shape, central keys and budgets, load balancing across deployments, and automatic fallbacks when a provider is down or rate limiting you. This doc covers the patterns and two popular ways to get them: the self-hosted LiteLLM proxy and the hosted OpenRouter service.
Why it matters
Provider outages, regional capacity limits and 429 responses are routine, not exceptional. Without a gateway, every service reinvents retry and fallback logic, usually inconsistently. A gateway also becomes the natural place for cross-cutting concerns:
- Unified API. Most gateways speak the OpenAI chat completions shape (many also accept the Anthropic Messages shape) and translate to each provider.
- Reliability. Retries, cooldowns for failing deployments, fallbacks to other models.
- Cost control. Per-team virtual keys, budgets, and spend logs.
- Observability. One place to log latency, tokens, errors and cache hits per model.
- Policy. Guardrails, PII redaction and allowed-model lists applied consistently.
How it works
The core concepts are the same across gateways.
- Model group (alias). A logical name your code uses, such as
chat-default, mapped to one or more concrete deployments (for example the same model on two providers or two regions). - Routing strategy. How the gateway picks a deployment within a group: simple shuffle, least busy, lowest latency, cost-based, or usage-based against rate limits.
- Retries. Re-send to the same group on transient failures, with backoff for rate limit errors.
- Cooldown. If a deployment fails too often within a window, take it out of rotation for a while.
- Fallbacks. After retries are exhausted, try a different model group. Gateways often support special-purpose fallbacks too, for example switching to a larger-context model when a request exceeds the context window.
Rendering diagram…
LiteLLM is an open-source Python SDK and proxy server. Its Router lets you list deployments under a shared model_name, set num_retries, configure fallbacks and context_window_fallbacks, and tune cooldowns with allowed_fails and cooldown_time. Retries happen first on the same group; fallbacks only kick in after retries fail. For multiple proxy instances, it can share state (such as usage and cooldowns) through Redis.
OpenRouter is a hosted gateway with one API key for many models and providers. It has two layers of failover. Provider routing (on by default) picks among providers hosting the same model and can be steered with provider preferences such as an explicit order or disallowing fallbacks. Model fallbacks are opt-in: you pass an ordered models array and OpenRouter tries the next model if the first returns an error, including rate limits, downtime and context length errors. You are billed for the model that actually served the request, which the response reports.
Reference architecture
Rendering diagram…
I run the gateway as its own stateless service (two or more replicas), with Redis for shared state and a database for keys and spend. Self-hosted engines plug in as just another OpenAI-compatible deployment, which makes "burst to a hosted provider when our GPUs are full" a config change.
Code
A LiteLLM proxy config.yaml with two deployments behind one alias, retries, and a fallback chain:
model_list:
- model_name: chat-default
litellm_params:
model: openai/gpt-4o-mini
api_key: os.environ/OPENAI_API_KEY
- model_name: chat-default
litellm_params:
model: hosted_vllm/Qwen/Qwen2.5-7B-Instruct
api_base: http://vllm.internal:8000/v1
- model_name: chat-large
litellm_params:
model: anthropic/claude-sonnet-4-5
api_key: os.environ/ANTHROPIC_API_KEY
router_settings:
routing_strategy: simple-shuffle
num_retries: 2
allowed_fails: 3
cooldown_time: 60
redis_host: os.environ/REDIS_HOST
litellm_settings:
fallbacks: [{"chat-default": ["chat-large"]}]
request_timeout: 30
Run it with litellm --config config.yaml, and clients call it like any OpenAI endpoint using model="chat-default". Model identifiers above are illustrative; use the exact ids from your providers' current model lists.
The OpenRouter equivalent of a fallback chain lives in the request body:
from openai import OpenAI
client = OpenAI(base_url="https://openrouter.ai/api/v1", api_key="<OPENROUTER_API_KEY>")
resp = client.chat.completions.create(
model="openai/gpt-4o-mini",
messages=[{"role": "user", "content": "Ping"}],
extra_body={"models": ["anthropic/claude-sonnet-4.5", "google/gemini-2.5-flash"]},
)
print(resp.model, resp.choices[0].message.content)
Trade-offs and pitfalls
- Fallbacks change behaviour. A fallback model has a different tokenizer, context window, tool-calling quirks and output style. Evaluate every model in a fallback chain on your prompts, and log which model actually answered.
- Retries multiply load. During a provider brownout, aggressive retries from many clients make it worse. Use backoff with jitter, respect
Retry-After, and cap total attempts (see rate limits and retries). - Streaming complicates failover. Once tokens have been streamed to a user you cannot transparently switch models mid-answer. Fail over before the first token, or surface a retry to the user.
- Another hop, another dependency. A gateway adds a little latency and a new single point of failure. Run it redundantly and keep it stateless.
- Hosted gateways see your data. A hosted gateway sits in the data path. Check its data retention policy and whether your compliance rules allow it.
- Provider prompt caching is per provider. Spreading identical prompts across providers can lower cache hit rates. Sticky routing per conversation helps (see caching).
Checklist
- All model calls go through one gateway with logical model names.
- Each alias has at least two deployments or a tested fallback group.
- Retries use backoff with jitter and a total attempt cap.
- Failing deployments are cooled down automatically.
- Logs record the model that actually served each request, plus tokens and latency.
- Fallback models have been evaluated on my real prompts and tool schemas.
- The gateway runs with redundancy and shared state.