Module 3: How to run routing as a system
Keep the router honest after it ships: spend ceilings at the gateway, a model-swap drill you can rerun each quarter, and a vetted list of tools to run it all on.
Put budgets and alerts at the gateway
Your proxy routes and falls back, but nothing yet stops a runaway agent, and nothing shows you spend by tier. This lesson adds keys, caps, and the dashboard signals that tell you whether the controls work.
In a multi-team environment, every agent service makes its own provider calls. Datadog's guidance on AI gateways in production puts it plainly: without a gateway, there is no single place to implement cost controls. With one, budgets and rate limits live in one control plane.
Adjusting a spend limit becomes a config update to the proxy, not a coordinated deployment across every agent service, and when a provider changes its pricing, the budget policy updates once and applies everywhere.
Virtual keys and caps
The mechanism is the virtual key. Each team, agent, or service gets its own key with its own spend ceiling.
When a key hits its limit, the proxy returns a 429 before the request ever reaches the provider, so an overrun stops at the gateway instead of surfacing in a billing dashboard after the fact.
You can also set tokens-per-minute and requests-per-minute caps per key or per model. Agent loops are where this matters most. A single misconfigured agent can fan out into many parallel calls and exhaust a provider quota, or run up significant spend, in minutes.
Beyond individual keys, some gateways support team-level budgets. A platform team allocates a monthly spend pool to each product team and enforces it centrally, so individual agent developers never manage cost controls themselves.
A per-request price cap, such as the maximum price filter in OpenRouter's auto router, is a second control at a finer grain.
Two more caps come from a contributed post on the Stack Overflow blog. Set a platform-wide ceiling, because N tenants times a per-tenant cap has no aggregate bound otherwise.
Cap the two things that quietly multiply a bill by ten: retry storms, where a flaky validation re-calls the model, and unbounded tool loops, where an agent keeps going. Emit a retries counter by reason, so a storm is visible.
The same post ranks the cost levers in order of payoff, and right-sizing the model is one of five:
- Don't call the model: route easy, deterministic cases through code.
- Batch: one call for many items instead of N calls.
- Cache: memoize deterministic results such as embeddings.
- Right-size the model: a cost-effective model for simple decisions, a capable one for the rest.
- Trim the prompt: load only the context the decision needs.
Right-sizing feeds directly into routing. If a cost-effective model passes evals for a slice, route it there; 5 to 20 times lower cost per call is common.
Your routing config is the first budget control
Keys catch overruns, and the routing configuration prevents them. A DataCamp tutorial on the Claude Code Router shows what that looks like. When background and default routes point to cost-effective or local models, premium models are never invoked for low-value tasks.
Reserve the reasoning and long-context routes for work that justifies the cost, and keep the long-context threshold as high as your workflow tolerates.
Where the gateway sits is a decision of its own. Datadog's caveat is that a gateway adds a network hop and an operational burden that can be hard for a smaller organization.
If your org reaches for only a few models and is short on platform engineering time, a shared SDK wrapper in your application code can suffice.
Three numbers that show the controls work
Budget controls are only as effective as your visibility into them. With the proxy in place, track spend and request volume for each virtual key.
Then set alerts to report when a team is approaching its budget, when a single key's spend is anomalous, or when a new agent rollout shifts the spend distribution.
Datadog names the three signals to track first:
- Spend per virtual key and per model, over time.
- Token usage broken out by agent task.
- The ratio of lightweight-model calls to frontier-model calls across your agent fleet.
Those three let you distinguish the probable causes of high cost: heavy use of one high-cost model, high-context tasks that can be trimmed, underuse of cost-effective models for simple tasks, and high usage from a particular team or user.
Keep the routing-quality signals from the first module on the same dashboard. Per-class latency, tokens, quality, and fallback rate belong beside total latency.
Treat cost-efficiency as a first-class eval axis. The cost-aware agent design pattern on AgentPatterns makes the case: when tokens or dollars per task at fixed quality score beside correctness, a routing change that quietly raises spend without improving quality shows up as a regression.
A router that reports the saving per request against an all-frontier baseline in its logs gives you that number for free.
Five questions a production-ready router answers
A Stack Overflow field guide to production-grade agents puts cost control, model routing, fallback, and a kill switch together on one rung of its maturity model: Level 5, Operability.
Its Level 5 deep-dive defines the rung with five questions. Can you run this thing day to day, see what it is deciding, control what it costs, survive a provider outage, and stop it in seconds when it misbehaves?
It sets a cost SLO to match, dollars per thousand decisions within a band of plan, and a starter alert that fires when an hour's spend exceeds the daily budget divided by 24.
Stopping it in seconds needs a kill switch, and that means something specific.
A deploy takes minutes you may not have, so the switch is runtime state that every node checks, with a middle gear that stops auto-execution while the agent keeps proposing, and a fail-toward-safe default when a node cannot read the switch.
A 30-second local cache of the switch is not "seconds."
Goal: Put one spend ceiling and one alert on your proxy.
Create a virtual key for the agent with a monthly budget and a tokens-per-minute cap. Choose values that fit one week of the traffic you measured in the first module.
terminalcurl -X POST http://localhost:4000/key/generate \ -H "Authorization: Bearer $LITELLM_MASTER_KEY" \ -d '{"max_budget": 50, "budget_duration": "30d", "tpm_limit": 100000, "metadata": {"team": "platform"}}'- Send requests with the new key until it fails with a budget-exceeded error. Confirm in the proxy log that the provider was not called.
- Add two dashboard panels: spend per key and per model, and the lightweight-to-frontier call ratio.
- Set two alerts: an hour's spend above the daily budget divided by 24, and fallback frequency above a threshold you pick.
- Check the Level 5 definition above against your setup. Note which of its five questions you cannot yet answer yes to.
Expected result: A key that rejects requests at its ceiling, two panels, two alerts, and a note on which maturity line is still open. In the next lesson you set the review cadence that keeps the models behind your tiers current.
Swap in new models without a redeploy
The model behind each alias is a value in a YAML file that you edit by hand and restart.
This lesson turns that into a runtime setting with a rollout path and a review cadence, so a new model reaches a tier without a redeploy and without a surprise.
The right model for a task keeps changing, because new models, open-weight ones included, keep landing on the frontier.
The LangChain engineers who built the Open SWE router describe the payoff of being ready for that: picking up those gains means swapping a tier, not rebuilding your agent.
The AWS Well-Architected Agentic AI Lens states the principle behind it. Model selection is a runtime-configurable parameter, not a one-time architectural decision.
Keep the tier-to-model mapping out of the code
The opposite is an anti-pattern: treating model choice as a decision baked into application code, so that evaluating or rolling out a new model requires a code change and a redeploy rather than a configuration update.
The fix is to hold three things outside the code. Model identifiers, task-class-to-tier mappings, and fallback rules go into a feature-flag or configuration service, and the router reads them at request time.
Decoupling selection from deployment lets you evaluate, promote, or roll back a model without redeploying the agent.
Datadog's guidance on AI gateways in production makes the same move from the gateway side. Because the gateway exposes one API across providers, switching the model for a specific agent step is a config change, not a code change.
Teams iterate on model choice per task in the gateway's configuration files, without modifying application logic.
The aliases you set up in the second lesson are what make this safe.
The cost-aware agent design pattern on AgentPatterns puts it bluntly: routing fails when a provider deprecates or renames a model tier, and teams without automated model-ID management spend their engineering time on breakage rather than on shipping features.
Roll a model change out in steps, with automatic rollback
A model swap is a deployment, so treat it as one. Shift traffic to the new model in steps, with bake-time validation at each step. Attach alarms on latency and quality, so the change rolls back automatically when an alarm fires.
Treating a model swap as a monitored deployment is what makes frequent model updates safe.
The two signals that gate promotion already sit on the dashboard you built in the previous lesson: per-class quality and the fallback-escalation rate. A rising fallback rate on the new model's class is the earliest sign that it does not fit.
If a live percentage feels like too much risk, the shadow evaluation you met in the first module is the lower-risk path. You run the candidate beside the incumbent on live traffic and judge both answers before you switch anything.
Review on your schedule, not the provider's
The last step is a schedule. Review per-class latency distributions, fallback-escalation rates, and quality scores on a defined cadence. Re-run your evaluation against newly released models, using the same task-distribution benchmark you built when you picked tiers.
Then promote, demote, or re-tier models based on observed data rather than on the provider's release cadence.
The cadence matters because the frontier moves. No single model stays best or most cost-effective for every sub-task, and the frontier shifts every few months.
When those configurations must constantly change as old models drift and new ones arrive, managing them in code is hard to do without breaking things.
What other teams saved, for comparison
You will want to judge your own numbers against something. Here is what other teams reported, each on its own workload.
Goal: Run one model-swap drill end to end and record it.
Turn on the proxy's runtime model store, so the alias-to-model mapping lives in its database instead of in
config.yaml. Changes made through the model endpoint apply to new requests without a restart.config.yamlgeneral_settings: store_model_in_db: trueAdd a candidate model under the
balancedalias as a second deployment, weighted to a small share of traffic. The proxy's default routing strategy splits requests between deployments that share a name by their weights.terminalcurl -X POST http://localhost:4000/model/new \ -H "Authorization: Bearer $LITELLM_MASTER_KEY" \ -H "Content-Type: application/json" \ -d '{"model_name": "balanced", "litellm_params": {"model": "provider/candidate-model", "api_key": "os.environ/PROVIDER_API_KEY", "weight": 1}}'Give the incumbent entry
weight: 9, so the candidate takes about one request in ten.- Run it for a bake period. Compare per-class cost, quality, and fallback rate against the incumbent on the dashboard from the previous lesson.
- Promote the candidate to the full share or roll it back. Record the decision, the date, and the numbers in your routing decision record.
- Put the next review on the calendar.
Expected result: A dated entry in your decision record with the candidate, the numbers, and the outcome, and a review date set.
The Code: Your daily unfair advantage in software engineering.
Join 350,000+ software engineers, tech leads, and CTOs who start their morning with The Code.
Which routing tools to start with
A short, vetted list of routers you can run this guide's setup on.
How routers compare
If you want to see routers scored against each other before you pick one, two public leaderboards do that. RouterArena, built at Rice University, is the independent one. It runs every router through the same 8,400 queries and reports accuracy and cost per thousand queries.
OpenRouter's board updates daily and lines routers up beside forty single models. Keep in mind that OpenRouter sells two of the routers it scores. On either board, the router you want is the one that beats the best single model at a lower cost.
By this point you should have:
- A virtual key with a budget and a rate cap, and the proxy rejecting requests at the ceiling.
- Two dashboard panels and two alerts, one on budget and one on fallback rate.
- The alias-to-model mapping in a runtime store, read without a restart.
- One model-swap drill run, recorded, and a review date on the calendar.
- A shortlist of routing tools, grouped by where the router sits.
Across the guide you built a router from a task map, chose and defended its three decisions, and put the controls around it that keep it honest.
The decision record you wrote is the artifact that outlives any model name in this guide, so keep it current, and let each review start there.
What’s Next
Your next steps after the guide.