AI infrastructure and systemsPart 4: AI application systems
Chapter 15LLM gateways, routing and caching
When a model provider has a bad hour, every product that calls it directly has a bad hour too, and the team that hard-coded one API key into 30 services finds out which of them have no timeout. A gateway turns that hour into a fallback, a dashboard line and a bill that is still inside budget.
After this chapter you can
- Explain why a gateway layer exists and what belongs in it
- Configure timeouts, retries, fallbacks and circuit breakers that do not cause retry storms
- Enforce per-tenant rate limits and budgets with token buckets and virtual keys
- Route requests across models by cost and difficulty
- Structure prompts for provider prompt-cache hits, and judge when semantic caching is safe
Why a gateway layer exists
An LLM gateway is a reverse proxy that sits between your applications and every model they use, hosted or self-hosted. Applications send one API format to one address. The gateway handles everything that is about operating models rather than about the product.
| Concern | Without a gateway | With a gateway |
|---|---|---|
| Provider keys | Copied into every service | Held in one place; apps get revocable virtual keys |
| Outages | Each app fails its own way | Central retries, fallbacks, circuit breakers |
| Spend | Discovered on the invoice | Per-team budgets enforced before the call |
| Model changes | Code change in every service | Config change in one place |
| Visibility | Scattered logs | One record per call: model, tokens, latency, cost, cache hits |
The open-source options are mature. LiteLLM (Python) has the broadest provider coverage plus virtual keys and budgets. The Portkey gateway (TypeScript) and Bifrost (Go) emphasize low overhead, and Envoy AI Gateway builds on Envoy for Kubernetes platforms. Hosted gateways from cloud and CDN vendors offer the same functions as a service.
One API over many providers
Most of the industry speaks the OpenAI-compatible Chat Completions format: a messages array, optional tools, and a usage object in the response. vLLM, Ollama, llama.cpp's server and most gateways accept it, so a client written once works against all of them by changing the base URL. The differences are where bugs hide.
| Area | What varies between providers |
|---|---|
| Tool calling | Schema subsets supported, parallel calls, how errors are returned |
| Streaming | Event names, where usage appears, how tool-call arguments arrive in chunks |
| Reasoning | Whether thinking tokens are returned, billed or hidden, and how effort is set |
| Caching | Automatic or explicit, minimum lengths, how cached tokens are reported |
| Limits | Context window, max output tokens, rate-limit headers |
| Errors | Status codes for overload (429, 503, 529) and content refusals |
A gateway normalizes the common path and must pass the rest through cleanly. Test streaming and tool calls per provider; they break first.
Timeouts, retries, fallbacks and circuit breakers
Timeouts come in layers
A single "30 second timeout" is wrong for LLM calls, because a healthy response can stream for minutes while a dead one never sends a byte. Use separate limits:
- Connect timeout, a few seconds: the provider is unreachable.
- Time to first token, tens of seconds for big prompts: the provider accepted the request but is stuck.
- Idle timeout between chunks: the stream stalled mid-answer.
- Overall deadline: inherited from the caller, so you never work on a request the user abandoned.
Retries without storms
Retry only what can succeed on retry: 429s (honouring retry-after), overload responses, 5xx errors and timeouts. Never retry 400s or auth failures. Use exponential backoff with jitter so that thousands of clients do not retry in lockstep. Cap retries with a retry budget, for example retries may not exceed 10 percent of requests; otherwise a struggling provider receives three times its normal load exactly when it can least handle it. Once you have streamed tokens to the client, you cannot transparently retry, so fail fast before the first byte.
Fallbacks change behaviour
A fallback sends a failed request to another deployment or model. A fallback to the same model at another region or provider is nearly invisible. A fallback to a different model changes outputs, tool-calling reliability and context limits, so it needs its own eval run before you rely on it. Context-window fallbacks (send oversized prompts to a longer-context model) and refusal fallbacks are useful special cases.
Circuit breakers stop the bleeding
A circuit breaker tracks failures per deployment and stops sending traffic to one that is clearly down, instead of paying a timeout on every request.
While the breaker is open, requests go straight to the fallback. LiteLLM implements this as allowed_fails and cooldown_time per deployment.
Keys, quotas and budgets per tenant
Virtual keys
Applications should never hold provider keys. The gateway issues virtual keys, each mapped to a team or service with its own allowed models, rate limits and budget. Provider keys live in a secret manager, are loaded by the gateway only and can be rotated without touching any application. Revoking a leaked virtual key affects one tenant, not the company.
Token buckets for rate limits
Providers limit you in requests per minute (RPM) and tokens per minute (TPM), and you must share those limits fairly among tenants. The standard algorithm is a token bucket: each tenant has a bucket that refills at a steady rate up to a maximum, and each request removes tokens. Bursts are allowed up to the bucket size; sustained rate is capped by the refill rate.
import time
class TokenBucket:
def __init__(self, rate_per_s: float, capacity: float):
self.rate, self.capacity = rate_per_s, capacity
self.tokens, self.updated = capacity, time.monotonic()
def try_take(self, n: float) -> bool:
now = time.monotonic()
self.tokens = min(self.capacity, self.tokens + (now - self.updated) * self.rate)
self.updated = now
if self.tokens >= n:
self.tokens -= n
return True
return False
# 100k TPM for one tenant, with bursts up to 20k tokens
bucket = TokenBucket(rate_per_s=100_000 / 60, capacity=20_000)Two details make this work for LLMs. You do not know output length in advance, so reserve estimated tokens, then reconcile: take input tokens plus max_tokens up front and refund the difference when the real usage arrives. With several gateway replicas, the bucket state must be shared, typically in Redis, updated with an atomic script.
Budgets
A budget caps spend per key, team or user over a period. Enforce it before the call (reject when spend has reached the cap), alert at a soft threshold such as 80 percent, and reset on a schedule. Spend counters are usually updated asynchronously, so a burst can overshoot slightly; size hard limits with that in mind.
Logging
Log metadata for every call: tenant, model, deployment, input, cached and output tokens, latency, time to first token, cost, cache hit and fallback count. Prompts and completions contain personal data and sometimes secrets, so log bodies only with redaction, sampling, short retention and access control. The chapter "Observability for AI systems" covers tracing these calls with OpenTelemetry.
Routing by cost and difficulty
Prices between small and frontier models differ by one to two orders of magnitude per token, while many requests do not need the frontier model. Model routing sends each request to the cheapest model likely to handle it.
| Strategy | How it decides | Watch out for |
|---|---|---|
| Static by route | Each feature or endpoint is pinned to a model | Simple and predictable; the default |
| Classifier router | A small model or trained classifier predicts difficulty | Router errors are silent quality loss |
| Cascade | Try the cheap model; escalate if a validator, schema check or confidence test fails | Added latency on escalations |
| Load and price aware | Choose among equivalent deployments by price, latency or remaining quota | Keep outputs equivalent across them |
A cascade is the easiest to make safe because escalation is triggered by a check you can test, such as "the JSON validated" or "the answer cited a source". Measure every router with the same eval suite you use for model changes; a router that saves 60 percent of cost and loses 5 points of quality is a product decision, not an infrastructure detail.
Provider prompt caching
Prompt caching reuses the attention key-value state a provider computed for a prompt prefix it has seen recently, so the shared part is neither recomputed nor billed at full price. It is the same KV cache described in "Inference fundamentals", kept between requests. Cached reads are typically billed at about a tenth of the normal input price and cut time to first token on long prompts substantially.
The mechanism dictates the rule: a cache hit needs an exact prefix match, token for token, from the very start of the prompt up to a cache boundary. One changed character invalidates everything after it.
Order prompts from most stable to least stable, and never put changing values early.
| Cache killer | Fix |
|---|---|
| Current date or request ID in the system prompt | Move it to the final user message |
| Tools listed in a different order per request | Sort tool definitions deterministically |
| JSON serialized with unstable key order | Serialize with sorted keys |
| Per-user data at the top of the prompt | Put shared content first, user content after |
| Rewriting or trimming history every turn | Append only; compact rarely and in large steps |
| Gateway injects metadata into messages | Pass metadata in headers, not prompt text |
| Provider style | How caching is triggered | Notable rules (late 2026) |
|---|---|---|
| OpenAI | Automatic on supported models; newest models also accept explicit breakpoints | Minimum about 1,024 tokens; prompt_cache_key improves routing to a warm cache; writes on newer models cost more than plain input, reads much less |
| Anthropic | cache_control set automatically at the top level, or on up to 4 explicit breakpoints | 5-minute default lifetime or 1 hour at a higher write price; writes 1.25 or 2 times input, reads 0.1 times |
| Self-hosted vLLM or SGLang | Automatic prefix caching in GPU memory | Free, but only hits on the replica that holds the prefix, so route by prefix or session |
Exact numbers and prices change often; check the provider documentation linked at the end. The mechanism, exact prefix match with a short lifetime, has been stable across every provider.
Response caching and semantic caching
A response cache returns a stored completion without calling the model at all. An exact response cache keys on a hash of the entire request: model, messages and parameters. It is safe for deterministic workloads such as evals, batch jobs and repeated tool lookups, but most interactive traffic never repeats exactly.
A semantic cache embeds the prompt and returns a cached answer when a previous prompt is similar enough. It finds more hits, and it fails in ways an exact cache cannot.
Where semantic caching works
- Single-turn, FAQ-like questions with stable answers
- Answers that do not depend on who asks
- Short TTLs and a high similarity threshold
- A measured false-hit rate on real traffic
Where it goes wrong
- "Refund policy in Germany" matches "refund policy in France"
- Multi-turn or agent traffic, where the latest message alone is ambiguous
- Answers that depend on the user's data or permissions
- Content that changes faster than the TTL
Key terms
- LLM gateway
- A proxy between applications and models that centralizes keys, routing, limits, caching and logging.
- Virtual key
- A gateway-issued credential mapped to a tenant, with its own models, limits and budget.
- Token bucket
- A rate-limit algorithm that refills tokens at a fixed rate up to a cap, allowing bounded bursts.
- Retry budget
- A cap on retries as a fraction of traffic, preventing retries from amplifying an outage.
- Circuit breaker
- A per-deployment switch that stops sending traffic after repeated failures and probes for recovery.
- Fallback
- Sending a failed request to an alternative deployment or model.
- Prompt caching
- Provider-side reuse of the KV state of an exactly matching prompt prefix.
- Semantic cache
- A response cache that returns answers for prompts whose embeddings are similar to earlier ones.
- Cascade routing
- Trying a cheap model first and escalating to a stronger one when a check fails.
Run an LLM gateway with fallbacks, budgets and caching
Goal: run LiteLLM in front of two local models, prove a fallback works, enforce a per-key budget and rate limit, and measure cache hit rate and cost.
You need: Docker with Compose, Python 3.11 or newer and Ollama. The models are local and free; the lab assigns them pretend prices so that cost tracking has something to count.
- Pull two small models. On Linux, Ollama must listen on all interfaces so the container can reach it; on macOS with Docker Desktop the default works.
ollama pull llama3.2:1b && ollama pull llama3.2:3b
# Linux only: restart Ollama listening on all interfaces
OLLAMA_HOST=0.0.0.0 ollama serve- Write the gateway config.
flakypoints at a port where nothing listens, so it always fails and falls back tosmall.
model_list:
- model_name: small
litellm_params:
model: ollama_chat/llama3.2:1b
api_base: http://host.docker.internal:11434
model_info:
input_cost_per_token: 0.0000002 # pretend: $0.20 per million input tokens
output_cost_per_token: 0.0000008
- model_name: large
litellm_params:
model: ollama_chat/llama3.2:3b
api_base: http://host.docker.internal:11434
model_info:
input_cost_per_token: 0.000003 # pretend: $3 per million input tokens
output_cost_per_token: 0.000015
- model_name: flaky
litellm_params:
model: ollama_chat/llama3.2:3b
api_base: http://host.docker.internal:11999 # nothing listens here
timeout: 5
model_info:
input_cost_per_token: 0.000003
output_cost_per_token: 0.000015
router_settings:
num_retries: 1
allowed_fails: 2
cooldown_time: 30
fallbacks: [{"flaky": ["small"]}]
litellm_settings:
cache: true
cache_params:
type: local
general_settings:
master_key: os.environ/LITELLM_MASTER_KEY- Write the Compose file. Postgres stores virtual keys and spend.
services:
litellm:
image: docker.litellm.ai/berriai/litellm:latest # pin a release tag for real use
command: ["--config", "/app/config.yaml"]
ports: ["4000:4000"]
volumes: ["./config.yaml:/app/config.yaml:ro"]
extra_hosts: ["host.docker.internal:host-gateway"]
environment:
LITELLM_MASTER_KEY: ${LITELLM_MASTER_KEY}
LITELLM_SALT_KEY: ${LITELLM_SALT_KEY}
DATABASE_URL: postgresql://litellm:litellm@db:5432/litellm
depends_on:
db: {condition: service_healthy}
db:
image: postgres:16
environment: {POSTGRES_USER: litellm, POSTGRES_PASSWORD: litellm, POSTGRES_DB: litellm}
healthcheck:
test: ["CMD-SHELL", "pg_isready -U litellm"]
interval: 5s
retries: 10printf 'LITELLM_MASTER_KEY=sk-%s\nLITELLM_SALT_KEY=sk-%s\n' \
"$(openssl rand -hex 16)" "$(openssl rand -hex 16)" > .env
docker compose up -d && docker compose logs -f litellm # wait for the startup banner, then Ctrl+C
set -a; source .env; set +a- Issue three virtual keys: one with a tiny budget, one with a rate limit, one for benchmarking.
newkey() {
curl -s localhost:4000/key/generate -H "Authorization: Bearer $LITELLM_MASTER_KEY" \
-H 'Content-Type: application/json' -d "$1" \
| python3 -c 'import sys, json; print(json.load(sys.stdin)["key"])'
}
export BUDGET_KEY=$(newkey '{"key_alias": "team-budget", "max_budget": 0.002}')
export RPM_KEY=$(newkey '{"key_alias": "team-rpm", "rpm_limit": 5}')
export BENCH_KEY=$(newkey '{"key_alias": "bench"}')
echo $BUDGET_KEY $RPM_KEY $BENCH_KEY- Prove the fallback. Ask for
flakyand look at the headers.
curl -si localhost:4000/v1/chat/completions -H "Authorization: Bearer $BENCH_KEY" \
-H 'Content-Type: application/json' \
-d '{"model": "flaky", "messages": [{"role": "user", "content": "Say hi"}]}' \
| grep -iE 'x-litellm-attempted-fallbacks|"model"'You should see x-litellm-attempted-fallbacks: 1 and a response whose model is the 1B model. Repeat a few times: once the breaker opens, flaky fails over immediately instead of waiting for its timeout.
- Measure caching. The benchmark sends 60 requests drawn from 10 prompts with a skewed popularity distribution, like real traffic.
import os, random, statistics, time
import requests
TOPICS = ["a token bucket", "a circuit breaker", "an idempotency key", "prompt caching",
"a vector index", "exponential backoff", "a virtual key", "a fallback model",
"semantic caching", "a retry budget"]
PROMPTS = [f"In one sentence, what is {t}?" for t in TOPICS]
WEIGHTS = [1 / (i + 1) for i in range(len(PROMPTS))] # a few prompts dominate
random.seed(7)
hit_ms, miss_ms, cost = [], [], 0.0
for _ in range(60):
prompt = random.choices(PROMPTS, WEIGHTS)[0]
t = time.perf_counter()
r = requests.post("http://localhost:4000/v1/chat/completions",
headers={"Authorization": f"Bearer {os.environ['BENCH_KEY']}"},
json={"model": "large", "max_tokens": 60,
"messages": [{"role": "user", "content": prompt}]})
r.raise_for_status()
ms = (time.perf_counter() - t) * 1000
(hit_ms if "x-litellm-cache-key" in r.headers else miss_ms).append(ms)
cost += float(r.headers.get("x-litellm-response-cost") or 0)
n_hit, n_miss = len(hit_ms), len(miss_ms)
print(f"hit rate {n_hit / 60:.0%} hits={n_hit} misses={n_miss}")
print(f"p50 latency: hit {statistics.median(hit_ms):.0f} ms, miss {statistics.median(miss_ms):.0f} ms")
avg_miss_cost = cost / max(n_miss, 1)
print(f"spend ${cost:.6f}; without the cache about ${avg_miss_cost * 60:.6f}")pip install requests && python bench.pyExpect a hit rate around 80 percent (only the first request for each prompt misses), hits answered in tens of milliseconds and misses in hundreds of milliseconds or seconds. Run it again and the hit rate approaches 100 percent, because the cache is still warm.
- Hit the budget. Unique prompts defeat the cache, so every request costs money.
for i in $(seq 1 30); do
code=$(curl -s -o /tmp/out.json -w '%{http_code}' localhost:4000/v1/chat/completions \
-H "Authorization: Bearer $BUDGET_KEY" -H 'Content-Type: application/json' \
-d "{\"model\": \"large\", \"messages\": [{\"role\": \"user\", \"content\": \"Write 80 words about request $i\"}]}")
echo "request $i: HTTP $code"; [ "$code" != "200" ] && cat /tmp/out.json && break
done
curl -s "localhost:4000/key/info?key=$BUDGET_KEY" -H "Authorization: Bearer $LITELLM_MASTER_KEY" \
| python3 -c 'import sys, json; i = json.load(sys.stdin)["info"]; print("spend", i.get("spend"), "max_budget", i.get("max_budget"))'After some requests you get an error that the budget is exceeded, and key/info shows spend at or slightly above 0.002. The overshoot is the asynchronous spend update described earlier.
- Hit the rate limit with eight quick requests on the RPM key; expect HTTP 429 after the fifth.
for i in $(seq 1 8); do
curl -s -o /dev/null -w "request $i: HTTP %{http_code}\n" localhost:4000/v1/chat/completions \
-H "Authorization: Bearer $RPM_KEY" -H 'Content-Type: application/json' \
-d "{\"model\": \"small\", \"max_tokens\": 5, \"messages\": [{\"role\": \"user\", \"content\": \"ping $i\"}]}"
doneCheck your work: you can show a fallback header on flaky requests, a measured hit rate and the latency gap between hits and misses, a budget error with the recorded spend, and 429 responses once the RPM key passes five requests a minute.
Stretch: switch the cache to redis-semantic with a Redis Stack container, send pairs of near-identical questions with different correct answers (refund policy in two countries) and measure the false-hit rate at two similarity thresholds.
Check yourself
A provider starts returning 503s for 20 percent of requests. Every client retries each failure three times with no backoff. What happens next?
Your Anthropic bill shows cache writes on almost every request but almost no cache reads. The system prompt begins with the current timestamp. What is the fix?
Why does a token-bucket limiter for LLM traffic reserve input tokens plus max_tokens before the call?
A team adds a semantic cache in front of a multi-tenant support assistant and sees a 40 percent hit rate. What is the most serious risk?
You configure a fallback from a frontier model to a much smaller model from another vendor. What must you do before trusting it in production?
Recap
- A gateway centralizes keys, routing, limits, caching and logging so applications speak one API and stay simple.
- Use layered timeouts, retry only retryable errors with jittered backoff and a retry budget, and isolate dead deployments with circuit breakers.
- Issue virtual keys per tenant, enforce rate limits with token buckets that reserve and reconcile, and enforce budgets before the call.
- Route by cost and difficulty, and measure every routing or fallback change with evals.
- Provider prompt caching needs exact prefixes: put stable content first, keep history append-only and never inject changing values early.
- Exact response caches are safe for deterministic work; semantic caches need tenant scoping, high thresholds and a measured false-hit rate.
Go deeper
- LiteLLM proxy documentation: configuration for routing, fallbacks, virtual keys, budgets and caching used in the lab.
- OpenAI prompt caching guide: exact rules for breakpoints, minimum lengths, lifetimes and cache keys.
- Anthropic prompt caching documentation: breakpoints, the lookback window and pricing, with worked examples of cache misses.
- vLLM automatic prefix caching: how self-hosted servers reuse KV cache between requests.
- Handling overload (Google SRE book): retry budgets, client-side throttling and load shedding from first principles.