Once a company uses more than one model, every application ends up reimplementing the same things: provider keys, retries, fallbacks when a provider is down, cost tracking per team, rate limits, redaction of personal data, and logs for audit. An AI gateway puts all of that in one place in front of every model, hosted APIs and self-hosted servers alike, behind one OpenAI-compatible endpoint. This lesson follows one request through a gateway, shows how it picks a model by task, falls back when the primary provider fails, and stops a runaway job before it spends a team's budget.
Difficulty: Advanced · Know this first: Lesson 36, Lesson 217, Lesson 234
This bar splits one request through the gateway, in milliseconds. It is a worked example, not a measurement. The model call is most of it; the gateway's own checks are tens of milliseconds.
Set the daily requests, their size, and how much traffic needs the large model. The rest goes to the small one. Prices are illustrative per million tokens: small $0.15 in and $0.60 out, large $3 in and $15 out.
cost per request = (input × input price + output × output price) ÷ 1,000,000 · saving = all-large cost − routed cost
Routing saves most of the bill
Three questions. No score is saved anywhere — this is just you against the material.
AI gateways grow in four levels: first why a front door helps, then configuring routes and keys, then policies, fallback, and observability, and finally running a multi-model platform for cost and governance.
At the basic level you can explain what a gateway does: one endpoint (usually OpenAI-compatible) in front of many models, hosted APIs and self-hosted servers. It holds the provider keys, knows which team is calling, applies limits and policies, picks a model, retries elsewhere when a provider fails, and records cost.
Examples: open-source gateways such as LiteLLM and Envoy AI Gateway, cloud gateways such as Azure API Management's AI policies and AWS Bedrock with inference profiles, and API gateways with AI plugins.
Where it breaks: the gateway becomes a single point of failure; run it like any critical API, in several replicas across zones.
Try it: Basic
Which problem does an AI gateway solve that a single app calling one provider does not see?
Now do it: List every place your organization calls a model, and who holds each key.
At the intermediate level you configure a gateway.
Troubleshooting: 429s from the gateway are your limits; 429s from a provider are its limits on your account; the gateway's logs say which.
Try it: Intermediate
An app gets 429 responses. How do you tell whether the gateway or the provider sent them?
Now do it: Run ai_gateway.py in Go deeper and lower the budget to $0.50. Find the request where the 429 starts.
At the advanced level the gateway enforces policy and keeps quality.
Try it: Advanced
A circuit breaker for a provider is open. What happens to requests on routes that use it?
Now do it: Write the routes for three tasks you run: the primary model, the fallback, and the evaluation each must pass.
At the master level the gateway is the control plane for AI use across the company.
Trade-off: a central gateway gives control and a single bill; it is also a shared dependency and a team that every AI project waits on. Keep it self-service: teams configure their own routes inside guardrails.
Try it: Master
A new provider offers the same quality at half the price. With a gateway, what does switching take?
Now do it: Estimate your monthly spend per model and per team. Which route would save the most if moved to a smaller model that passes its evaluations?
Routing, fallback, and budgets are a few lines each. This script routes three kinds of task, falls back when the primary provider is down, and refuses a request once the team's daily budget is spent. Prices are illustrative. Standard library only; python3 ai_gateway.py.
# ai_gateway.py - route by task, fall back on failure, and enforce a team's token budget
PRICES = { # dollars per million tokens (input, output); illustrative numbers
"small-fast": (0.15, 0.60), "large-smart": (3.00, 15.00), "backup-large": (2.50, 10.00)}
ROUTES = {"classify": ["small-fast"], "summarize": ["small-fast", "large-smart"], "reason": ["large-smart", "backup-large"]}
BUDGET = {"support": 2.00} # dollars per day, per team
spent = {"support": 0.0}
down = {"large-smart"} # the primary provider is returning 503 right now
def cost(model, tin, tout):
pin, pout = PRICES[model]
return (tin * pin + tout * pout) / 1_000_000
def call(team, task, tin, tout):
for model in ROUTES[task]:
if model in down:
continue # try the next model on the route
c = cost(model, tin, tout)
if spent[team] + c > BUDGET[team]:
return f"429 budget: {team} has ${BUDGET[team] - spent[team]:.4f} left, request needs ${c:.4f}"
spent[team] += c
return f"200 {model:<12} ${c:.4f}"
return "503 every model on the route is unavailable"
requests = [("classify", 800, 5), ("summarize", 3000, 300), ("reason", 2000, 1500)] + [("reason", 6000, 4000)] * 40
for i, (task, tin, tout) in enumerate(requests):
r = call("support", task, tin, tout)
if i < 4 or r.startswith("429"):
print(f"{task:<9} in={tin:<5} out={tout:<5} -> {r}")
if r.startswith("429"):
break
print(f"support spent ${spent['support']:.2f} of ${BUDGET['support']:.2f} today")
$ python3 ai_gateway.py classify in=800 out=5 -> 200 small-fast $0.0001 summarize in=3000 out=300 -> 200 small-fast $0.0006 reason in=2000 out=1500 -> 200 backup-large $0.0200 reason in=6000 out=4000 -> 200 backup-large $0.0550 reason in=6000 out=4000 -> 429 budget: support has $0.0542 left, request needs $0.0550 support spent $1.95 of $2.00 today
Read it like this: classification and summarization go to the small model for fractions of a cent; reasoning falls back to the backup model because the primary is down; and after thirty-odd large requests the team's $2 budget refuses the next one with a 429 that says exactly how much is left. Availability is checked before price, so a down model never blocks a request that the backup could serve.
model_list:
- model_name: support-summarize
litellm_params:
model: openai/gpt-4o-mini
api_key: os.environ/OPENAI_API_KEY
- model_name: support-reason
litellm_params:
model: openai/gpt-4o
api_key: os.environ/OPENAI_API_KEY
- model_name: support-reason-backup
litellm_params:
model: azure/gpt-4o-prod
api_base: os.environ/AZURE_API_BASE
api_key: os.environ/AZURE_API_KEY
router_settings:
fallbacks:
- support-reason: ["support-reason-backup"]
num_retries: 1
timeout: 30
general_settings:
master_key: os.environ/GATEWAY_MASTER_KEY
The file follows LiteLLM proxy's documented layout and parses as YAML; model identifiers change often, so take them from your providers' current lists. Team budgets and rate limits are set per virtual key through the proxy's admin API. Run it locally with the proxy's container image and a test key before pointing any app at it.
This is a composite of a failure pattern that keeps repeating; the numbers are illustrative. Several teams called a hosted model provider directly, each with its own key.
All traffic moved behind a gateway with per-team virtual keys, daily budgets with hard stops for batch keys, alerts at 50 and 80 percent, and a reserved share of the provider rate limit for customer-facing routes. Batch jobs got their own provider account. The retry bug would happen again somewhere; now it would cost one team one day's budget.
Design an AI gateway for a company where 15 teams use three hosted providers and two self-hosted models, with one customer-facing assistant and many internal tools and batch jobs.
Which data classes may go to which providers and regions? Which routes are customer-facing? What are the provider rate limits and contracts? How will teams be charged? Who may add a model to a route?
Say 2 million requests a day, 70 percent internal, average 2,500 input and 400 output tokens, and a monthly AI budget that must not grow faster than usage.
A gateway in two zones behind the internal load balancer, OpenAI-compatible; per-team virtual keys with allowed models, rate limits, and budgets (hard stops for batch); routes per task with evaluated fallbacks and circuit breakers; redaction and data-class policies on input, link and schema checks on output; reserved provider capacity for the customer-facing route; OpenTelemetry traces and a cost ledger with chargeback per team; self-service route config through Git with review.
Central control and a single bill versus a shared dependency and a team others wait on; self-service config within guardrails keeps it moving. Hard budget stops protect money and can stop a legitimate job; use them for batch, alerts for interactive routes. Redaction protects data and can remove context the model needed; test it on real prompts.