A gateway (an LLM proxy) is one endpoint in front of every model provider that turns each model call into a chain of decisions: may this caller spend, which deployment answers, what to do when it fails, and what to log. Each decision follows a rule in the code, and several of those rules are not what the configuration file suggests.
Fig. 1 is the whole page in one picture: your code speaks one format to one place, and the gateway decides the rest. On the left, callers (an agent with virtual key sk-team-a, a batch job with sk-team-b, an eval run that pins one provider, section 9); in the middle, the gateway's stations in the order a request meets them in LiteLLM's proxy; on the right, the upstreams: model group "chat" (deployment A, provider X in region 1; deployment B, provider Y), fallback group "chat-backup" (deployment C, another model family) and OpenRouter, a rented gateway that is one more upstream. A cooldown moves traffic inside a group; a fallback moves it to another group. Three stations are where this page's recordings found the rule differs from the config's wording: rate limit and budget (sections 5, 6), route (2, 10) and retry, cool down, fall back (3, 4). SOURCE
The same request takes three paths depending on what the gateway already knows. Note two orders the docs do not make obvious: the budget is reserved at authentication, before the cache is consulted, and the cache lookup happens after routing, inside the call to the chosen deployment.
max_tokens, or 16,384 output tokens if none) and reserves that against every budget the key sits under (section 6).rpm_limit (section 5).You need: why an agent stack wants a gateway at all, on the parent Topic: agentic-frameworks (Reading section 6, and its Production stack tab, which records one LiteLLM proxy falling back); retries with backoff and the token bucket, on Reliability engineering.
New terms. Deployment: one concrete endpoint (provider, model id, base URL, key); each model_list entry in LiteLLM's config. Model group: the name your code asks for (model="chat"); every deployment sharing that model_name; a group of one is common and changes the failure rules (section 3). Provider prefix: the part before the slash in litellm_params.model (openai/, anthropic/, lm_studio/); it chooses the code that speaks to the upstream, so it decides the wire format (section 8). Router and proxy: LiteLLM is a Python library whose Router does routing, retries, cooldowns and fallbacks in your process, and a proxy server (litellm --config) that wraps the same Router behind HTTP and adds keys, budgets, rate limits and spend logs. Virtual key: a key the gateway issues (sk-...) carrying limits (models allowed, budget, requests and tokens per minute, parallel requests). Cooldown: a deployment the router stops sending traffic to for a few seconds after failures.
mlx-community/Qwen3-4B-Instruct-2507-4bit, mlx-lm 0.32.0); Claude Haiku 4.5 through the Claude Code CLI for the router experiment. OpenRouter was not called (no account); its public catalogue was read the same day. Labels: MEASURED recorded here, SOURCE read from code at the pinned version, DOCS vendor documentation, UNCONFIRMED could not be checked.The duties, in order: authenticate the caller from a gateway-issued key, so provider keys live in one place; authorise the model (some data may go only to approved vendors or self-hosted models); check rate limits and budget; transform and guard (redact personal data, apply input rails: the classifiers are on Guardrails); look up the cache; route; call with a timeout, retrying or falling back on failure; stream the reply back unbuffered; write one usage event (caller, model, input, cached and output tokens, cost, latency) for billing and dashboards. Turning those events into traces is LLM observability; how the gateway sits in a whole LLM service (tenancy, the batch path, rollouts, degradation ladders) is ML system design.
What it costs: one more network hop (milliseconds against seconds of generation); one more service that must not go down (run several stateless copies behind a load balancer, and keep its own dependencies, such as Redis for counters, off the critical path when they fail); the risk that it buffers streams or caps connection times; it concentrates power, because whoever owns it decides which models the company may use; and it concentrates secrets, because its database holds every provider key, which makes the gateway itself the prize. The LiteLLM 1.107.0 release of 21 October 2026 was a credential stealer, built and signed by LiteLLM's own release pipeline after an attacker took a maintainer's GitHub token; its payload read the provider keys from the proxy's database along with every token on the host (the chain is on Agent security, section 3). For a gateway that means: pin the version and upgrade deliberately, never latest; verify the image against the publisher's current signing key; keep a rotation plan for every provider key it holds; and do not log request or response bodies by default, since agents' traffic can carry tokens. When not to run one: a single product calling a single provider, owned by one team; a client library with retries and a usage log is enough until a second model, a second team or a budget question appears.
Uber built its GenAI Gateway as "a Go service that acts as an encompassing layer around the clients for third-party vendors"; "a pivotal design decision was to mirror the HTTP/JSON interface of the OpenAI API", and it includes "a PII redactor that anonymizes sensitive information within requests before forwarding them to third-party vendors" and audit logs for "cost attribution, security audit purposes, quality evaluation". In mid-2024 it was "used by close to 30 customer teams and serves 16 million queries per month, with a peak QPS of 25" (Uber Engineering, 11 Jul 2024). 25 queries a second is small: a gateway exists for control, not for throughput.
Bloomberg and Tetrate started Envoy AI Gateway because "traditional rate-limiting based on number of requests doesn't work for controlling usage of LLM providers" (announcement, 18 Oct 2024); renamed Agent Router (v1.1.0, 21 Aug 2026), its README describes two tiers: "The Tier One Gateway handles authentication, top-level routing, and global rate limiting", and a second tier in front of self-hosted models picks the endpoint (README at v1.1.0).
Chip Huyen's AI Engineering (O'Reilly, 2025) makes "Add Model Router and Gateway" step 3 of its five-step platform architecture, after context and guardrails and before caches (table of contents, chapter 10). DOCS
When a group has several deployments (the same model in two regions, or at two providers), something picks one per call, and the pick decides latency, cost and how evenly load spreads. Each LiteLLM routing_strategy is a small file in litellm/router_strategy/, and what it measures is easy to get wrong from its name. SOURCE One level down, inside a self-hosted pool, a second router picks the replica by queue and prefix cache: that layer is LLM serving in production, section 1. The auto routers (auto_router/complexity_router, adaptive_router and others) choose between different models from the prompt (section 10).
The recording. One group, two copies of the same fake model: A answers in 0.2 s, B in 1.0 s. Forty requests, four at a time, through litellm.Router under each strategy; Fig. 2 piles up the requests each copy answered and says what the strategy read. In the cost rows B is the cheaper copy ($1 against $2 per million input tokens). MEASURED
simple-shuffle (default). Random choice, weighted by weight if set (or else rpm, or else tpm) (simple_shuffle.py). Recorded: 19 to A, 21 to B, all 40 in 6.5 s.simple-shuffle, weight A 3 : B 1. The same coin, loaded: 29 to A, 11 to B, 4.9 s.least-busy. Fewest requests in flight right now (least_busy.py). It sent 26 to A without measuring anything: A finishes sooner, so it is idle more often when the next request arrives.latency-based-routing. Lowest average of the last 10 latencies, where a latency is the response time divided by the output tokens (time to first token when streaming). No history counts as 0, so a new deployment is tried first; a timeout adds a 1,000-second penalty sample; lowest_latency_buffer (default 0) picks at random within that fraction of the best; history lives 1 hour (lowest_latency.py). Latency-based routing found the fast copy but still sent it only 34 of 40: both copies start at "no history = 0" and B is tried until its own samples push its average up. That exploration is the price of measuring.usage-based-routing-v2. Fewest tokens used in the current calendar minute, skipping any over its own tpm/rpm (lowest_tpm_rpm_v2.py; counters keyed by %H-%M). Usage-based balanced tokens per minute (18 to 22), which is what it is for, and ignored that B is five times slower: the slowest run, 7.4 s.cost-based-routing, prices in model_info. Cheapest by input plus output price per token, read from litellm_params, else LiteLLM's price map for the model name, else $5.00 per token each (lowest_cost.py). Cost-based with prices in model_info sent all 40 to A, the expensive copy: the strategy reads prices only from litellm_params, so both copies cost the default and the first wins every tie.litellm_params. Moving the same two numbers into litellm_params sent all 40 to B: cheap, and at 11.0 s the slowest by far. The proxy's spend tracking does read model_info prices, so the mistake in step 6 is invisible on the bill.x-litellm-model-id response header).Each bar is one request, placed at the time it was sent and coloured by the copy that answered (blue A, orange B). It opens on all 40; drag back to watch the strategy decide, and switch strategy to compare on the same workload.
Load balancing in general (layer 4 against layer 7, round robin in the client) is on Service APIs, section 13; this section is only what LiteLLM implements.
Retry: the same group again after a short wait (a blip?). Cooldown: stop routing to one deployment for a while (a broken copy?). Fallback: call another group (is this model unusable right now?). LiteLLM chooses by the error's HTTP status: SOURCE
| Upstream answer | Retried in the group? | Can cool the deployment down? | Goes to fallbacks? |
|---|---|---|---|
| 429 rate limited | yes | yes, at once, if the group has another deployment | yes |
| 500, 502, 503 and any 5xx | yes | yes, once more than half of this minute's calls to it failed and it had at least 5 | yes |
| 408 timeout, 409 | yes | 408 yes, 409 no | yes |
| 401, 403 bad credentials | only if the group has another deployment | 401 yes | yes |
| 400 context window exceeded | no | no | yes: to context_window_fallbacks if set, else to the regular fallbacks |
| 400 content policy | no | no | yes: to content_policy_fallbacks if set, else regular |
| other 400s, 404 | no | 404 yes | regular fallbacks |
From litellm/utils.py (_should_retry: 408, 409, 429 and 5xx), router.py (should_retry_this_error) and router_utils/cooldown_handlers.py (_is_cooldown_required, _should_cooldown_deployment) in 1.104.0. Defaults: num_retries 2, cooldown_time 5 s, at most 5 fallbacks per request; an error whose text contains "APIConnectionError" never triggers a cooldown.
Two cooldown regimes, and a trap. Without allowed_fails, the rules in the table apply: a 429 benches a deployment at once, other errors only once more than 50% of its calls this minute failed and there were at least 5 (DEFAULT_FAILURE_THRESHOLD_PERCENT 0.5, DEFAULT_FAILURE_THRESHOLD_MINIMUM_REQUESTS 5). With allowed_fails, a simpler counter: cool down once failures within cooldown_time exceed it. But the code decides whether you "set" it by comparing with the library default, 3 (_is_allowed_fails_set_on_router). Writing allowed_fails: 3 in a config therefore changes nothing; the parent page's Production stack config contains exactly that line.
The recording. A group of two: A healthy (0.2 s), C scripted to fail every call. Thirty requests one after another, 0.3 s apart, num_retries: 2. Each mark is one call that reached C; a red mark is a request whose user got an error. MEASURED
allowed_fails: 3: the same, as the source predicts, plus one user error: request 2 picked C, and both retries picked C again. A retry re-runs the routing choice at random, so with two deployments a request whose first pick is the bad one fails all three tries with probability 1/2 × 1/2 = 1/4 while the bad one is not benched. enable_weighted_failover (async calls, simple-shuffle only) re-picks among the other deployments instead.allowed_fails: 1: benched after its second failure, back 5 s later.ContextWindowExceededError in 0.1 s; with either fallbacks or context_window_fallbacks the request went straight to the long-context group.allowed_fails: 3 and cooldown_time: 60, expecting it to be benched after three failures for a minute. What happens?cooldown_time is honoured. Write allowed_fails: 2 or use allowed_fails_policy (per error type, for example InternalServerErrorAllowedFails) to get a counter that applies.Grey bands: more than 4 s in which no call reached C although requests kept coming, which the rules attribute to a cooldown. Seconds from the first request. Every attempt, including those to A, is replayed at the end of section 4.
Outages: plan the fallback, do not just configure it. A fallback is another deployment of the same model, the same model at another provider (Claude is also sold through AWS Bedrock and Google Vertex AI, and OpenAI's models through Azure, AWS Bedrock and, in private preview since October 2026, Vertex AI; open models through many, section 9), or a different model. Check it like a backup generator: is its quota big enough to take all the traffic at once; does it accept the same prompt and tool-call format; does it behave the same on safety; has it been evaluated on your task? It starts with a cold prompt cache, so requests cost more and first tokens come later until it warms. A fallback that has never carried full traffic is untested; fail over on a schedule.
An agent's model call passes through several programs that each retry: the provider SDK in your agent, your own loop, the gateway, sometimes a second gateway. Each layer's retries run once for every attempt of the layer above. With the SDK's 2 retries and the gateway's 2, one request can reach the provider 3 × 3 = 9 times:
num_retries, 2 in this config, and a default request timeout of 6,000 seconds)Defaults read from openai/_constants.py (openai 2.54.0), anthropic/_constants.py (anthropic 1.11.0) and litellm/constants.py (DEFAULT_REQUEST_TIMEOUT_SECONDS = 6000.0), 6 October 2026. SOURCE
The recording. Provider C hangs for 30 seconds on every call. The gateway gives each attempt 5 seconds and retries twice. The client is the OpenAI Python SDK, run three ways. In Fig. 3 time runs left to right; the three rows are the SDK, the gateway and the provider, and each provider bar is one call it worked on. MEASURED
APITimeoutError after 32.8 s and three sends; the provider received 9 calls, the last one starting at 36.9 s, four seconds after the user had been told it failed. 270 seconds of provider work for one failed request. The gateway does not stop its retry chain when the client hangs up.max_retries=0 in the SDK: 3 calls, error after 10.2 s (the gateway still sent the third, grey, after the user's error).Other coding harnesses hit the same from the other side: Gemini CLI 0.62.0 waits 60 s for headers and retries up to 10 times, so against a slow local server its retries overlapped and multiplied the load until the server ran out of memory. MEASURED there
Pick a case; it opens on the end of the run, and the scrubber walks back through the attempts in the order they happened, lane by lane (the caller's requests, healthy provider A, failing provider C), with a line saying what happened and running counts. Pairs worth comparing: 429 against 503; allowed_fails 3 against 1; context error with and without fallbacks; SDK 2 retries against 0.
How it was recorded: each fake provider is one small Python HTTP server (src/code/fake_provider.py), scripted per case to answer, fail with a status or hang; it logs every call with its start and end time and the request's text, which names the case and request number, so every attempt is matched to its request. Router cases: src/code/e2_failures.py (sequential requests 0.3 s apart, a warm-up first because the first failing call in a fresh process paid about 10 s of one-off set-up in a trial run). Retry layers: src/code/e3_amplify.py (openai 2.54.0 against the proxy).
A rate limit caps how much one caller may send per unit of time, so one runaway agent cannot take everyone's capacity; past it the server answers 429 Too Many Requests, which "MAY include a Retry-After header indicating how long to wait" (RFC 6585 §4). For LLM traffic the unit cannot be requests alone. Two customers limited to 60 requests a minute: one sends 60 short chats (60 × 1,400 = 84,000 tokens), the other 60 requests each carrying a 50,000-token contract (3 million tokens, 36 times the load for the same "60 requests"). So limits count tokens too, and the usual algorithm is a token bucket holding model tokens (the algorithm is taught on Reliability engineering). An agent behind a gateway meets limits in three places, each counted differently:
| Where | Counted in | Algorithm | Answer when over |
|---|---|---|---|
| Provider (Anthropic, per organisation and model class) | requests, input tokens, output tokens per minute (RPM, ITPM, OTPM) | token bucket: "capacity is continuously replenished up to your maximum limit, rather than being reset at fixed intervals"; "a rate of 60 requests per minute (RPM) might be enforced as 1 request per second" DOCS | 429 with retry-after |
| Gateway (LiteLLM, per key, user, team, model) | rpm_limit, tpm_limit, max_parallel_requests | a counter per window of 60 s (LITELLM_RATE_LIMIT_WINDOW_SIZE) that starts at the first request and resets whole SOURCE | 429 throttling_error, retry-after: 60 MEASURED |
| Router (LiteLLM, per deployment) | rpm/tpm on a deployment | counts per calendar minute; a deployment over its limit is skipped | the next deployment, or "no deployments available" |
Output tokens are unknown at admission, and limiters answer in one of three ways: reserve the worst case and refund later (OpenAI; LiteLLM's tpm_limit), count output as it is produced (Anthropic), or charge after the response (Envoy AI Gateway, which can end 200 tokens over). Alongside token limits, cap concurrent streams per caller (max_parallel_requests): fifty open streams from one tenant are fifty batch slots nobody else can use, whatever the token count.
The gateway's window, recorded. LiteLLM's limiter calls itself "based on a similar one by Envoy proxy" and names its functions "sliding window", but the code keeps one start time and one counter per key: the first request opens a 60-second window, and once 60 whole seconds have passed the next request starts a fresh one at zero. That is a fixed window anchored on the first request, with the fixed window's weakness at the boundary. Two keys with rpm_limit: 10: one sends a request every second for 130 s; the other sends 1, waits until second 50, sends 9, then 10 more just after the window rolls over. Predict how many the burst key gets through between second 50 and 65; Fig. 4 then plays the recorded burst through LiteLLM's rule and three others side by side, in five stretches of time. MEASURED
429 throttling_error with retry-after: 60.The burst key had 19 requests accepted between second 50 and second 65, almost twice its limit inside 15 seconds, then 429s. A calendar-minute window does the same here, because its boundary at second 60 also falls inside the burst: any fixed window has this weakness. The steady key was accepted for 10 seconds out of every 60 (seconds 0 to 9, 61 to 70, 121 to 129: the limiter counts whole wall-clock seconds, and this run happened to start just before a second ticked over). On the same burst a sliding log accepts at most 10 in any 15 seconds, and a token bucket holding 10 and refilling one every 6 seconds at most 12 (its full bucket plus two refills), which is the shape Anthropic's limiter imposes downstream: a gateway that lets 19 through will meet the provider's 429s.
Replay it yourself. The widget runs both recorded traces (the burst, and a key sending one request per second for 130 s) through the same four limiters at any limit; it opens on the end of the run, and the table counts each limiter's decisions. At the recorded limit (10) LiteLLM's rule, replayed from its source, reproduces every recorded decision.
redis_host set the same window logic runs as a Lua script on the shared Redis (BATCH_RATE_LIMITER_SCRIPT in the same file). SOURCE(1) Reserve the worst case, refund later: OpenAI counts "the maximum of max_tokens and the estimated number of tokens based on the character count", so a careless max_tokens of 32,000 on every call burns limit that is never used (OpenAI rate limits). LiteLLM's tpm_limit does the same with a floor of 1,024 output tokens when max_tokens is missing (DEFAULT_MAX_TOKENS_ESTIMATE 4,096 divided by 4, capped at a quarter of the smallest TPM limit), corrected after the response. SOURCE (2) Count output as it is produced: Anthropic, "OTPM rate limits are evaluated in real time as output tokens are produced, counting only the actual tokens generated." (3) Charge after the response: Envoy AI Gateway (Agent Router) v1.1.0, "Token usage is charged after the response completes"; it "does not interrupt an already admitted stream", so with a 1,000-token hourly limit one admitted request "can stream 1,200 tokens successfully. The bucket is then 200 tokens over the limit" (usage-based rate limiting, v1.1.0). DOCS
Anthropic's input-token limit counts only uncached input for most models ("only uncached input tokens count toward your ITPM"), so with an 80% cache hit rate a 2,000,000 ITPM limit admits 10,000,000 input tokens a minute; output tokens count as they are generated, so a large max_tokens costs nothing against OTPM (rate limits, read 6 Oct 2026). OpenAI returns what is left in x-ratelimit-remaining-tokens and related headers. Envoy's per-tenant, per-model policy, trimmed: the request costs 0 and the response costs its total tokens, read from metadata the gateway fills in; "If the existing charged usage is over the limit, the request is rejected with a 429 status code". DOCS
rateLimit:
type: Global
global:
rules:
- clientSelectors:
- headers:
- {name: x-tenant-id, type: Distinct} # one bucket per tenant
- {name: x-ai-eg-model, type: Exact, value: gpt-4}
limit: {requests: 1000, unit: Hour} # here: 1000 tokens per hour
cost:
request: {from: Number, number: 0}
response: {from: Metadata, metadata: {namespace: io.envoy.ai_gateway, key: llm_total_token}}
Rows: what LiteLLM 1.104.0 answered; LiteLLM's rule read from its source (a 60 s window from the first request, in whole wall-clock seconds) replayed on the same arrivals, which reproduces every recorded decision; a calendar-minute window (what the router uses for a deployment's own rpm); a sliding log (allow if fewer than the limit were accepted in the last 60 s); a token bucket holding the limit, refilled continuously at limit per 60 s (Anthropic's shape). Rejected requests use no capacity in any of them.
A budget caps dollars for a key, user, team, organisation or end customer, optionally per period (budget_duration: "30d"). The gateway prices every call from its price table and adds it to each entity's spend. The hard part is concurrency: if the check reads the spend so far, 20 calls arriving together all see the same number and all pass. DOCS
What 1.104.0 does instead: reserve, then settle. Before calling the provider, the proxy estimates the request's maximum cost (its input tokens, plus max_tokens output tokens, or 16,384 if the request sets none, capped at the model's own output limit) and adds it atomically to the key's counter. If that would cross the budget but some is left, the reservation shrinks to what is left and the call goes ahead; if nothing is left, HTTP 422 budget_exceeded. When the call ends the reservation is replaced by the real cost (proxy/spend_tracking/budget_reservation.py). SOURCE
The recording. Budget $0.0004 per key; each call really costs $0.00008 (40 input tokens at $1 per million, 8 output tokens at $5 per million), so 5 calls fit; the fake provider takes 2 s per call. The same wave of 20 simultaneous calls under three admission policies; predict how many get through without max_tokens. In Fig. 5 the glass tank is the budget, orange is reserved, blue is spent. MEASURED
general_settings: disable_budget_reservation: true, which the docs keep for "temporary mitigation").max_tokens.max_tokens: 16.Ten calls one after another: exactly 5 accepted, final spend $0.0004, then 422s.
max_tokens on every call. Without it, a small per-key budget serialises an agent's parallel tool calls or subagents, and the 422 arrives long before the money is spent. LITELLM_BUDGET_RESERVATION_MAX_COST_USD caps one request's reservation instead (PR 38647). Budgets nest: "If a key belongs to a team, only the team (and team-member) budgets are enforced" (docs).Rate limit, quota, capacity: three refusals to keep apart. A rate limit protects capacity right now; a quota or budget caps total use over a period, usually in money (Envoy: "Use QuotaPolicy when you need to cap cumulative token spend, and usage-based rate limiting (this page) when you need to control request velocity."). Anthropic's API answers 429 with a retry-after header for a rate limit; 429 with no retry-after and the code enforced_spend_limit_reached when the monthly spend cap is reached (every retry layer will hit it again until the month ends); and 529 overloaded_error when "the API experiences high traffic across all users" (Anthropic errors). DOCS A gateway should keep the same three apart for its callers: over your limit (wait), out of budget (stop), out of capacity (fall back). Reserved capacity is the paid way round the third: Anthropic's Priority Tier committed input and output tokens per minute for 1 to 12 months, "targets 99.5% uptime", and "Requests beyond your committed capacity automatically fall back to standard tier"; it is "no longer available for purchase" to new buyers as of October 2026 (Anthropic service tiers). DOCS Its own 429 (throttling_error, retry-after 60) is the caller's key limit, which no fallback can fix; a provider 429 is capacity, which another deployment can. A budget is only as current as the price table, which LiteLLM ships with the library and can refresh at start-up or take from your config (dated table, section 11).
The in-run spend reads can precede LiteLLM's batched spend write, so final spends were read back from /key/list after all runs.
Not prompt caching. Provider prompt caching keeps the computed attention state for a prompt prefix inside the model server, so the model still generates a fresh answer, cheaper (Context engineering and Caching own it). A gateway response cache stores whole answers: on a match the model is never called.
The key. LiteLLM concatenates every model parameter present in the request (model, messages, temperature, max_tokens, tools ...) and hashes it with SHA-256 (Cache.get_cache_key in litellm/caching/caching.py). Backends: in-memory (default TTL 600 s), Redis, S3, GCS, Azure Blob, disk, and three semantic caches (Redis, Valkey, Qdrant). Per request, cache: {"no-cache": true} skips the lookup, ttl sets the lifetime, and mode: default_off makes caching opt-in. SOURCE
The recording. Cache on (in-memory), the local model behind it, six calls with the same question. MEASURED
Seconds are what the caller waited (the first call also waited for the shared local model server). Cache key: the first 12 hex digits of the x-litellm-cache-key header, present only on hits.
Semantic caching, and why it is the risky one. A semantic cache embeds the prompt and returns a stored answer when a previous prompt is merely similar (cosine similarity above a threshold): LiteLLM's Redis, Valkey and Qdrant backends, Azure API Management's llm-semantic-cache-lookup and llm-semantic-cache-store policies (Microsoft Learn, read 24 Oct 2026). It is the only cache that can return a wrong answer: a hit is a bet that two different questions deserve the same reply, and the threshold trades money saved against wrong answers served. At a gateway three things make it worse: the cache is shared by every caller, so an entry must be scoped per tenant and user or one customer's answer reaches another; the reply is frozen, like any cache hit above; and nobody sees a false hit in an error counter. Use it last and narrowly, after measuring its false-hit rate on your traffic; Caching, section 12, measures that rate threshold by threshold on real labelled pairs.
A gateway accepts several request formats (OpenAI Chat Completions, OpenAI Responses, Anthropic Messages, Gemini generateContent) and sends each upstream in whatever format the provider speaks. The deployment's provider prefix decides the outgoing format, and the mapping is not always the obvious one.
The recording. One Anthropic-format request (POST /v1/messages, with a system prompt) for the local model, through two deployments that differ only in prefix; a logging proxy in front of the model server recorded what arrived. MEASURED
With openai/, LiteLLM assumed an upstream that speaks OpenAI's newer Responses API and sent POST /v1/responses (the system prompt became instructions, the message became input, and it asked for reasoning.encrypted_content); mlx-lm has no such route, so the caller got a 404 that names the model group, not the format. With lm_studio/ it sent ordinary /v1/chat/completions and the caller got a well-formed Anthropic reply. Other coding harnesses found the same with a Responses request (openai/ forwards /responses unchanged, lm_studio/ translates it), which is how it ran Codex, which speaks only the Responses API (wire_api = "chat" is now a config error), against the local model.
reasoning items, provider-specific parameters. LiteLLM drops unknown parameters when drop_params: true is set and raises otherwise. When something silently stops working behind a gateway, log the outgoing request body (the proxy's debug log, or a logging proxy like the one used here) before blaming the model.Provider API versions break gateways too: Anthropic's 2026-10-21 version rejects temperature, top_p and top_k, and its new SDKs send the key as Authorization: Bearer (Service APIs section 2 has the version change, and its section 7 compares the providers' API designs; the key's move between headers is on Auth section 1). A gateway that sets X-Api-Key or forwards sampling parameters to Claude must change: drop them for Claude on the new version (as drop_params does for unknown ones) or pin that route's anthropic-version to 2023-06-01.
OpenRouter is a hosted gateway: one OpenAI-compatible endpoint, one key and one bill in front of many model vendors and inference providers (its catalogue size and fees are in the dated table, section 11). It routes two ways. Across models: send a models list and it tries them in order on errors, rate limits and downtime, billing the model that answered (model fallbacks). Across providers of one model, the part with no LiteLLM equivalent: the same open-weights model is served by many companies at different prices, and by default OpenRouter will "Prioritize providers that have not seen significant outages in the last 30 seconds", then "For the stable providers, look at the lowest-cost candidates and select one weighted by inverse square of the price", then "Use the remaining providers as fallbacks" (provider routing). DOCS
Why it matters for an agent. "The same model" is not the same numbers. For Llama 3.3 70B Instruct, 11 endpoints ranged from $0.10 to $1.04 per million input tokens, declared their weights as fp8, bf16, fp16 or nothing, and offered contexts from 12,288 to 131,072 tokens; under the rule the two cheapest take about two thirds of first picks; gpt-oss-120b had up to 23 endpoints. An eval run through default routing mixes providers, and an agent's long prompt needs an endpoint whose context fits. Pin providers for evals (order with allow_fallbacks: false, or quantizations), and read the provider field each response carries. The provider object's other options: only, ignore, require_parameters, data_collection, zdr, sort (price, throughput or latency), preferred_min_throughput, preferred_max_latency; the suffixes :nitro and :floor mean sort by throughput and by price. LiteLLM can use OpenRouter as one more upstream (openrouter/ prefix), so the two compose: your own gateway for keys, budgets and logs, OpenRouter for reach.
Endpoint lists OpenRouter published for four open-weights models on 6 October 2026 (GET /api/v1/models/{author}/{slug}/endpoints, no key needed). The filters do what the provider options quantizations, a minimum context and max_price would. MEASURED (catalogue)
Sections 2 to 9 route between copies of the same model. Here the gateway picks which model: the cheapest that will answer well. Tier prices differ by a factor of 2 to 40 (dated table, section 11), so savings are large if most traffic is easy, but every misrouted hard question is a worse answer no error counter sees. So a router is measured as a classifier on labelled traffic: answer quality against the share of calls sent to the strong model, beside random routing at the same share (any router can trade cost for quality; a good one does it better than a coin).
Rules come first. Most production routers start as tier rules ("summaries go small") or a small classifier: Huyen describes "an intent classifier that predicts what the user is trying to do" so "simpler queries" go "to cheaper models" (Building A Generative AI Platform, 25 Jul 2024). Context rules send long prompts to pools configured for long context; getting one wrong is what happened in August 2025, when a routing bug sent some Claude Sonnet 4 requests to servers configured for a different context length, up to 16% of them in the worst hour, with normal error rates (Anthropic, 17 Sep 2025). Policy rules pin a tenant to a contracted vendor, keep data in a region, or send sensitive data only to self-hosted models.
| Approach | Decides from, and when | Example |
|---|---|---|
| Rules on the prompt | keywords, length, code markers, weighted into a score; before the call, in under a millisecond | LiteLLM complexity_router SOURCE |
| Classifier trained on preferences | which of two models people preferred on similar prompts; before the call | RouteLLM (Ong et al., 2024) PAPER |
| Cascade | the cheap model's own answer, judged by a scorer; after the cheap call, escalating if rejected | FrugalGPT (Chen, Zaharia and Zou, 2023) PAPER |
| Online learning | feedback on live traffic, a bandit per request type and model | LiteLLM adaptive_router SOURCE |
| Other people's spending | which models users pay for, per task type | OpenRouter Auto Router DOCS |
A router guesses difficulty from the prompt and adds no latency; a cascade sees the real answer but pays the cheap call, and its latency, on every hard request. The details, with weights, quotes and reported savings, are in the closed block below the experiment.
The experiment. 48 questions written for this page with exactly gradable answers, four families of 12: one-step facts, arithmetic word problems of 2 to 7 steps, "what does this Python print", and letter puzzles (count the r's in a made-up word, or write it backwards). Each was answered once by the local model on Apple M1 Pro (Qwen3 4B, temperature 0, up to 512 tokens) and once by Claude Haiku 4.5 (Claude Code CLI, no tools, the same instruction), each ending with an "ANSWER:" line; LiteLLM's complexity router then scored every question offline. Predict: will a keyword router send the letter puzzles up? Then move the threshold. MEASURED
total_cost_usd; the subscription paid).Vertical: questions right out of 48; horizontal: share sent to Haiku. Dashed: random routing (expected value); green: a perfect router; purple: every threshold of the complexity score, the dot at the one chosen. The default threshold sends the router's MEDIUM tier up.
Answers are the final "ANSWER:" line of each reply (click a row for the end of the full reply). A number is right if the first number in that line equals the answer; a word must match exactly. "no answer": the reply hit its 512-token allowance before an ANSWER line. Questions: src/code/r_tasks.py, seed 7.
| Approach | Decides from | Details |
|---|---|---|
| Rules on the prompt | keywords, length, code, "step by step" markers, weighted into a score with tier boundaries | LiteLLM's complexity_router: weights code 0.30, reasoning markers 0.25, technical terms 0.25, token count 0.10, simple indicators 0.05, multi-step 0.03, question complexity 0.02; tiers SIMPLE, MEDIUM, COMPLEX, REASONING at 0.15, 0.35, 0.60; "no external API calls and <1ms latency"; "Inspired by ClawRouter" SOURCE |
| A classifier trained on preferences | which of two models people preferred on similar prompts; decides before any call | RouteLLM (Ong et al., 2024): routers "leveraging human preference data and data augmentation", which the abstract says reduce costs "by over 2 times in certain cases" without compromising response quality; matrix factorisation ("recommended"), similarity-weighted Elo, a BERT classifier and an LLM classifier, with the threshold calibrated to a target share of strong calls (repo) PAPER |
| A cascade | the cheap model's answer itself, judged by a scorer; decides after the cheap call | FrugalGPT (Chen, Zaharia and Zou, May 2023): query models in order of cost, stop when a learned scorer accepts the answer; the abstract reports matching "the best individual LLM (e.g. GPT-4)" "with up to 98% cost reduction" on its tasks. A cascade pays the cheap call on every hard request and adds its latency, in exchange for seeing the actual answer rather than guessing from the prompt. PAPER |
| Online learning | feedback signals on live traffic | LiteLLM's adaptive_router (v0): seven request types, a Beta-distribution bandit per (type, model) sampled per request, scored as quality weight times sample plus cost weight times normalised cost; updates flushed to Postgres about every 10 s SOURCE |
| Other people's spending | which models users pay for, per task type | OpenRouter's Auto Router (openrouter/auto): "Powered by the market: the aggregate spend of millions of people using OpenRouter, measured over a trailing 7-day window for each task type", about 30 task types, "no additional fee"; allowed_models, excluded_models, cost_tier restrict it (Auto Router, read 6 Oct 2026) DOCS |
Sakana Fugu is "a Multi-Agent System, Delivered as One Model" behind an OpenAI-compatible API, built on the TRINITY ("a lightweight evolved coordinator ... assigning Thinker, Worker, or Verifier roles") and Conductor ("trained with reinforcement learning") papers (Sakana, read 6 Oct 2026; prices in the dated table). Not a router in front of models but a system behind one model name: it takes the orchestration away from you. DOCS
Every gateway does the duties of section 1; they differ in where they run, who holds the provider keys and the bill, and what they add. Read from each project's own documentation on the dates shown; Kong AI Gateway is another option, not checked here. DOCS
| Tool | Design | What it adds or lacks |
|---|---|---|
| LiteLLM (this page's recordings) | Open-source Python: an in-process Router and a self-hosted proxy with Postgres for keys and spend, Redis for shared counters | Virtual keys, nested budgets with reservation, rate limits, cooldowns, fallbacks by error type, many provider prefixes, response and semantic caches; every rule in sections 2 to 8 is its source at 1.104.0 |
| OpenRouter | Hosted, rented: one key and one bill, OpenRouter holds the provider relationships | A market of providers per model with price-weighted provider routing (section 9), model fallbacks, Auto Router; no self-hosting; your data passes through a third party (the data_collection and zdr options restrict which providers see it) |
| Portkey gateway | Open source (MIT), runs on Node.js (npx @portkey-ai/gateway), Docker or Cloudflare Workers, or Portkey's hosted cloud | Fallbacks, retries ("up to 5 times"), weighted load balancing across keys or providers, response caching, guardrail checks on inputs and outputs; claims "<1ms latency" and a 122 kb footprint (README, read 24 Oct 2026; vendor figures, not measured here) |
| Envoy AI Gateway (now Agent Router) | Built on Envoy proxy, configured as Kubernetes resources; two tiers (a front gateway for authentication, top-level routing and global rate limits; a second in front of self-hosted models) | Token-based rate limiting charged after the response (section 5), QuotaPolicy for cumulative spend; the network-proxy view of a gateway |
| Cloud gateways: Azure API Management AI gateway, Cloudflare AI Gateway | A feature of an existing managed API or edge platform, not a separate service | Azure: llm-token-limit (TPM or a token quota per counter key, with prompt tokens estimated before the call), semantic caching, round-robin, weighted, priority and session-aware load balancing, a circuit breaker that honours Retry-After, token metrics (Microsoft Learn). Cloudflare: analytics, logging, caching, rate limiting, "request retry and model fallbacks" (docs). Both read 24 Oct 2026. |
Choosing: self-host (LiteLLM, Portkey, Envoy) when the provider keys, the logs and the budget rules must stay yours; rent (OpenRouter) for reach across open-weights providers without contracts; use the cloud gateway when the models already live in that cloud and its API platform already fronts your services. The layers compose: LiteLLM in front, OpenRouter as one upstream.
| Fact | Value | Source, date |
|---|---|---|
| Tier prices, $ per million input / output tokens | Claude 4.5 Haiku $1 / $5; Sonnet 5.5 $2 / $10; Opus 5.5 $4 / $20; GPT-6 Luna $0.10 / $0.50 | the knowledge base's price snapshot, 2026-10-01 |
| OpenRouter catalogue | models from model authors, of them free variants | GET /api/v1/models, 6 Oct 2026 |
| OpenRouter fees | "no markup on inference pricing"; buying credits 5.5% ($0.80 minimum) by card, 5% in crypto; BYOK: "Pay-as-you-go includes $25,000 per month with no BYOK fee", 5% above; free models 50 requests a day, 1,000 after buying $10 of credits | FAQ, 6 Oct 2026 |
| Sakana Fugu | Fugu Ultra $5 / $30, Fugu Max $2 / $6 per million input / output tokens | Sakana, 6 Oct 2026 |
| Portkey reach | "1,600+ LLMs", "45+ providers" (the README also says 250+ and 200+ in other places) | README, 24 Oct 2026 |
| LiteLLM versions | 1.104.0 recorded here (uploaded 3 Oct 2026); its price table stops at Claude Sonnet 4.5; since 1.106.0 (18 Oct 2026) stdio MCP servers are disabled by default; 1.107.0 (21 Oct 2026) on PyPI and the matching Docker tags were malicious (clean: 1.106.2), and the image-signing key was rotated on 24 Oct, so verification against the old key fails | PyPI; releases |
| Envoy AI Gateway | renamed Agent Router, v1.1.0 (21 Aug 2026) | GitHub |
The old notes on the parent page say you run LiteLLM at work and have hand-built a DAG engine over model calls; nothing else about that setup is known here.
| Check | Why | How to see it |
|---|---|---|
| Which layer retries | SDK, gateway and engine retries multiply (section 4) | Set max_retries=0 in the SDK client that talks to the gateway; count upstream calls per request in the spend logs |
| Timeouts per deployment | The default request timeout is 6,000 s; a hung provider holds a worker that long | timeout (and stream_timeout) in each deployment's litellm_params, shorter than the client's |
allowed_fails | 3 is the default and is treated as unset (section 3) | Use 2, or allowed_fails_policy per error type |
| Single-deployment groups | Never cooled down: every request pays the full retry chain before falling back | Give important groups a second deployment, or lower num_retries for them |
| Prices for cost routing | Read from litellm_params only (section 2) | Send 20 requests, count x-litellm-model-id |
max_tokens on every call | Budget reservation assumes 16,384 output tokens without it (section 6) | Look for 422 budget_exceeded while spend is far below the cap |
| Redis for more than one replica | Without it, rate limits, cooldowns and budget counters are per process | router_settings.redis_host |
| Fallbacks evaluated | A fallback model nobody evaluated degrades answers silently | Run the eval set against every model in each fallback chain; tag traces with the model that answered |
| Response cache for agents | Exact keys rarely hit in agent loops and freeze sampled answers (section 7) | mode: default_off, opt in per call type |
| Pinned, verified release | The gateway holds every provider key; 1.107.0 was a signed, malicious release (section 1) | Pin an exact version or image digest you checked; verify with the current signing key; keep a key-rotation runbook; leave body logging off |
| Claude API version | 2026-10-21 rejects temperature, top_p, top_k and new SDKs send Authorization: Bearer (section 8) | Send one request per Claude deployment with the new SDK; check which header and parameters reach the provider |
| Provider prefix | Decides the wire format sent upstream (section 8) | Debug-log one outgoing request per deployment |
| MCP servers behind the gateway | Since 1.106.0 LiteLLM disables stdio MCP servers (the ones it would start as local processes) by default; a config that listed them stops serving their tools after the upgrade | List the gateway's MCP tools after upgrading; prefer HTTP MCP servers, and turn stdio back on only deliberately, since it lets the gateway run commands on its host |
A hand-built DAG engine already does the workflow half of what LangGraph would (the parent page's section 10; LangChain and LangGraph in depth). Behind a gateway it should keep one job for itself: each node's deadline, passed down as the gateway call's timeout, so a slow branch fails fast instead of waiting through the gateway's whole retry chain. Retries belong in one place; with a gateway in front, that place is usually the gateway.
Traces from the gateway. LLM observability (its section 4) found that LiteLLM's langfuse_otel callback sends a GenAI span per request, with usage and cost, and that LiteLLM now recommends it over the older langfuse callback; gateway spans see every request but not the agent around it, so join them with the app's spans on the trace id.
Sources are linked where each fact is used: LiteLLM 1.104.0's source (PyPI wheel, uploaded 3 October 2026; files named inline), LiteLLM's docs and GitHub issues, OpenRouter's docs and public catalogue API, Anthropic's rate-limit docs, the OpenAI (2.54.0) and Anthropic (1.11.0) Python SDKs' constants, the RouteLLM paper and repository, and Sakana's Fugu page, all read on 6 October 2026; the FrugalGPT paper and the Portkey, Azure API Management and Cloudflare AI Gateway documentation, read on 24 October 2026. Recordings, 6 October 2026, one Apple M1 Pro: litellm.Router runs (routing, failures) and a LiteLLM proxy with Postgres 16 (amplification, rate limits, budgets, cache, translation) in front of fake providers written for this page and the local model mlx-community/Qwen3-4B-Instruct-2507-4bit (mlx-lm 0.32.0); 48 Claude Haiku 4.5 answers through Claude Code 2.1.291 on a subscription (costs are its API-price estimates). Redacted recordings, the scripts that made them and recompute.py, which re-derives every number quoted, are in this page's src/.
The recorded replays that used to be lab tabs are now beside their sections: the forty requests per strategy (section 2), every failed attempt (end of section 4), four rate limiters on the same traffic (section 5), every budget call (section 6), OpenRouter endpoints with filters (section 9), and the 48-question router experiment (section 10).
Why a gateway at all (Reading section 6), and the Production stack tab: a LiteLLM proxy retrying and falling back on a failing provider, keys, a hundred-request simulator, then tracing, an eval gate and hosted runtimes around the same loop. Reading 24 min, plus 2 closed; labs 18 to 21 min each.
Traces, OpenTelemetry GenAI conventions, Langfuse: where the gateway's spend logs and the deployment that answered should end up; its section 4 covers LiteLLM's langfuse_otel callback. 30 min
Pydantic AI, the OpenAI Agents SDK (which reaches non-OpenAI models through LiteLLM), smolagents, Google ADK (which needs LiteLLM for non-Gemini models). 28 min
The Claude Code loop as a library; its cost accounting is the per-run view of what a gateway counts per key. 29 min
Node-level retry policies and durable execution: the other place retries can live. 34 min
Many agents in parallel: the traffic shape that meets budgets and rate limits first. 32 min
Codex through a LiteLLM gateway to a local model, and Gemini CLI's retries overlapping on a slow server. 30 min
Provider prompt caching (prices, TTLs, breakpoints): the cache this page's section 7 is not; and, in its section 8, memory layers (Mem0, Graphiti, Letta), whose writes are extra model calls through the gateway like any other. 35 min
Timeouts, retries with backoff and jitter, retry budgets, circuit breakers, a measured retry storm, and the five rate-limiting algorithms animated on one burst. 33 min
Proxies and timeouts for LLM APIs: which hop's timeout ends a long generation, and when a retry is safe. 45 min
Load balancing at layer 4 and 7 and in the client, measured in its section 13. 52 min
Every cache layer, and semantic caching measured threshold by threshold in section 12: how often a similar-enough answer is wrong. 43 min
API keys and their storage, OAuth, what a virtual key is standing in for. 42 min
A rate limiter designed end to end (token bucket per key in Redis), interview style. 41 min
The gateway inside a whole LLM service: tenancy and isolation, realtime, streaming and batch paths, rollouts, degradation ladders, and a cost-against-quality design lab. 23 min
Below the gateway: which replica gets the request (prefix-aware routing, measured), autoscaling on queue depth, cold starts. 34 min
The servers behind the providers. 34 min
Strategies, retries, cooldowns, fallbacks, as documented; check against section 2 and 3. 25 min
Fallback types, timeouts, retry policies in the proxy config. 15 min
The hierarchy, durations, budget reservation and how to switch it off. 20 min
router.py, router_strategy/, router_utils/cooldown_handlers.py, proxy/hooks/parallel_request_limiter_v3.py, proxy/spend_tracking/budget_reservation.py. 1 h or more
The default rule and every provider option. 15 min
Fees, BYOK, free-model limits. 10 min
Token bucket, cache-aware ITPM, headers, spend caps. 15 min
Routers trained on preference data, evaluated as quality against strong-model share. 45 min
A multi-model system sold as one model name. 10 min
Prompt adaptation, model approximation and the LLM cascade: query cheap models first and stop when a scorer accepts. 40 min
Two other gateway designs: a small open-source Node.js gateway, and gateway policies inside a cloud API platform. 20 min