Education › Inference › Stage 7: Production inference systems

AI gateways

Routing, rate limits, fallbacks, caching and traffic management in front of your models.

Advanced ~35 min read Module 15 of 15

Applications should not talk to model servers directly. An AI gateway sits in front of every model, self-hosted or hosted, and gives you one API, one place for keys and quotas, routing and fallbacks when a backend fails, caching, cost tracking and policy. This lesson explains what a gateway does that an ordinary API gateway does not, the routing and reliability patterns it enables, how it relates to the inference-aware routing inside a cluster, and how to configure a working example with open-source tools.

After this module you can
  • Explain what an AI gateway adds over a generic API gateway
  • Design routing, fallbacks and retries across self-hosted and hosted models
  • Apply per-tenant rate limits and token budgets
  • Decide when response caching is safe
  • Place the gateway relative to cluster-level inference routing

What an AI gateway does

A generic API gateway routes HTTP and counts requests. LLM traffic needs more: requests vary a thousandfold in cost depending on tokens, responses stream for seconds, failures include rate limits and context-length errors, and the same logical model may be served by several backends. An AI gateway understands those things.

  • One API (usually OpenAI-compatible) in front of many models and providers, with model names as aliases you control.
  • Authentication and virtual keys per team or customer, so provider keys never reach applications.
  • Rate limits and budgets in requests and in tokens, per key, team or tenant.
  • Routing: by model alias, weights for canaries, cost, latency or current load.
  • Reliability: retries with backoff, timeouts, and fallbacks to another deployment or model.
  • Caching of identical requests, and sometimes semantic caching.
  • Observability and cost: per-request token counts, latency, errors and spend, exported as metrics and traces.
  • Policy and guardrails: PII redaction, content filters, allowed-model lists.

Routing and fallbacks

Treat the model name an application sends as a contract, not an address. chat can map to two self-hosted vLLM deployments with load-based routing, fall back to a hosted provider when both are saturated or failing, and shift 5% of traffic to a new model version as a canary. Applications never change.

one APIleast busyon failuremetricsApplicationsmodel: chatAI gatewaykeys, budgets, routingvLLM Aself-hostedvLLM Bself-hostedchat-backuphosted fallbackObservabilitytokens, cost, errors
Applications call one alias on the gateway; it routes across self-hosted replicas and falls back to a substitute model only when they fail or saturate.
LiteLLM proxy: two self-hosted vLLM backends for chat, with a fallback group
yaml
model_list:
  - model_name: chat
    litellm_params:
      model: hosted_vllm/YOUR_ORG/YOUR_MODEL
      api_base: http://vllm-a.ai.svc:8000/v1
      rpm: 600
  - model_name: chat
    litellm_params:
      model: hosted_vllm/YOUR_ORG/YOUR_MODEL
      api_base: http://vllm-b.ai.svc:8000/v1
      rpm: 600
  - model_name: chat-backup
    litellm_params:
      model: openai/BACKUP_MODEL_NAME
      api_key: os.environ/BACKUP_PROVIDER_KEY

router_settings:
  routing_strategy: least-busy
  num_retries: 2
  fallbacks: [{"chat": ["chat-backup"]}]

general_settings:
  master_key: os.environ/LITELLM_MASTER_KEY
  • Retry only idempotent failures (timeouts, 5xx, 429 from a backend) and with backoff; never retry a request that already streamed tokens to the client.
  • Fallback models must be acceptable substitutes: check prompt format, context length, tool-calling support and quality before wiring them in.
  • Context-length fallbacks route requests that are too long for one model to a deployment with a larger window.
  • Record which backend actually served each request, or debugging quality issues becomes guesswork.

Limits, budgets and caching

Request-per-minute limits are not enough when one request can cost a thousand times another. Enforce tokens per minute and spend budgets per tenant, and return HTTP 429 with a clear message when they are exceeded. This protects shared self-hosted capacity from one noisy customer and protects your bill from runaway agents stuck in loops.

Exact caching returns a stored response for an identical request (same model, messages and parameters). It is safe for deterministic settings and repeated queries, such as classification or FAQ answers, and pointless for creative, personalised or temperature-sampled outputs. Semantic caching returns a stored answer for a similar question; it can save a lot, but it can also serve a wrong answer to a subtly different question, so use it only where that risk is acceptable and measured. Never share cache entries across tenants.

Watch out

A gateway sees every prompt and response, which makes it both your best control point and a sensitive system. Lock down who can read its logs, redact personal data before storage, and keep provider keys in a secret store.

Where the gateway sits

Think in two layers. The AI gateway is the front door: it decides which logical model and which backend group serve a request, enforces tenant policy, and can leave your infrastructure entirely for a hosted provider. Inside your cluster, inference-aware routing decides which replica of a self-hosted model handles it, using cache locality and queue depth: the Gateway API Inference Extension's endpoint picker, Dynamo's router or the llm-d scheduler. They complement each other; a gateway that picks a backend group and then round-robins replicas throws away the cluster layer's benefits.

LayerDecidesExamples
AI gatewayModel alias, backend group, provider fallback, tenant limitsLiteLLM, Envoy AI Gateway, other open-source and commercial gateways
Inference routingWhich replica, by cache overlap and loadGateway API Inference Extension, Dynamo router, llm-d
Engine schedulerWhich requests run in this stepvLLM, SGLang, TensorRT-LLM
Hands-on practice

A gateway with a fallback you can watch

  1. Run two small vLLM (or SGLang) servers on two ports or GPUs serving the same model.
  2. Run the LiteLLM proxy with the config from this lesson, pointing both chat entries at your servers and chat-backup at any other OpenAI-compatible endpoint you have.
  3. Send requests for model chat through the proxy with its master key and confirm they spread across both servers.
  4. Stop one server and confirm traffic continues on the other; stop both and confirm requests fall back to chat-backup.
  5. Create a virtual key with a low tokens-per-minute limit, exceed it, and inspect the 429 response.
  6. Look at the proxy's per-request logs or metrics and confirm you can tell which backend served each request.
Cheat sheet

AI gateways — at a glance

Main things to focus on

  • Applications call model aliases on one API; the gateway maps them to backends.
  • Keys, quotas and budgets live at the gateway, in tokens as well as requests.
  • Retries with backoff for idempotent failures; never after tokens streamed.
  • Fallbacks must be real substitutes: format, context, tools, quality.
  • Exact caching only for deterministic repeats; semantic caching with care; never cross tenants.
  • Gateway picks the backend group; inference routing picks the replica.

LiteLLM proxy config

model_list: - model_name: ALIAS litellm_params: {model, api_base}Map an alias to a backend
model: hosted_vllm/MODELSelf-hosted vLLM backend
api_key: os.environ/VARRead secrets from the environment
router_settings: {routing_strategy: least-busy}Also simple-shuffle, latency-, cost-, usage-based
fallbacks: [{"chat": ["chat-backup"]}]Fallback model groups
general_settings: {master_key: ...}Require auth on the proxy

Reliability patterns

retry: timeouts, 5xx, backend 429With exponential backoff and jitter
fallback: alias -> substitute aliasOn repeated failure or saturation
context-window fallbackToo-long requests to a larger-window model
weighted routing 95/5Canary a new model version

Limits

rpm / tpm per key or teamRequests and tokens per minute
budget per tenant per periodSpend cap
HTTP 429 + Retry-AfterClear rejection when exceeded

Caching

exact cacheSame model + messages + params
semantic cacheSimilar questions; risk of wrong answers
cache key includes tenantNever share across customers

Common pitfalls

  • Applications holding provider keys and calling backends directly.
  • Request-count limits only, so a few huge requests exhaust capacity.
  • Retrying after tokens already streamed, duplicating output.
  • Fallback models that silently change quality or break tool calling.
  • A gateway that round-robins replicas and defeats cache-aware routing.
Quiz

Check your understanding

5 questions · 4 to pass · answers are explained as you go. Your best score is saved on this device only.

Progress and quiz scores are saved in this browser only. Back up or restore on the hub.

Was this lesson useful? Tell me what to improve →