Model Gateway Routing, Quotas, and Failover
Consider a hypothetical company where three applications call language models directly. Each holds its own provider key in its configuration, and each handles provider errors in its own way. One afternoon a provider starts returning overload errors. The search application retries immediately in a loop, which makes the overload worse for everyone sharing that provider account. The reporting application has no retry at all and drops jobs. A nightly batch job, started before the incident, spends most of the month’s token allowance by the time anyone notices, and nobody can say which application used how much. The team then switches the search application to a second provider by editing its code, and over the next week reviewers notice that answers read differently, because the second provider’s model follows the prompt differently. Each of these problems is local to one application, yet all of them are the same missing piece: nothing sits between the applications and the providers.
A model gateway is that piece. It is a service that every application calls instead of calling providers directly, and it applies the same policy to all of them: who is calling, which model they may use, how much they may use, which provider serves the request, and what happens when that provider fails. This article explains each of those functions and why it is built the way it is, then implements them in a small gateway that talks to two fake providers and prints what it does. By the end you should be able to describe what a gateway should authenticate and record, design model aliases and routing rules, choose between request, token, concurrency, and budget limits, explain which differences between providers an adapter can hide and which it cannot, and decide when failover is safe.
The gateway and providers in this article are written for it in Python’s standard library and run on one machine. They show control flow and accounting under stated assumptions. The prices are made-up credits, the providers’ wire formats are simplified imitations of two common API styles, and nothing here calls a real service. Real products appear in the sections on tools, described from their documentation.
What this article builds on
Model Serving: Batching, Autoscaling, and Tail Latency explains why a service with finite capacity needs a bounded queue and an explicit overload response, and why clients that retry without backoff turn a short overload into a long one. A gateway protects the serving capacity sized there, so this article assumes those results: waiting time grows sharply near capacity, rejecting early is better than queueing without limit, and a 429 or 503 response should say whether and when to retry. General knowledge of HTTP APIs and authentication is assumed. No provider-specific knowledge is needed.
What a gateway is for
Like an API gateway, a model gateway gives a platform one place to put cross-cutting policy. Its position matters more than any single feature: because every call passes through it, the platform can enforce rules that individual applications cannot enforce on themselves, such as a shared budget for a team or a consistent response to provider failure. Its functions fall into six groups.
- Authenticate the caller and attribute every request to an application and a team.
- Authorize which model aliases that caller may use.
- Limit usage: requests, tokens, concurrency, and spend.
- Route the request to a provider or deployment, with a defined fallback order.
- Translate between the gateway’s request format and each provider’s.
- Record what happened, including which model actually answered.
The gateway does not make a model good, and it does not decide whether a model is safe to use for a task. That is the work of evaluation, covered in the next article of this module. It also adds costs of its own. Every request gains a network hop and some processing time, and the gateway becomes a dependency of every application, so its availability is capped by its own design. A gateway that is a single instance with local state turns a provider outage into a platform outage. The last section returns to this.
The request path through the gateway built below looks like this.
client app
| key or token
v
authenticate -> authorize alias -> budget check -> rate limits (requests, tokens)
-> choose candidates (weights, cooldown, region, context window)
-> adapter: gateway format -> provider format -> provider A or B
<- adapter: provider format -> gateway format, with token usage
-> charge budget, reconcile token reservation, write audit record
v
response with x-served-by and x-fallback headers
Authentication and caller identity
Everything else in a gateway depends on knowing who is calling. The identity has to be useful for three jobs: deciding what the caller may do, charging usage to someone, and finding the responsible team when something goes wrong. A single shared key serves none of them, since all usage looks the same and a leaked key cannot be revoked without breaking every application.
The common design is one credential per application, mapped by the gateway to a record that names the application, the owning team, the aliases it may use, and its limits. A key is a bearer credential, so whoever holds it is the caller. Keys should be random and long, shown once at creation, and stored by the gateway only as a hash. Because a random key has high entropy, a fast hash such as SHA-256 is adequate for this lookup; the slow hashes used for human passwords exist to resist guessing, which does not apply here. The gateway in this article stores the SHA-256 of each key and nothing else.
A second kind of credential is a signed token from an identity provider, typically an OpenID Connect JSON Web Token (JWT). The gateway validates the signature against the provider’s published public keys and reads the caller’s identity and group claims from it, so no long-lived secret is distributed to applications. Both open-source gateways discussed below support this in some form. Envoy Gateway documents JWT validation from an Authorization: Bearer header through its SecurityPolicy resource. LiteLLM documents OIDC and JWT-based authentication, and its documentation marks that feature as part of its enterprise offering, which is an example of how a feature that looks standard can sit behind a license.
Two further points apply to either credential. First, the gateway should hold the provider credentials, and applications should never see them. Envoy AI Gateway’s documentation describes this as upstream authentication: a separate layer between the gateway and each provider that keeps credentials in one place, which makes rotation and revocation a single change. Second, authorization is a separate check from authentication. A valid key proves who is calling and nothing about what they may do. The gateway checks the requested alias against the caller’s allowed list on every request, which is least privilege applied to model access: the batch application in the demo below can use the default alias and is refused the premium one.
Routing: aliases, weights, and fallback order
Applications should not name providers. They name an alias, such as chat-default, and the gateway maps the alias to one or more targets: a provider, a provider-specific model name, and a weight or priority. The indirection makes four things possible without changing any application. The platform can move an alias to a new model version after it passes evaluation. It can split traffic between two deployments, for example 80/20 during a gradual change. It can add a second provider for resilience. And it can record which concrete model served each call. The cost is that the alias hides which model answers, so the gateway must expose that fact on every response and record it, a point the audit section returns to. Versioning Models, Data, Prompts, and Evaluation Artifacts covers why a mutable name must resolve to an exact, recorded version.
Both documented tools express this directly. LiteLLM groups deployments under one model_name and supports weighted selection, order-based priority tiers, and routing strategies such as latency-based and rate-limit-aware. Envoy AI Gateway lists prioritized backendRefs on an AIGatewayRoute, where the first is primary and later ones are fallbacks, matched on the model name in the request.
The gateway below selects targets by weighted random order: the first element of the order is the preferred target, and the rest form the fallback sequence. Candidates are then filtered by conditions that are properties of the request and caller, not preferences: whether the provider is in cooldown after failures, whether the caller’s policy allows its region, and whether the request fits its context window. These filters matter most during failover, where the next target in line may be unsuitable.
Limits: requests, tokens, concurrency, and budgets
A limit has two parts: what it counts and what happens when it is exceeded. Language-model traffic needs several counts, because no single one captures cost or load.
| Limit | Counts | Protects against | Weakness |
|---|---|---|---|
| Requests per minute | Calls | Floods of calls, loops | A few large requests can use far more capacity than many small ones |
| Tokens per minute | Input plus output tokens | Heavy requests; matches provider limits and cost | Output size is unknown at admission |
| Concurrency | Requests in flight | Exhausting slots on a self-hosted model; slow upstream calls | Says nothing about how large each request is |
| Budget | Spend over a period | Runaway cost | Spend is known only after the call |
The weakness of request counts is easy to quantify. A limit of 60 requests per minute admits 60 requests of 100 tokens (6,000 tokens per minute) and 60 requests of 20,000 tokens (1,200,000 tokens per minute) equally. Providers meter both for this reason. Anthropic documents separate limits for requests, input tokens, and output tokens per minute. OpenAI documents requests and tokens per minute among its limits, and states that a limit can be reached on any of them, whichever comes first.
The token bucket
The standard mechanism for rate limits is the token bucket. (This is unrelated to language-model tokens; the name predates them.) A bucket holds up to a capacity \(C\) units and refills continuously at a rate \(r\) units per second. A request that needs \(n\) units is admitted if the bucket holds at least \(n\), and the bucket then drops by \(n\). If it does not, the request is refused, and the time until it would fit is
\[ t_{\text{wait}} = \frac{n – \text{level}}{r} \]
The capacity sets the largest burst and the rate sets the sustained throughput. A bucket for 6 requests per minute has \(C = 6\) and \(r = 0.1\) per second: six calls can arrive at once, and after that one more is admitted every 10 seconds, which is also the Retry-After value for a refused caller. Anthropic’s documentation says its API uses the token bucket algorithm and that a limit stated per minute may be enforced at a finer granularity, such as 60 requests per minute enforced as one per second, so short bursts can trigger errors even when the minute total is within the limit. A gateway limit should therefore sit below the provider’s, and the gateway’s burst capacity needs to be chosen deliberately.
A request whose cost exceeds the capacity can never be admitted, however long the caller waits. That case should not look like a rate limit. Returning 429 with a Retry-After would invite retries that cannot succeed, so the bucket reports “never fits” separately and the gateway answers 413 with an explanation.
Counting tokens before the response exists
A token limit has a timing problem: the number of output tokens is not known when the request arrives. Three approaches exist, and gateways differ.
- Reserve, then reconcile. Charge an upper bound at admission (the estimated input plus the requested
max_tokens), then refund the unused part when the response reports its actual usage. This is the approach in the demo. It is safe, since a request cannot be admitted if its worst case does not fit, but it has a side effect that is visible in practice: a caller who sets a largemax_tokensis limited as if it would use all of it. OpenAI’s rate-limit guide says exactly this, that the limit is computed from the larger ofmax_tokensand an estimate from the request’s character count, and recommends settingmax_tokensclose to the expected response size. - Charge after the response. Admit the request if the bucket is not already over its limit, then charge the real usage when the response finishes. Envoy AI Gateway documents this behavior for its token-based limits, including for streaming: an admitted stream is not interrupted when it pushes usage past the limit, and later requests are rejected until the window recovers. The approach never wastes capacity on pessimistic reservations, but one admitted request can overshoot the limit by its full size.
- Count against the provider’s own accounting. Providers may count tokens differently from each other, as the next section shows. A gateway that enforces a provider’s limit on the provider’s terms needs to know those terms.
Concurrency limits are the third kind. They matter most for self-hosted models, where the number of slots is the capacity, and for slow upstreams, where requests in flight accumulate. The behavior when the cap is exceeded is a policy choice. LiteLLM’s documentation for max_parallel_requests states that requests over the cap now receive an immediate 429, whereas earlier versions queued them, which could serialize traffic silently and produce long latencies instead of errors. That is the same trade-off as the bounded queue in the serving article: an unbounded wait hides overload from the caller.
Budgets
A budget limits spend per team or key over a period. It differs from a rate limit in what a refusal means. A rate-limited caller can succeed after waiting. A caller whose budget is exhausted cannot, until the period resets or someone raises the budget, so the response must not suggest retrying. Anthropic’s documentation shows the same distinction on its own API: reaching a spend limit returns a 429 of the same rate_limit_error type as a rate limit, but with no retry-after header and an error_code that tells the cases apart, and it states that retrying, including automatic retries in its SDK, fails until access resumes. A gateway that returns one undifferentiated 429 for both makes client retry logic wrong for one of them. The gateway below uses distinct error types and sends Retry-After only for rate limits.
Spend is known only after a call completes, so a budget is a soft limit. If the check runs before the call and the charge after, a few calls in flight when the budget is crossed will all finish. The overshoot is bounded by the number of concurrent requests times the largest possible cost, and a gateway that needs a hard cap must reserve worst-case cost the way the token limit does. LiteLLM’s documentation lists per-key, per-user, and per-team spend tracking with budgets and a reset duration, and records spend in database tables.
When the gateway runs as several replicas, limit state has to be shared or the effective limit multiplies by the number of replicas. LiteLLM’s router documentation says Redis can hold cooldown and usage state across instances. Envoy AI Gateway builds on Envoy Gateway’s global rate limit service. Local state is fast and approximate, shared state is accurate and adds a dependency and a round trip. Retry-After and Backoff explains how a client should combine the hint returned with a 429 with its own backoff.
Provider differences and the adapter layer
Applications want one request format. Providers do not agree on one, and the differences go beyond field names.
| Area | What differs | Example |
|---|---|---|
| Request schema | Where the system prompt goes, which fields are required, how messages and content blocks are shaped | Anthropic’s Messages API takes system as a separate top-level field and requires max_tokens. OpenAI’s Chat Completions API takes max_completion_tokens (its older max_tokens is documented as deprecated), and that bound includes reasoning tokens |
| Response schema | Where text and usage appear, names of stop reasons | Anthropic lists stop reasons such as end_turn, max_tokens, tool_use, and refusal; other APIs use stop and length |
| Token accounting | How tokens are counted and which count toward limits | Anthropic documents limits for input and output tokens separately, and for most Claude models only uncached input tokens count toward the input limit; OpenAI documents a combined tokens-per-minute metric |
| Errors | Status codes and types for overload and limits | Anthropic documents 529 overloaded_error for overload; OpenAI documents Retry-After on both 429 and 503 |
| Streaming | Event formats, and when usage is reported | Usage may arrive only at the end of a stream |
| Limits of the model | Context window, maximum output | Differ by model and change with versions |
An adapter converts between the gateway’s format and one provider’s, in both directions: it maps the request out and the response, usage, and errors back. Envoy AI Gateway expresses the provider choice as an API schema on each AIServiceBackend, and its documentation lists the schemas it supports, such as OpenAI-style, AWS Bedrock, Azure OpenAI, Vertex AI, and Anthropic’s. LiteLLM presents an OpenAI-compatible interface in front of many providers and, per its documentation, maps context-window and content-policy errors across providers so that fallbacks can be chosen by error type.
What an adapter cannot hide is as important. Tokenizers differ, so the same text has different token counts and therefore different cost and different headroom against a limit. Token explains why there is no universal conversion from words or characters to tokens. Context windows differ, so a request that fits one model may not fit another. Features differ, and a request that uses a capability one model lacks cannot be translated. A gateway should treat these as eligibility properties of each target and skip targets that cannot serve a request, instead of sending it and handling the failure.
A minimal gateway
The following code implements the functions above. It uses only the Python standard library (Python 3.12 on macOS), runs the gateway and two fake providers as HTTP servers on the loopback interface, and drives them with a script. The providers imitate two wire styles in simplified form: alpha speaks a chat-completions style API with prompt_tokens and completion_tokens, and beta speaks a messages style API with a top-level system field, a required max_tokens, content blocks, and input_tokens and output_tokens. They also differ in tokenizer (about 4 and about 3 characters per token), region, context window, and prices. A fake clock lets the script advance time without waiting.
The token bucket and clock come first.
import math
class FakeClock:
"""A clock the demo can advance, so rate-limit examples are deterministic."""
def __init__(self): self.t = 0.0
def __call__(self): return self.t
def advance(self, s): self.t += s
class TokenBucket:
"""Holds up to `capacity` units and refills at `rate` units per second."""
def __init__(self, capacity, rate, clock):
self.capacity, self.rate, self.clock = capacity, rate, clock
self.level, self.last = float(capacity), clock()
def _refill(self):
now = self.clock()
self.level = min(self.capacity, self.level + (now - self.last) * self.rate)
self.last = now
def available(self):
self._refill()
return self.level
def try_take(self, n):
"""Returns (admitted, retry_after_seconds). retry_after is None if n can never fit."""
self._refill()
if n > self.capacity:
return False, None
if n <= self.level:
self.level -= n
return True, 0.0
return False, math.ceil((n - self.level) / self.rate)
def refund(self, n):
self._refill()
self.level = min(self.capacity, self.level + n)
The fake providers can be switched into overload or rate-limited modes. Their error formats differ on purpose: alpha answers 503 with a Retry-After header, and beta answers 529 without one.
"""Two fake model providers with deliberately different wire formats, token counts, and error semantics."""
import json, math, threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
def make_provider(kind, state):
"""kind 'alpha' speaks a chat-completions style API; 'beta' speaks a messages style API.
`state` is a dict the demo mutates: {'mode': 'ok'|'overloaded'|'ratelimited', 'calls': 0}."""
class H(BaseHTTPRequestHandler):
def log_message(self, *a): pass
def _send(self, code, body, headers=()):
raw = json.dumps(body).encode()
self.send_response(code); self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(raw)))
for k, v in headers: self.send_header(k, v)
self.end_headers(); self.wfile.write(raw)
def do_POST(self):
state["calls"] += 1
req = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
if state["mode"] == "overloaded":
if kind == "alpha":
return self._send(503, {"error": {"type": "server_is_overloaded", "message": "try later"}}, [("Retry-After", "5")])
return self._send(529, {"type": "error", "error": {"type": "overloaded_error", "message": "overloaded"}})
if state["mode"] == "ratelimited":
if kind == "alpha":
return self._send(429, {"error": {"type": "rate_limit_exceeded", "message": "slow down"}}, [("Retry-After", "7")])
return self._send(429, {"type": "error", "error": {"type": "rate_limit_error", "message": "slow down"}}, [("retry-after", "7")])
if kind == "alpha":
text = " ".join(m["content"] for m in req["messages"])
tin = math.ceil(len(text) / 4) # alpha's tokenizer: ~4 characters per token
tout = min(req.get("max_tokens", 64), 12)
self._send(200, {"id": "a-1", "model": req["model"],
"choices": [{"message": {"role": "assistant", "content": "alpha answer " + text[:20]},
"finish_reason": "stop" if tout < req.get("max_tokens", 64) else "length"}],
"usage": {"prompt_tokens": tin, "completion_tokens": tout}})
else:
if "max_tokens" not in req:
return self._send(400, {"type": "error", "error": {"type": "invalid_request_error", "message": "max_tokens: field required"}})
text = req.get("system", "") + " " + " ".join(m["content"] for m in req["messages"])
tin = math.ceil(len(text) / 3) # beta's tokenizer: ~3 characters per token
tout = min(req["max_tokens"], 12)
self._send(200, {"id": "b-1", "model": req["model"],
"content": [{"type": "text", "text": "beta answer " + text[:20]}],
"stop_reason": "end_turn" if tout < req["max_tokens"] else "max_tokens",
"usage": {"input_tokens": tin, "output_tokens": tout}})
srv = ThreadingHTTPServer(("127.0.0.1", 0), H)
threading.Thread(target=srv.serve_forever, daemon=True).start()
return srv
The gateway applies the pipeline from the diagram. Note the order of steps. Authentication comes first, and the audit record is created even for refused requests. Limits are checked before any provider is called. The candidate list is filtered by policy before it is tried. On a retryable provider error the provider is put into a cooldown and the next candidate is tried; a non-retryable provider error is not retried elsewhere, because the same request is likely to fail again and the cause is probably in the gateway’s translation.
import hashlib, json, math, random, threading, urllib.error, urllib.request
from collections import namedtuple
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from bucket import TokenBucket
Target = namedtuple("Target", "provider model weight")
Provider = namedtuple("Provider", "schema region context price_in price_out") # prices: credits per 1K tokens
PROVIDERS = {"alpha": Provider("chat", "eu", 8000, 1.0, 3.0),
"beta": Provider("messages", "us", 2000, 0.8, 4.0)}
ALIASES = {"chat-default": [Target("alpha", "alpha-large", 80), Target("beta", "beta-medium", 20)],
"chat-premium": [Target("alpha", "alpha-large", 100)],
"pin-alpha": [Target("alpha", "alpha-large", 100)],
"pin-beta": [Target("beta", "beta-medium", 100)]}
RETRYABLE = {429, 500, 502, 503, 504, 529}
COOLDOWN_SECONDS = 30
def to_provider(schema, req, model):
if schema == "chat":
return "/v1/chat/completions", {"model": model, "messages": req["messages"], "max_tokens": req["max_tokens"]}
system = " ".join(m["content"] for m in req["messages"] if m["role"] == "system")
rest = [m for m in req["messages"] if m["role"] != "system"]
return "/v1/messages", {"model": model, "system": system, "messages": rest, "max_tokens": req["max_tokens"]}
def from_provider(schema, b):
if schema == "chat":
c = b["choices"][0]
return dict(text=c["message"]["content"], finish={"stop": "stop", "length": "length"}],
tin=b["usage"]["prompt_tokens"], tout=b["usage"]["completion_tokens"])
return dict(text=b["content"][0]["text"], finish={"end_turn": "stop", "max_tokens": "length"}[b["stop_reason"]],
tin=b["usage"]["input_tokens"], tout=b["usage"]["output_tokens"])
class Gateway:
def __init__(self, clock, urls, keys, budgets, seed=0):
self.clock, self.urls, self.budgets = clock, urls, budgets
self.keys = {hashlib.sha256(k.encode()).hexdigest(): p for k, p in keys.items()} # only hashes are stored
self.buckets, self.spend, self.cooldown, self.audit = {}, {t: 0.0 for t in budgets}, {}, []
self.rng, self.lock, self.n = random.Random(seed), threading.Lock(), 0
def _buckets(self, name, pol):
if name not in self.buckets:
self.buckets[name] = (TokenBucket(pol["rpm"], pol["rpm"] / 60, self.clock),
TokenBucket(pol["tpm"], pol["tpm"] / 60, self.clock))
return self.buckets[name]
def _order(self, targets):
pool, out = list(targets), []
while pool:
pick = self.rng.choices(pool, [t.weight for t in pool])[0]
out.append(pick); pool.remove(pick)
return out
def handle(self, auth, req):
with self.lock:
return self._handle(auth, req)
def _handle(self, auth, req):
self.n += 1
rec = {"id": f"req-{self.n:04d}", "attempts": []}
def done(status, body, headers=None, **extra):
rec.update(status=status, **extra); self.audit.append(rec)
return status, {"x-request-id": rec["id"], **(headers or {})}, body
def err(status, etype, msg, headers=None):
return done(status, {"error": {"type": etype, "message": msg}}, headers, error=etype)
# 1. authenticate: who is calling?
key = auth.removeprefix("Bearer ") if auth else ""
pol = self.keys.get(hashlib.sha256(key.encode()).hexdigest())
if pol is None:
return err(401, "authentication_error", "invalid or missing API key")
rec.update(caller=pol["app"], team=pol["team"], alias=req.get("model"))
# 2. authorize the alias
targets = ALIASES.get(req.get("model"))
if targets is None or req["model"] not in pol["aliases"]:
return err(403, "permission_error", "this key may not use that model alias")
max_tokens = min(req.get("max_tokens", 256), 4096)
text = " ".join(m["content"] for m in req["messages"])
rec["prompt_sha"] = hashlib.sha256(text.encode()).hexdigest()[:8] # never log the prompt itself
est_in = math.ceil(len(text) / 3) # conservative estimate
reserve = est_in + max_tokens
# 3. budget, then rate limits
if self.spend[pol["team"]] >= self.budgets[pol["team"]]:
return err(429, "budget_exceeded", "team budget exhausted for this period") # no Retry-After: waiting does not help
rpm, tpm = self._buckets(pol["app"], pol)
ok, wait = tpm.try_take(reserve)
if not ok and wait is None:
return err(413, "request_too_large", f"needs {reserve} tokens; the per-minute limit is {tpm.capacity}")
if not ok:
return err(429, "rate_limit_exceeded", "token rate limit", {"Retry-After": str(wait)})
ok, wait = rpm.try_take(1)
if not ok:
tpm.refund(reserve)
return err(429, "rate_limit_exceeded", "request rate limit", {"Retry-After": str(wait)})
# 4. choose candidates: weighted order, then drop providers this request must not use
candidates, ordered = [], self._order(targets)
preferred = ordered[0].provider # the first choice before any filtering
for t in ordered:
p, why = PROVIDERS[t.provider], None
if self.cooldown.get(t.provider, 0) > self.clock(): why = "cooldown"
elif pol["regions"] and p.region not in pol["regions"]: why = "region"
elif reserve > p.context: why = "context_window"
if why: rec["attempts"].append(f"{t.provider}:skipped({why})")
else: candidates.append(t)
if not pol["allow_fallback"]: candidates = candidates[:1]
# 5. call providers in order, failing over on retryable errors
for t in candidates:
p = PROVIDERS[t.provider]
path, body = to_provider(p.schema, req | {"max_tokens": max_tokens}, t.model)
status, payload, retry_after = self._call(self.urls[t.provider] + path, body)
if status == 200:
out = from_provider(p.schema, payload)
cost = (out["tin"] * p.price_in + out["tout"] * p.price_out) / 1000
self.spend[pol["team"]] += cost
tpm.refund(reserve - out["tin"] - out["tout"]) # return the unused part of the reservation
rec["attempts"].append(f"{t.provider}:200")
return done(200, {"model": t.model, "choices": [{"text": out["text"], "finish_reason": out["finish"]}],
"usage": {"input_tokens": out["tin"], "output_tokens": out["tout"]}},
{"x-served-by": f"{t.provider}/{t.model}", "x-fallback": str(t.provider != preferred).lower()},
served=f"{t.provider}/{t.model}", fallback=t.provider != preferred, tin=out["tin"], tout=out["tout"], cost=round(cost, 4))
rec["attempts"].append(f"{t.provider}:{status}")
if status not in RETRYABLE:
tpm.refund(reserve)
return err(502, "upstream_rejected", f"{t.provider} rejected the request ({status})")
self.cooldown[t.provider] = self.clock() + max(COOLDOWN_SECONDS, retry_after)
tpm.refund(reserve)
return err(503, "no_eligible_provider", "no provider could serve this request under the caller's policy")
def _call(self, url, body):
r = urllib.request.Request(url, json.dumps(body).encode(), {"Content-Type": "application/json"})
try:
with urllib.request.urlopen(r, timeout=2) as resp:
return resp.status, json.loads(resp.read()), 0
except urllib.error.HTTPError as e:
ra = e.headers.get("Retry-After") or e.headers.get("retry-after") or "0"
return e.code, json.loads(e.read() or b"{}"), int(ra)
except (urllib.error.URLError, TimeoutError):
return 504, {}, 0
def serve(gw):
class H(BaseHTTPRequestHandler):
def log_message(self, *a): pass
def do_POST(self):
req = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
status, headers, body = gw.handle(self.headers.get("Authorization"), req)
raw = json.dumps(body).encode()
self.send_response(status); self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(raw)))
for k, v in headers.items(): self.send_header(k, v)
self.end_headers(); self.wfile.write(raw)
srv = ThreadingHTTPServer(("127.0.0.1", 0), H)
threading.Thread(target=srv.serve_forever, daemon=True).start()
return srv
The demo script sets up four callers with different policies, then runs seven scenarios. Its keys are placeholders for this exercise.
import collections, json, urllib.error, urllib.request
from bucket import FakeClock
from providers import make_provider
from gateway import Gateway, serve
clock = FakeClock()
state = {"alpha": {"mode": "ok", "calls": 0}, "beta": {"mode": "ok", "calls": 0}}
provs = {k: make_provider(k, state[k]) for k in state}
urls = {k: f"http://127.0.0.1:{p.server_port}" for k, p in provs.items()}
def pol(app, team, aliases=("chat-default", "chat-premium", "pin-alpha", "pin-beta"), rpm=600, tpm=600_000, regions=None, fb=True):
return dict(app=app, team=team, aliases=set(aliases), rpm=rpm, tpm=tpm, regions=regions, allow_fallback=fb)
keys = {"key-search-0001": pol("search-app", "search"),
"key-batch-0002": pol("batch-app", "batch", aliases=("chat-default",), rpm=6, tpm=1200),
"key-eu-0003": pol("eu-app", "eu", regions={"eu"}),
"key-trial-0004": pol("trial-app", "trial")}
gw = Gateway(clock, urls, keys, budgets={"search": 1e9, "batch": 1e9, "eu": 1e9, "trial": 0.2}, seed=4)
gurl = f"http://127.0.0.1:{serve(gw).server_port}/v1/chat/completions"
def call(key, model="chat-default", prompt="Summarize the incident report for the on-call team.", max_tokens=64, system=None):
msgs = ([{"role": "system", "content": system}] if system else []) + [{"role": "user", "content": prompt}]
r = urllib.request.Request(gurl, json.dumps({"model": model, "messages": msgs, "max_tokens": max_tokens}).encode(),
{"Content-Type": "application/json", **({"Authorization": "Bearer " + key} if key else {})})
try:
with urllib.request.urlopen(r) as resp: return resp.status, dict(resp.headers), json.loads(resp.read())
except urllib.error.HTTPError as e: return e.code, dict(e.headers), json.loads(e.read())
def show(label, res):
st, h, b = res
detail = b["error"]["type"] if "error" in b else f"served by {h.get('x-served-by')} fallback={h.get('x-fallback')}"
ra = f" Retry-After={h['Retry-After']}" if "Retry-After" in h else ""
print(f" {label:<34s} -> {st} {detail}{ra}")
print("1. Authentication and authorization")
show("no key", call(None)); show("unknown key", call("key-nope"))
show("valid key, allowed alias", call("key-search-0001"))
show("batch-app asks for chat-premium", call("key-batch-0002", model="chat-premium"))
print("\n2. Weighted routing, 500 requests, alias chat-default = alpha 80 / beta 20")
c = collections.Counter(call("key-search-0001")[1]["x-served-by"] for _ in range(500))
print(" ", dict(c))
print("\n3. Rate limits for batch-app: 6 requests per minute, 1,200 tokens per minute")
for i in range(1, 9): show(f"request {i} (small)", call("key-batch-0002", max_tokens=20))
clock.advance(10); show("after waiting 10 s", call("key-batch-0002", max_tokens=20))
clock.advance(60)
tpm = gw.buckets["batch-app"][1]
print(f" token bucket after a minute of quiet: {tpm.available():.0f} of {tpm.capacity}")
show("max_tokens=1150", call("key-batch-0002", max_tokens=1150))
print(f" bucket after the call (unused part of the reservation refunded): {tpm.available():.0f}")
show("max_tokens=1150 again", call("key-batch-0002", max_tokens=1150))
show("max_tokens=1150, third time", call("key-batch-0002", max_tokens=1150))
show("max_tokens=5000", call("key-batch-0002", max_tokens=5000))
print("\n4. Budget: trial team has 0.2 credits")
for i in range(1, 7): show(f"request {i}", call("key-trial-0004"))
print(f" spend = {gw.spend['trial']:.4f} credits (the check runs before the call, so one request can overshoot)")
print("\n5. Same prompt and system message, pinned to each provider")
for alias in ("pin-alpha", "pin-beta"):
st, h, b = call("key-search-0001", model=alias, system="Be brief.")
print(f" {h['x-served-by']:<18s} usage={b['usage']} finish={b['choices'][0]['finish_reason']}")
print("\n6. Failover: alpha starts returning 503")
state["alpha"]["mode"] = "overloaded"
before = {k: v["calls"] for k, v in state.items()}
for i in range(1, 4): show(f"request {i}", call("key-search-0001"))
print(" provider calls during these 3 requests:", {k: state[k]["calls"] - before[k] for k in state})
clock.advance(31); state["alpha"]["mode"] = "ok"
for i in range(4, 7): show(f"request {i} (alpha healthy, cooldown over)", call("key-search-0001"))
print("\n7. Failover that policy forbids")
state["alpha"]["mode"] = "overloaded"; gw.cooldown = {}
show("eu-app, alpha down", call("key-eu-0003"))
gw.cooldown = {}; state["alpha"]["mode"] = "ok"
state["alpha"]["mode"] = "overloaded"
show("long prompt, alpha down", call("key-search-0001", prompt="x" * 7000, max_tokens=64))
state["alpha"]["mode"] = "ok"
print("\nAudit records (the prompt text is never stored, only a short hash)")
picks = [next(r for r in gw.audit if r.get("fallback")),
next(r for r in gw.audit if "alpha:skipped(cooldown)" in r["attempts"]),
gw.audit[-2], gw.audit[-1]]
for r in picks: print(" ", json.dumps(r))
The output below is from one run. The script is deterministic: the weighted choice uses a seeded generator and time comes from the fake clock.
1. Authentication and authorization
no key -> 401 authentication_error
unknown key -> 401 authentication_error
valid key, allowed alias -> 200 served by alpha/alpha-large fallback=false
batch-app asks for chat-premium -> 403 permission_error
2. Weighted routing, 500 requests, alias chat-default = alpha 80 / beta 20
{'alpha/alpha-large': 384, 'beta/beta-medium': 116}
3. Rate limits for batch-app: 6 requests per minute, 1,200 tokens per minute
request 1 (small) -> 200 served by alpha/alpha-large fallback=false
request 2 (small) -> 200 served by alpha/alpha-large fallback=false
request 3 (small) -> 200 served by alpha/alpha-large fallback=false
request 4 (small) -> 200 served by beta/beta-medium fallback=false
request 5 (small) -> 200 served by beta/beta-medium fallback=false
request 6 (small) -> 200 served by alpha/alpha-large fallback=false
request 7 (small) -> 429 rate_limit_exceeded Retry-After=10
request 8 (small) -> 429 rate_limit_exceeded Retry-After=10
after waiting 10 s -> 200 served by alpha/alpha-large fallback=false
token bucket after a minute of quiet: 1200 of 1200
max_tokens=1150 -> 200 served by alpha/alpha-large fallback=false
bucket after the call (unused part of the reservation refunded): 1175
max_tokens=1150 again -> 200 served by alpha/alpha-large fallback=false
max_tokens=1150, third time -> 429 rate_limit_exceeded Retry-After=1
max_tokens=5000 -> 413 request_too_large
4. Budget: trial team has 0.2 credits
request 1 -> 200 served by alpha/alpha-large fallback=false
request 2 -> 200 served by alpha/alpha-large fallback=false
request 3 -> 200 served by alpha/alpha-large fallback=false
request 4 -> 200 served by alpha/alpha-large fallback=false
request 5 -> 200 served by alpha/alpha-large fallback=false
request 6 -> 429 budget_exceeded
spend = 0.2450 credits (the check runs before the call, so one request can overshoot)
5. Same prompt and system message, pinned to each provider
alpha/alpha-large usage={'input_tokens': 16, 'output_tokens': 12} finish=stop
beta/beta-medium usage={'input_tokens': 21, 'output_tokens': 12} finish=stop
6. Failover: alpha starts returning 503
request 1 -> 200 served by beta/beta-medium fallback=true
request 2 -> 200 served by beta/beta-medium fallback=true
request 3 -> 200 served by beta/beta-medium fallback=true
provider calls during these 3 requests: {'alpha': 1, 'beta': 3}
request 4 (alpha healthy, cooldown over) -> 200 served by alpha/alpha-large fallback=false
request 5 (alpha healthy, cooldown over) -> 200 served by alpha/alpha-large fallback=false
request 6 (alpha healthy, cooldown over) -> 200 served by beta/beta-medium fallback=false
7. Failover that policy forbids
eu-app, alpha down -> 503 no_eligible_provider
long prompt, alpha down -> 503 no_eligible_provider
Audit records (the prompt text is never stored, only a short hash)
{"id": "req-0526", "attempts": ["alpha:503", "beta:200"], "caller": "search-app", "team": "search", "alias": "chat-default", "prompt_sha": "26c185f7", "status": 200, "served": "beta/beta-medium", "fallback": true, "tin": 18, "tout": 12, "cost": 0.0624}
{"id": "req-0527", "attempts": ["alpha:skipped(cooldown)", "beta:200"], "caller": "search-app", "team": "search", "alias": "chat-default", "prompt_sha": "26c185f7", "status": 200, "served": "beta/beta-medium", "fallback": true, "tin": 18, "tout": 12, "cost": 0.0624}
{"id": "req-0532", "attempts": ["beta:skipped(region)", "alpha:503"], "caller": "eu-app", "team": "eu", "alias": "chat-default", "prompt_sha": "26c185f7", "status": 503, "error": "no_eligible_provider"}
{"id": "req-0533", "attempts": ["beta:skipped(context_window)", "alpha:503"], "caller": "search-app", "team": "search", "alias": "chat-default", "prompt_sha": "bad0f0b2", "status": 503, "error": "no_eligible_provider"}
Reading the results
Authentication and authorization behave as designed (section 1). A missing key and an unknown key both get the same 401, with no hint about which part was wrong. A valid key with a disallowed alias gets 403, a different failure with a different remedy.
Weighted routing (section 2) sends 384 of 500 requests to alpha and 116 to beta, which is 77 and 23 percent for configured weights of 80 and 20. Weights describe probabilities, and a finite sample deviates from them. A rollout that depends on an exact split needs a deterministic assignment, for example hashing a request or user identifier.
The rate-limit scenario (section 3) shows the bucket’s burst-then-sustain behavior. The batch-app key allows 6 requests per minute, so six requests pass at the same instant, the seventh and eighth are refused with Retry-After=10, and after 10 simulated seconds one more is admitted. The token limit shows reservation and reconciliation. With the bucket full at 1,200 tokens, a request with max_tokens=1150 is admitted because its reservation (1,150 plus an estimated 17 input tokens) fits. The request actually used 25 tokens, so the unused reservation is refunded and the bucket reads 1,175. A second identical request is admitted too, and a third is refused with a 1-second Retry-After, because the bucket is down to about 1,150 and the third reservation needs 1,167. None of these requests used more than 25 tokens. This is the cost of pessimistic reservation: a caller that declares a large max_tokens is throttled as if it would use it. A request with max_tokens=5000 is capped by the gateway at 4,096, and because that exceeds the bucket’s whole capacity it gets 413, not 429: no waiting would help.
The budget scenario (section 4) refuses the sixth request with budget_exceeded and no Retry-After. The spend is 0.245 credits against a 0.2 budget. The check ran before each call and the charge after, so the fifth request, which started at 0.196, finished above the limit.
The same prompt and system message cost different input token counts on the two providers (section 5): 16 on alpha and 21 on beta, because of their tokenizers (in this fake setup, 4 and 3 characters per token). The audit records show the cost consequence for a similar request: 0.049 credits through alpha and 0.0624 through beta, 27 percent more, even though beta‘s input price is lower, because its output price is higher and its token count is larger. A budget in currency and a limit in tokens are different things, and failover between providers changes both.
Failover: when it is safe
Failover means sending a request to a different target because the intended one failed. It is attractive because it converts a provider outage into a slower or different answer instead of an error. It is safe only when four questions have an answer.
- Is the failure retryable? Overload, timeouts, connection errors, and rate limits from the provider are. A 400 from the provider usually is not, because the next provider will likely reject the same request, and it often signals a translation bug. The gateway returns 502 with
upstream_rejectedfor those. Authentication failures on the provider side are a platform problem and should alert, not fail over silently. - Is the next target eligible? Failover moves traffic to a provider the request may not be allowed to reach, or that cannot handle it. Scenario 7 shows two cases. The
eu-appcaller is restricted to theeuregion andbetais inus, so whenalphais down the gateway refuses with 503no_eligible_providerinstead of silently moving data across a boundary. A long request that exceedsbeta‘s context window is refused for the same reason. The audit records show why:beta:skipped(region)andbeta:skipped(context_window). Data-handling terms such as region, retention, and permitted use differ between providers and are contractual, so they belong in the eligibility filter. They are not a preference. - Will the answer be acceptable? A different model produces different output. Prompts tuned for one model may behave differently on another, and refusal and safety behavior differ. Fallbacks come in two kinds that deserve different treatment. The same model served from another deployment or region changes latency but not behavior. A different model family changes behavior. LiteLLM’s configuration distinguishes load balancing across deployments of one
model_namefromfallbacksthat name other model groups. Different-model fallbacks should be evaluated before they are enabled, and callers whose outputs are consumed by other systems should be able to opt out. The demo implements this as a per-callerallow_fallbackflag. The release gates in the next article apply to fallback targets as well as primary ones. - Can the fallback carry the load? A provider outage moves all of its traffic to the next target at once, which can exceed the fallback’s own rate limits and produce a second failure. The fallback target needs capacity headroom, and the gateway’s limits need to account for the total.
The gateway also needs a rule for when to stop sending traffic to a failing target. In scenario 6, alpha begins answering 503. The first request tries alpha, receives the error, records a 30-second cooldown, and succeeds on beta. The next two requests skip alpha entirely, and the provider call counts confirm it: alpha was called once and beta three times across the three requests. Without the cooldown, every request would pay the failed attempt, and a struggling provider would keep receiving traffic. After the cooldown expires the gateway tries alpha again, and the following requests are served by alpha. This is a simple circuit breaker. A more careful one admits a few probe requests before restoring full traffic, and uses error rates over a window in place of one failure. Envoy AI Gateway’s fallback configuration expresses a similar policy through priorities and a BackendTrafficPolicy retry configuration, where retries are triggered by connection failures, retriable status codes, and similar conditions.
Streaming adds one more constraint. Once the gateway has sent the first bytes of a response to the client, it cannot restart the request on another provider without the client seeing a corrupted or duplicated answer. Failover for streamed responses therefore has to happen before the first byte, and a failure partway through a stream is an error the client must handle.
Audit
The audit record is what lets a platform answer questions after the fact: who used what, which model answered, why a request failed, whether a fallback served it, and what it cost. Audit Log makes the general point that a request and its outcome are different events and that a record is useful only if it carries identifiers that can be correlated. The gateway’s records have these properties.
- Identity: the application and team, from the credential, never the credential itself.
- The requested alias and the model that actually served the request, plus the list of attempts with their outcomes. The records above show
["alpha:503", "beta:200"]for a failover and["beta:skipped(region)", "alpha:503"]for a refusal, so a reader can reconstruct the decision. - The
fallbackflag, so that quality changes can be correlated with the days when a fallback served traffic. - Token counts and cost as reported by the provider, so budgets can be reconciled.
- A request identifier, returned to the client in a header so a user report can be matched to a record.
- A short hash of the prompt text, not the prompt. Prompts and responses often contain personal or confidential data, and storing them in a platform log makes the log a sensitive store of its own. If content has to be retained for debugging or evaluation, that is a separate decision with its own access control and retention, covered in the next module’s article on observability and sensitive data.
The response carries the same provenance, in x-served-by and x-fallback headers and in the model field. Clients that store model output should store the served model alongside it, since the alias alone no longer identifies what produced the text.
Choosing a gateway
Two open-source gateways are widely used and have public documentation, and they represent two different ways to deploy the function.
| LiteLLM proxy | Envoy AI Gateway | |
|---|---|---|
| Shape | A standalone proxy with an OpenAI-compatible API in front of many providers | A set of Kubernetes custom resources layered on Envoy Gateway and the Gateway API |
| Identity | Virtual keys owned by users and teams; JWT/OIDC is documented as an enterprise feature | Envoy Gateway security policies, including JWT validation; upstream credentials in a BackendSecurityPolicy |
| Limits and budgets | Per-key and per-team budgets, tpm_limit, rpm_limit, max_parallel_requests | Token-based rate limiting through Envoy Gateway’s global rate limit service; a quota policy for cumulative token budgets |
| Routing and fallback | Weighted and strategy-based routing, order, fallbacks, context-window and content-policy fallbacks, cooldowns | Prioritized backends with retry policy |
| State | Spend and keys in a database; Redis for shared limit and cooldown state | Rate-limit service; Kubernetes resources for configuration |
The choice follows from where the platform already lives. A platform running on Kubernetes with Envoy-based ingress can express routing, authentication, and limits in the same declarative system it uses for other traffic, and gets Envoy’s proxy performance and observability. A team that wants per-user keys, spend tracking, and an OpenAI-compatible front end quickly, without adopting a service mesh, gets that from a standalone proxy, at the price of operating the proxy and its database. Managed gateways from cloud providers exist as well; their features and limits are specified by each provider and are not covered here. Whichever is chosen, the checks in the demo (each of the seven scenarios) are the ones to run against it.
Envoy AI Gateway’s documentation now presents the project under the name Agent Router, as a project of the Agentic AI Foundation, and states that the Kubernetes API groups and resource names are unchanged.
Failure modes of the gateway itself
The gateway sits in the path of every call, so its own failures need explicit design.
- Availability. Run several stateless replicas behind a load balancer, keep configuration in a store that survives restarts, and decide what limit state is shared. A gateway with local state fails open or closed per replica, and the choice should be deliberate: failing closed when the limit store is unreachable protects budgets and breaks applications, failing open does the reverse.
- Added latency. The gateway adds processing and a hop. Measure it separately from provider latency, with the same percentile discipline as in the serving article, and keep per-request work cheap: hashing a key and updating a bucket is, but logging full prompt bodies synchronously is not.
- Overload of the gateway. It needs its own concurrency and queue bounds, for the same reasons as any service. Admission control that rejects early protects both the gateway and the providers behind it.
- Configuration errors. A wrong alias mapping or weight sends traffic to the wrong model for every application at once. Alias changes should be versioned, reviewed, and rolled out gradually, with the audit log showing which configuration served each request.
- Credential leakage. A gateway holding every provider credential is a valuable target. Keep credentials in a secret store, rotate them, and scope them to the gateway’s needs.
What comes next
A gateway decides which model answers. It does not decide whether a new prompt or a new model should start answering at all. That decision needs evidence from an evaluation run, thresholds that mean something, and a way to roll back. Prompt and Model Promotion with Evaluation Gates builds that release gate, including the check that a fallback target is acceptable before it is allowed to serve traffic.
References
- LiteLLM documentation, AI Gateway (LLM Proxy)
- LiteLLM documentation, Router: load balancing, fallbacks, and cooldowns
- LiteLLM documentation, Virtual keys, teams, and spend tracking
- LiteLLM documentation, Fallbacks and reliability
- Envoy AI Gateway documentation (now Agent Router)
- Envoy AI Gateway documentation, Usage-based rate limiting
- Envoy AI Gateway documentation, Provider fallback
- Envoy AI Gateway documentation, Upstream authentication
- Envoy Gateway documentation, JWT authentication
- Claude API documentation, Rate limits
- Claude API documentation, Errors
- Claude API documentation, Create a Message
- OpenAI API documentation, Rate limits
- RFC 6585, Additional HTTP Status Codes
Discover more from Insightful Data Lab
Subscribe to get the latest posts sent to your email.
