Gateways and routing: LiteLLM, OpenRouter, fallbacks, budgets, rate limits

What a gateway does to one model call, read from LiteLLM 1.104.0's source and recorded request by request against scripted fake providers and a local model (6 October 2026); OpenRouter from its live catalogue the same day. Child of Topic: agentic-frameworks. Data as of October 2026. Reading: 37 min, plus 17 in closed details.

The idea in one screen

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.

  1. Authenticate. The proxy hashes the caller's virtual key and finds its row (cached in memory after the first lookup): models allowed, budget, limits. Provider keys never leave the gateway.
  2. Reserve the budget. It estimates the most this call could cost (input tokens plus max_tokens, or 16,384 output tokens if none) and reserves that against every budget the key sits under (section 6).
  3. Rate limit. It adds 1 to the key's request counter for the current 60-second window and refuses with 429 if that passes rpm_limit (section 5).
  4. Route. The router picks one deployment of the group with the routing strategy, skipping any that are cooling down (section 2).
  5. Cache lookup. Inside the call to that deployment, LiteLLM hashes the request (model group, messages, temperature ...) and looks it up: no stored answer.
  6. Call. It translates the request into the deployment's format (section 8) and sends it with that deployment's timeout. Recorded: the local model answered in 1.1 to 3.6 s.
  7. Settle and log. The real cost replaces the reservation, the answer is stored in the cache, and a spend log row is written (in batches): one usage event per call.

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.

What is real on this page, and the labels (provenance)
A real LiteLLM 1.104.0 (the latest on PyPI on 6 October 2026, uploaded 3 October) on one laptop, with Postgres 16 in Docker for its keys; small fake providers written for this page (an OpenAI-shaped server that answers, fails with a chosen status, or hangs, on a script); a local model on Apple M1 Pro (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.

1. One request through the gateway

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.

Gateways in production: Uber, Envoy AI Gateway, Huyen's platform (provenance, 2 min)

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

2. Choosing a deployment: what each strategy really measures

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

  1. 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.
  2. simple-shuffle, weight A 3 : B 1. The same coin, loaded: 29 to A, 11 to B, 4.9 s.
  3. 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.
  4. 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.
  5. 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.
  6. 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.
  7. The same prices in 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.
Check what your strategy reads
A strategy that cannot find its input does not fail; it falls back to random or to the first deployment. After changing a routing setting, send a few dozen requests and count which deployment answered (the proxy returns it in the x-litellm-model-id response header).
Replay the forty requests per strategy on a time axis (widget)

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.

3. When a call fails: retry, cool down, or fall back

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 answerRetried in the group?Can cool the deployment down?Goes to fallbacks?
429 rate limitedyesyes, at once, if the group has another deploymentyes
500, 502, 503 and any 5xxyesyes, once more than half of this minute's calls to it failed and it had at least 5yes
408 timeout, 409yes408 yes, 409 noyes
401, 403 bad credentialsonly if the group has another deployment401 yesyes
400 context window exceedednonoyes: to context_window_fallbacks if set, else to the regular fallbacks
400 content policynonoyes: to content_policy_fallbacks if set, else regular
other 400s, 404no404 yesregular 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

  • 429: C was benched after its first 429 and came back every 5 to 6 seconds (calls at 0.1, 5.7, 11.8 and 17.8 s). Users never saw an error.
  • 503, default settings: C was picked about one time in three until its fifth failure in the minute (at 7.3 s), then benched until 14.7 s; after that each new failure benched it again.
  • 503, 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.
  • One deployment in the group: never cooled down (the "single-deployment model group" exemption: benching the only copy would turn a partial outage into a total one), so every request paid two backoff waits and then fell back: about 5.5 s per request, every time.
Two more recorded cases: allowed_fails 1, and a context-window error (depth)
  • 503, allowed_fails: 1: benched after its second failure, back 5 s later.
  • Context window error: never retried; with no fallbacks the user got ContextWindowExceededError in 0.1 s; with either fallbacks or context_window_fallbacks the request went straight to the long-context group.
Predict, then open. A group has two deployments and the bad one returns 500 on every call. You set allowed_fails: 3 and cooldown_time: 60, expecting it to be benched after three failures for a minute. What happens?
It is benched only after more than half of its calls in the current minute failed and there were at least five (the default regime), and the bench lasts 60 s because 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.
A 429 benches C at once; a 503 keeps being tried until five failures; allowed_fails 3 behaves like the default

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.

4. Timeouts and retries across layers

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:

attempts reaching the provider = (1 + r1) × (1 + r2) × … × (1 + rn)
ri
retries at layer i (OpenAI and Anthropic Python SDKs: 2 by default, with a 600-second timeout; LiteLLM: 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

  1. One send, three gateway attempts. The SDK sends at 1.4 s with a 10-second timeout. The gateway gives each provider attempt 5 s, then backs off and tries again: calls at 1.6, 7.8 and 13.9 s, each of which the provider works on for its full 30 s (it cannot tell the caller gave up until it writes the answer).
  2. The SDK times out and sends again. At 11.8 s the SDK's timeout fires and its first retry starts a second gateway chain: three more calls (12.0, 18.1, 24.3 s), while the first chain is still running.
  3. The second SDK retry: nine calls. At 22.7 s the SDK's last retry starts a third chain (24.4, 30.4, 36.9 s): 3 × 3 = 9, the formula with r1 = r2 = 2.
  4. The user hears; the provider keeps working. SDK defaults with a 10-second timeout: the user got 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.
  5. One layer retries. The same with 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).
  6. Outer timeout longer than the inner chain. SDK timeout 60 s: the gateway's own chain finished first (about 20 s), returned 408, and the SDK retried it, twice: 9 calls, error after 61.9 s.

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

The rule
Retry at one layer only, the one that knows the most (usually the gateway, which can switch deployments); set the others to 0. Give each layer a timeout shorter than the layer above it, so the inner one gives up first and reports why. A request retried 9 times is a capacity problem, not bad luck. Retry budgets and retry storms are measured on Reliability engineering (its section 14 counts the SDK's own retries, "twice by default", inside yours); which hop's timeout ends a long generation is on HTTP, section 9.
Replay every recorded attempt of sections 3 and 4, event by event (widget, 11 cases)

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.

Router cases (litellm.Router, two deployments A and C, num_retries 2)
Retry layers (OpenAI SDK, LiteLLM proxy, provider hanging 30 s)
request (caller waiting)answerederrorprovider working on a callprovider busy on a call nobody will read

Every request of this case

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).

5. Rate limits: three places, three algorithms

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:

WhereCounted inAlgorithmAnswer 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" DOCS429 with retry-after
Gateway (LiteLLM, per key, user, team, model)rpm_limit, tpm_limit, max_parallel_requestsa counter per window of 60 s (LITELLM_RATE_LIMIT_WINDOW_SIZE) that starts at the first request and resets whole SOURCE429 throttling_error, retry-after: 60 MEASURED
Router (LiteLLM, per deployment)rpm/tpm on a deploymentcounts per calendar minute; a deployment over its limit is skippedthe 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

  1. One request opens the window. At second 0 the burst key sends one request; every limiter accepts it. LiteLLM's window now starts at second 0, the calendar minute is 0 to 60, the sliding log holds one entry and the token bucket (holding 10, refilled at 10 per 60 s) has 9 left.
  2. Nine more in four seconds. Seconds 50 to 54: all four accept all nine. Both fixed windows and the log now hold 10 of 10; the bucket, full again after the quiet 50 seconds, is drained to 1.7.
  3. Second 60: the windows roll over. LiteLLM's window (60 whole seconds since its first request) and the calendar minute both reset to zero and accept the request at 60.5 s. The log accepts it too, because the request of second 0 has just aged out; the bucket has refilled to 2.75.
  4. Nine more: the fixed windows take them all. Seconds 61 to 65: both fixed windows accept every request (19 since second 50); the log refuses all nine (its ten entries from seconds 50 to 54 stay until 110 s); the bucket accepts two more as tokens trickle back, one every 6 s.
  5. Then 429s everywhere. Seconds 66 and 67: every limiter refuses. LiteLLM answers 429 throttling_error with retry-after: 60.
  6. Count any 15 seconds. The piles are the requests each limiter accepted from second 50 to 65: 19 and 19 for the fixed windows, 10 for the sliding log, 12 for the token bucket. Rejected requests use no capacity in any of them.

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.

Several gateway replicas
Without Redis each LiteLLM process keeps its own counters, so three replicas behind a load balancer admit three times the limit. With 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
The three admission answers in their own words, cache-aware input limits, and Envoy's per-tenant policy (depth, 2 min)

(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}}
The same arrivals through four limiters: both fixed windows let 19 through in 15 seconds, a sliding log 10, a token bucket 12

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.

6. Budgets and virtual keys: what a dollar cap really does

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

  1. 20 calls arrive together. Budget $0.0004; each call really costs $0.00008, so 5 fit. No call sets max_tokens.
  2. Reserve the worst case. The first call reserves its worst case, about $0.082 (16,384 output tokens at $5 per million), far more than the whole budget, so the reservation is shrunk to the whole $0.0004; the other 19 find nothing left and get HTTP 422: 1 accepted, 19 refused in about 0.4 s.
  3. Wave 1 settles (2 s later). The reservation is replaced by the real cost, $0.00008.
  4. Wave 2, 4 s after wave 1. Budget left: $0.00032. Again one call takes all of it: a second wave 4 s later, again 1. The key has become a queue of one.
  5. Final spend. Recorded final spend $0.00016 against a $0.0004 budget: never over, and three fifths of it never spent.

Ten calls one after another: exactly 5 accepted, final spend $0.0004, then 422s.

Correction to the parent page (now applied there)
The parent's Production stack tab recorded a sequential overshoot of one call ($0.0008 cap, three calls of $0.00033, final $0.00099) and first concluded that a key "can overshoot its cap by the calls in flight", with batched spend writes "widening the overshoot under parallel traffic". On 1.104.0, the version both pages ran, the sequential overshoot reproduces (the last call gets whatever budget remains and can cost more); parallel calls do not overshoot. LiteLLM's docs: "Budget reservation is enabled by default", and switching it off "can allow concurrent requests to exceed a configured budget" (docs); known gaps are requests whose cost cannot be estimated, which skip it (issue 35524), and project budgets (issue 34101). MEASURED SOURCE
What follows for agents
Send 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).

Every call of the four budget runs, and the refusal messages (widget)

The refusal messages, verbatim (key hashes removed)

The in-run spend reads can precede LiteLLM's batched spend write, so final spends were read back from /key/list after all runs.

7. Caching at the gateway: a memo of whole answers

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

  • Hit: 0.08 s instead of seconds, no tokens spent.
  • Temperature 0.9: a miss (temperature is part of the key), then a hit that returned the sampled answer word for word. The cache turns a random answer into a fixed one for the TTL; for an agent that retries a step hoping for a different action, that is the opposite of what it wants.
  • One extra space: a miss. Each agent turn appends the last tool result, so an agent's calls almost never hit an exact cache. The gateway cache pays for repeated identical calls (classification, embedding, evals re-run on unchanged items), not for agent loops.
A hit returns a sampled answer word for word; one extra space misses

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.

8. The translation layer: what actually leaves the gateway

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.

The same request, two prefixes: openai/ sends the Responses API, lm_studio/ sends Chat Completions
What translation can lose
Anything one format has and the other does not: Anthropic cache breakpoints, thinking blocks and their signatures, server tools, OpenAI's 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.

9. OpenRouter: a gateway you rent, and a market of providers

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

P(provider i first) = (1 / pi2) / Σj (1 / pj2)
pi
provider i's price. The docs' example: at $1, $2 and $3 per million tokens, the $1 provider is 9 times likelier than the $3 one. They do not say which price (input or output) nor how many "lowest-cost candidates" are kept; the shares below use the input price over every listed endpoint, so they illustrate the rule, not OpenRouter's exact numbers.

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.

One model name, many endpoints: price, precision and context all differ

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)

10. Routing by difficulty: routers and cascades

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.

ApproachDecides from, and whenExample
Rules on the promptkeywords, length, code markers, weighted into a score; before the call, in under a millisecondLiteLLM complexity_router SOURCE
Classifier trained on preferenceswhich of two models people preferred on similar prompts; before the callRouteLLM (Ong et al., 2024) PAPER
Cascadethe cheap model's own answer, judged by a scorer; after the cheap call, escalating if rejectedFrugalGPT (Chen, Zaharia and Zou, 2023) PAPER
Online learningfeedback on live traffic, a bandit per request type and modelLiteLLM adaptive_router SOURCE
Other people's spendingwhich models users pay for, per task typeOpenRouter 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

  • The two models: local 38 of 48, Haiku 44 of 48. Both got every fact and every arithmetic problem; the local model missed 4 code questions and 6 letter puzzles (8 of its 10 misses ran out of its 512-token allowance without an ANSWER line); Haiku missed 4 backwards-spelling puzzles. Haiku's 48 answers cost $0.19 at API list prices (the CLI's total_cost_usd; the subscription paid).
  • The complexity router scored all 12 code questions MEDIUM (they contain code) and all 36 others SIMPLE. Sending MEDIUM up: 42 right with 25% of calls to Haiku. Random routing at 25% would expect 39.5; a perfect router needs only 6 strong calls (12.5%) for 44. RouteLLM's metric, the share of the quality gap recovered, is (42 − 38) / (44 − 38) = 0.67.
  • Why it worked, and where it did not: the families the small model failed happened to differ in surface features (code), so a keyword rule found half of them. It sent none of the letter puzzles, which look simple and are hard for a small model because it sees tokens, not letters. A router's features must predict your cheap model's failures on your traffic; that is what training on preference data, or on your own graded logs, buys over keywords.
What this experiment is not
A small invented question set, one run per model: it shows how to evaluate a router, not how good routers are. Grading is lenient on units ("2500 grams" counts for 2500); Haiku's raw grade before that was 39 of 48.
The keyword router recovers two thirds of the gap, because it spots code, not difficulty

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.

The 48 questions, both answers and each score (table, uses the threshold above)

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.

The five approaches in detail: weights, quotes, reported savings (depth, 2 min)
ApproachDecides fromDetails
Rules on the promptkeywords, length, code, "step by step" markers, weighted into a score with tier boundariesLiteLLM'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 preferenceswhich of two models people preferred on similar prompts; decides before any callRouteLLM (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 cascadethe cheap model's answer itself, judged by a scorer; decides after the cheap callFrugalGPT (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 learningfeedback signals on live trafficLiteLLM'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 spendingwhich models users pay for, per task typeOpenRouter'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
A trained orchestrator sold as one model: Sakana Fugu (depth)

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

11. The tools, compared by design

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

ToolDesignWhat 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 countersVirtual 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
OpenRouterHosted, rented: one key and one bill, OpenRouter holds the provider relationshipsA 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 gatewayOpen source (MIT), runs on Node.js (npx @portkey-ai/gateway), Docker or Cloudflare Workers, or Portkey's hosted cloudFallbacks, 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 GatewayA feature of an existing managed API or edge platform, not a separate serviceAzure: 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.

Volatile facts, dated: prices, fees, rosters and versions (one table)
FactValueSource, date
Tier prices, $ per million input / output tokensClaude 4.5 Haiku $1 / $5; Sonnet 5.5 $2 / $10; Opus 5.5 $4 / $20; GPT-6 Luna $0.10 / $0.50the knowledge base's price snapshot, 2026-10-01
OpenRouter catalogue models from model authors, of them free variantsGET /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 creditsFAQ, 6 Oct 2026
Sakana FuguFugu Ultra $5 / $30, Fugu Max $2 / $6 per million input / output tokensSakana, 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 versions1.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 failsPyPI; releases
Envoy AI Gatewayrenamed Agent Router, v1.1.0 (21 Aug 2026)GitHub

Depth: a checklist for your own setup, and interview rehearsal

Checklist for a LiteLLM deployment at work (each row: what this page found, and how to see it)

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.

CheckWhyHow to see it
Which layer retriesSDK, 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 deploymentThe default request timeout is 6,000 s; a hung provider holds a worker that longtimeout (and stream_timeout) in each deployment's litellm_params, shorter than the client's
allowed_fails3 is the default and is treated as unset (section 3)Use 2, or allowed_fails_policy per error type
Single-deployment groupsNever cooled down: every request pays the full retry chain before falling backGive important groups a second deployment, or lower num_retries for them
Prices for cost routingRead from litellm_params only (section 2)Send 20 requests, count x-litellm-model-id
max_tokens on every callBudget 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 replicaWithout it, rate limits, cooldowns and budget counters are per processrouter_settings.redis_host
Fallbacks evaluatedA fallback model nobody evaluated degrades answers silentlyRun the eval set against every model in each fallback chain; tag traces with the model that answered
Response cache for agentsExact keys rarely hit in agent loops and freeze sampled answers (section 7)mode: default_off, opt in per call type
Pinned, verified releaseThe 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 version2026-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 prefixDecides the wire format sent upstream (section 8)Debug-log one outgoing request per deployment
MCP servers behind the gatewaySince 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 upgradeList 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.

Interview rehearsal: design angles (optional)
Design the gateway for 50 internal teams calling three providers. What goes in it?
Virtual keys per team with budgets and rate limits; model groups with several deployments each (regions, providers) and per-deployment timeouts; one retry layer with backoff and a retry budget; cooldowns for broken deployments; fallbacks across model families that were each evaluated; Redis for shared counters across replicas; spend logs and traces tagged with team, model group and the deployment that answered; caching off by default.
A client has a 10 s timeout and 2 retries; the gateway has 5 s per attempt and 2 retries; the provider hangs. How many provider calls, and when does the user hear?
Up to 3 × 3 = 9 calls (measured: 9, the last starting after the user's error at 32.8 s). Fix: one retry layer, inner timeouts shorter than outer ones, and cancellation propagated when the client goes away.
How would you enforce a dollar budget under concurrency?
Reserve the worst-case cost of each request atomically before calling (input tokens plus max output tokens at list price), settle to the real cost afterwards, and refuse when the reservation does not fit. Cap the reservation per request so a missing max_tokens does not serialise the caller. This is what LiteLLM 1.104.0 does.
Fixed window, sliding window or token bucket for an LLM API?
Token bucket (what Anthropic uses): it allows a burst up to the bucket size and then a steady rate, with no boundary double burst. Count tokens, not only requests, and reserve output tokens at admission because they are unknown until the end.
Router or cascade?
A router decides from the prompt before any call: no extra latency, but it must predict difficulty. A cascade calls the cheap model first and escalates when a scorer rejects the answer: it sees the real answer but pays the cheap call and its latency on every hard request. Either is judged by quality against the strong-call share, beside random routing at the same share.

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/.