Module 2: How to make your routing decisions stronger
Routing saves money only inside certain boundaries. Learn where those boundaries are, from the cache arithmetic to the fallback chain, and write them into a one-page decision record.
Route by complexity, by role, or by task type
The rule you wrote in the first module routes by complexity, which is one of three axes.
Complexity routing decides which tier handles a task. Role routing decides which capability handles it, regardless of tier. Task-type routing fires on the shape of the request.
The axes compose, as the cost-aware agent design pattern on AgentPatterns shows: a role can still run on a lightweight or a powerful model.
This lesson shows you the two other axes and the four mechanisms, so you can decide whether to keep your rule, add to it, or replace it.
Routing by complexity
You already run this axis. The pattern's starting table matches it to coding work:
| Task type | Characteristics | Model tier |
|---|---|---|
| File search, exploration | High volume, low reasoning | Fast |
| Code implementation | Balanced capability and speed | Balanced |
| Architecture, complex refactoring | Deep reasoning required | Performance |
The same idea runs inside a single agent as big.LITTLE orchestration, named after the CPU design with powerful cores for demanding work and efficient cores for background tasks. A powerful model reasons while an efficient one does read-only exploration.
NVIDIA calls the same shape at system scale a system of models: a frontier reasoning model plans and orchestrates a workflow, while smaller specialized models perform targeted tasks such as code review, tool use, and alert monitoring.
A contributed post on the Stack Overflow blog frames the same axis as routing by what the decision needs.
Low-stakes or high-volume decisions go to a cost-effective model, ambiguous or high-stakes decisions to a capable model, and long-context or extraction-heavy work to the model measured best at it. A judge goes to a different model family from the primary, so its verdict is independent.
That post keeps the routing rules in one place, the gateway, where they stay readable and testable. LangChain puts the router in the harness instead, because the harness holds the task context a gateway lacks.
Both keep the rules in one place; they differ on which place.
Routing by role
Role routing asks a different question: which capability does this step need? The OPENDEV paper defines five model roles. Each is independently configurable, with its own fallback chain for graceful degradation:
| Role | Purpose | Fallback |
|---|---|---|
| Action | Primary execution model for tool-based reasoning | Default for all workloads |
| Thinking | Extended reasoning without tool access | Action model |
| Critique | Self-evaluation of output, selective, not every turn | Thinking model, then Action model |
| Vision | Vision-language model for screenshots and images | Action model, if vision-capable |
| Compact | Fast summarization during context compaction | Action model |
A provider abstraction separates role assignment from model identity, so you can swap providers without touching agent code.
In a multi-agent coding pipeline, the roles are the agents themselves. The Augment Code routing guide walks through four: a coordinator that decomposes requirements and manages parallel work, implementors that write code, a navigator that searches files, and a reviewer that checks the result.
Each role has a different cost of getting the model wrong:
| Agent role | Over-provisioning cost | Under-provisioning cost |
|---|---|---|
| Planning and orchestration | Unnecessary spend on the largest model | Poor decomposition cascades errors downstream |
| File navigation and search | 5x cost inflation on high-frequency retrieval | None; capable models offer no quality benefit |
| Code generation | Wasted context on small files | Truncation discards instructions on large files |
| Code review | Serialized bottleneck limits parallel reviews | Missed bugs and security vulnerabilities |
When a weaker model handles planning, every downstream agent operates on malformed inputs with no upstream correction. When a frontier model handles file navigation, hundreds of structurally simple reads exhaust the budget before the tasks that need it.
Routing by task type
Task-type routing reads the shape of the request rather than its difficulty or its role. A DataCamp tutorial on the Claude Code Router shows five routes in one coding harness:
| Task type | When it fires | Typical model choice |
|---|---|---|
| background | File scanning, context gathering | Fast local model |
| think | Plan mode, complex reasoning | Reasoning model |
| longContext | Requests above a token threshold | High-context model |
| webSearch | Web search tasks | Model with native search support |
| default | Everything else | Mid-tier capable model |
The author's experience is that the background route delivers the biggest immediate return. Silent file-scanning requests happen constantly during a coding session, and before routing he had no idea how much they were adding up.
Task-type classification can go much finer. OpenRouter's market-based router assigns each prompt one of roughly 30 task types, such as code debugging or multi-step planning, and then ranks models by what the community spends on that task type over a trailing week.
Four mechanisms, and when each breaks
Whichever axis you choose, the rule runs through one of four mechanisms. The Augment guide compares the first three:
| Factor | Static | Dynamic | Hybrid |
|---|---|---|---|
| Best for | Fixed pipelines with clear role boundaries | High-volume systems with variable task complexity | Complex workflows where planning requires frontier models |
| Setup complexity | Low: assign a model per agent | Medium: train or tune a routing classifier | Medium: configure planner plus execution pool |
| Latency overhead | None | 50 to 200 ms per routing decision | Planning step only |
| Breaks when | Task complexity varies within a role | Call volume is too low to justify classifier maintenance | Planning model cost dominates the budget |
| Team size fit | Any | 5+ engineers with ML ops capacity | 3+ engineers comfortable with multi-model orchestration |
Hybrid routing pairs a static planner with dynamic execution. A reasoning model produces a multistep plan, then selects the model for each step based on whether intelligence or latency matters most.
It saves on execution, not on orchestration, because the planning step still needs a frontier model.
Dynamic routing has a volume threshold. Augment Code puts it at about 500 agent calls per day: below that, the engineering overhead of maintaining a classifier often exceeds the savings it produces.
The fourth mechanism is the cascade. You query the more cost-effective model first and escalate only when a check fails. FrugalGPT showed up to 98% cost reduction this way, and no coding tool implements it natively.
You approximate it with a two-pass pattern: fast model first, a deterministic gate such as tests, a linter, or a type checker, then escalation to the capable model on failure.
Goal: Decide the axis for your router and record why.
- Take your task-mix table from the first module. Mark each class with the axis that explains its cost best: complexity, role, or request shape.
- Check the "breaks when" row against your agent. Does task complexity vary inside one role or one class?
- Count your agent's calls per day and compare against the 500-call threshold.
If a role or a task type explains cost better than complexity, add one route for it to
config.yamlas a second router entry. Keepsmart-routerfor the rest.config.yaml- model_name: background litellm_params: model: fast- Write the axis decision and the reason in one paragraph as a comment at the top of your config file.
Expected result: A one-paragraph axis decision in your config, and at most one new route alongside the complexity router. In the next lesson you decide when the router is allowed to switch, and what a switch costs you in cache.
When switching models mid-session costs more than it saves
Your router picks a tier once per thread, at the first message. That boundary was a default. This lesson shows you what a mid-session switch costs, and gives you the rules for when a switch is allowed.
SSD Nodes founder and CEO Matt Connor explains why agent traffic is different, and the rest of this lesson follows his arithmetic.
Why cost in an agent loop is the prefix, re-billed every call
An agent turn is not one request. One instruction like "fix the failing test" becomes twenty to sixty API calls, and each call re-sends the entire conversation: the system prompt, every tool definition, every file the agent has read, every command output it has seen.
By call thirty the repeated prefix can be tens of thousands of tokens, while the new content in each call is a few hundred.
That shape changes what "expensive" means. In chat, cost is roughly the model's price times the request. In an agent loop, cost is the prefix, re-billed on every single call, and the prompt cache is what keeps that affordable.
Caches are keyed on a hash of the prompt prefix, and they are per model. A request to a different model hashes against a store that has never seen the prefix, finds nothing, and pays full price.
The cache is also a hierarchy: tools first, then system, then messages. A change at any level invalidates that level and everything after it, so editing one tool definition discards the system prompt cache behind it.
Agents that register tools at runtime hit this without touching a router at all.
What one mid-session switch costs
Take a session with a 40,000-token stable prefix, an ordinary size once an agent has read a handful of files. Here is the prefix cost of a single turn, worked from published list prices.
The first turn on the balanced model costs more because that model holds no entry for the prefix and has to write one. Coming back costs the most, because the original entry expired while the session was away.
So the round trip pays two cache writes to avoid two cache reads. Against that, the switch bought one turn of output at the more cost-effective model's output price.
The saving lands in fractions of a cent, and the cache penalty lands in tens of cents. The penalty is larger by more than an order of magnitude, and it grows with prefix length while the saving does not.
A second comparison breaks most routing plans. A router moving work down a tier compares list prices.
But an agent mid-session is paying the cache-read price on the model it already uses, and that price sits below the uncached rate of every more cost-effective tier but one.
Read across the rows. Re-reading a warm prefix on either Opus costs less per input token than reading the same prefix cold on Haiku 4.5, and far less than reading it cold on either Sonnet.
The exception is the newest small model, whose uncached input undercuts a warm Opus read on prompts up to 100,000 tokens. Past that size it charges five times more, and long agent sessions cross that line.
When a switch is allowed: four positions
SSD Nodes' position has four rules:
- Route across providers for availability. When the alternative is a failed request, any cost is the right cost.
- Route across tiers for cost at task boundaries only. A fast model for a rename and a performance model for a refactor is a good decision made once, before the session starts, and a bad decision made on turn thirty.
- Pin one model per session for anything agentic. Treat switching the way you would treat clearing the cache, because that is what it does.
- Route subagents freely. A subagent that starts with a fresh, small context has no warm cache to lose.
LangChain, in the Open SWE router, picks once at thread start and keeps that model for the whole thread. Mid-thread re-routing is on their list for later: when a question turns into a bug fix, a model change might pay off.
OpenRouter's market-based router takes a middle path it calls session stickiness. It remembers the model a conversation landed on and prefers it on later turns, but still ranks candidates from scratch each turn.
When the conversation shifts to a different kind of task, a better-suited model can win.
Scott Wu, CEO of Cognition, argues from the other direction.
The initial prompt is not enough to know the difficulty of a task: "fix xyz bug" could be a one-line edge case or a rearchitecture, and you cannot know until the agent has investigated the code.
So the agent needs to be able to update and re-route dynamically.
Caching saves as much as routing does
The honest default is one model, chosen once, with caching turned on and a TTL long enough to cover the gaps when you stop to read a diff.
The one-hour cache write costs twice base input and pays for itself after two reads. On any session where you expect to come back and continue, the longer lifetime usually costs less than a cold prefix.
The cost-aware agent design pattern on AgentPatterns reaches the same conclusion from the billing side. Cached input bills at a tenth of fresh input on every model in that comparison, which makes a stable prompt prefix as valuable as a tier downgrade.
Routing pays when the context is fresh and small: at the start of a task, or in a subagent that carries only the context it needs.
You can see the symptom of a lost cache in the response itself. Check the cache-read and cache-creation token fields in the usage object; a turn that reads zero cached tokens on a long session is the sign that a switch happened.
Goal: Measure the cache share of your own agent's sessions and write the boundary rule into your config.
- From the week of traces you exported in the first module, pull the cache-read and cache-creation token counts per call for three long sessions.
- For each session, compute the share of input tokens that were cache reads.
- Find any turn after the first few calls that read zero cached tokens, and check the
modelfield on that turn. - Work the switch arithmetic for your own prefix size, using the three scenarios from the table above and your provider's current prices.
Decide the boundary: thread start only, or thread start plus a named escalation trigger. Write it as a comment under the router entry in
config.yaml, and enable session pinning if your proxy supports it.config.yaml# Boundary: route at thread start only. Subagents may route freely. # Escalate mid-task only on a retry loop.- Set the cache TTL to the longer option for sessions where someone reads diffs between turns.
Expected result: A three-row sheet (session, cache-read share, switch events found) and a boundary rule in your config that names when a switch is allowed. In the next lesson you rewrite the fallback block so an outage never becomes a silent quality drop.
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.
Design fallback so an outage never silently changes your output
Your fallback block pairs a primary model with a same-provider standby. That was the right first move, and this lesson shows you why.
It also shows you what goes wrong when a fallback fires in the middle of a task, how to tighten the trigger, and when routing itself is the wrong tool.
Fallback routing is the feature most likely to be enabled by accident. A gateway is configured to retry on another model when the first returns a rate limit or a server error, then puts the failed model in a cooldown for some seconds.
On chat traffic that is exactly right.
Inside a long agent task, as SSD Nodes founder and CEO Matt Connor points out, it means the second half of your task ran on a model you did not choose.
A mid-task fallback changes behavior with no error
Nothing reports the switch. The task does not fail, the agent does not warn, and the exit status is success.
What you get is a task where the plan was written by one model and the edits were made by another, with a tone and a set of habits that change halfway through.
The only reliable signal is the model field in the gateway's request log or the response metadata. If you run fallbacks at all, log that field per request and read it when a result surprises you.
Debugging behavior without knowing which model produced it wastes more time than the fallback saved.
Scott Wu, CEO of Cognition, makes the underlying point from the other side: even when different models can pass the task, subtle differences in behavior and style mean they are not interchangeable.
Tool-call formats are not the same across providers
An agent is a tool-calling loop, so the tool-call format matters in a way it never does for chat. One provider's API returns a tool-use content block and expects a tool-result block back.
OpenAI-compatible APIs return a tool-calls array in which the function arguments are a JSON-encoded string rather than a nested object. A gateway translates between the two, and for ordinary calls the translation is clean.
The problems appear at the edges. Parallel tool calls, where a model emits several calls in one response, are represented differently and are not supported identically everywhere.
Strict schema enforcement is a per-provider feature, so a model that guarantees schema-valid arguments on one endpoint only tends toward valid arguments on another.
Your agent sees the difference as a tool result containing a parse error, which it then tries to repair by spending another turn.
Those repair turns are billed at the full prefix price, so a format mismatch shows up on the invoice as well as in the transcript.
The rule from your setup follows from that: pin the fallback to a model with the same tool-call format, so the agent's loop keeps working when the standby takes over.
Put retry, circuit breakers, and fallback in one place
A multi-provider environment exposes more failure modes than a single provider. Individual providers rate-limit, return server errors, degrade in latency, or occasionally produce malformed outputs.
Datadog's guidance on AI gateways in production warns that when every agent implements its own retry and failover logic, behavior is inconsistent and reliability bugs recur across teams.
The fix is one configuration at the gateway. A single retry policy lets a throttled request retry an efficient number of times before it rolls over to the next option, and prevents retry storms from bringing down agent services.
Circuit breakers stop routing to a provider that is failing, so cascading timeouts do not spread. Load balancing across multiple deployments of the same model keeps you under per-deployment rate limits.
Choose the fallback target with care. Fallback models can have different cost, latency, and quality characteristics.
A/B the fallback target and confirm it meets a minimum quality bar before you make it a live failover. Otherwise reliability improves at the cost of output regressions.
Once the target is live, keep watching it. Track per-provider error rates, per-provider latency, retry frequency, and fallback frequency, and alert on the last two, so you can spot a provider degrading and adjust your policy.
Four rules that make a fallback chain correct
A contributed post on the Stack Overflow blog writes the fallback chain as an ordered list per request. A low-stakes request falls from the cost-effective model to the capable one.
A high-stakes request falls from the capable model to a named fallback. A judge never falls back silently, because an independent verdict from a different model is the point.
Four non-obvious rules make the chain correct:
- Check the circuit breaker before calling, and record a failure on every caught error. The common bug is doing both inside the error handler, so the breaker never proactively skips a dead provider.
- Use one overall deadline with per-attempt timeouts. A fixed timeout reused per model makes total latency the number of models times the timeout, which blows the upstream budget.
- Idempotency is mandatory. A primary that timed out but completed its work must not be double-processed.
- Degrade deliberately. Decide per capability whether a weaker fallback's answer is acceptable, or whether the request should route to a human with a reason code.
Name the escalation signal and watch the fallback rate
You already have the four escalation signals from the AWS Well-Architected Agentic AI Lens: a confidence score below a threshold, a schema validation failure, a parse error, or an explicit incomplete response, with escalation limited to one step.
The number to watch afterward is the fallback rate. A rising fallback-escalation rate on a class is an early indicator that the primary model no longer fits, either because traffic shifted or because a newer model would serve the class better.
It shows up before the user-facing regression is large enough to alarm.
One discipline ties routing and fallback together: eval every model on the path.
A routed-to or fallen-back-to model is a different model, with potentially different quality, and a fallback that quietly tanks quality is a worse outage than the one it covers.
Your golden set should pass on the cost-effective model and on the fallback model for the capabilities that use them.
Record which model decided, so outcome analysis can see whether the cost-effective or the fallback model underperformed. SSD Nodes reached the same rule from the cache side.
If you route by role, give each role its own chain. The OPENDEV roles you met in the lesson on choosing the routing axis each degrade to a named next model, rather than to whatever the gateway picks.
When routing itself is the wrong tool
The cost-aware agent design pattern on AgentPatterns lists four conditions where routing backfires:
- Validation gates are slow or absent. A cascade only saves money when the gate is cost-effective and deterministic: tests, a linter, a type checker. If the validation step takes longer than the cost difference between tiers, the cascade adds latency without saving money. Measure gate cost before you commit to escalation-based routing.
- Single-task pipelines with low volume. A three-tier routing system adds configuration and coordination overhead. For a pipeline with one task type and few invocations, a single capable model at a fixed tier is simpler and often costs less once you amortize setup and maintenance.
- Frequently updated model rosters. Routing fails when a provider deprecates or renames a model tier. Teams without automated model-ID management spend engineering time on breakage rather than on shipping.
- High task interdependency. Some tasks cannot be separated by complexity, such as a refactor that needs reasoning at every file edit. Routing exploration to a fast model and implementation to a capable one then backfires, because the capable model must re-ingest the fast model's findings, which adds tokens and latency.
- Default everything to the top tier. Safe but wasteful at scale.
- Heavy agents for simple tasks. Decompose into lightweight agents.
- Vague agent descriptions. "Helps with code" gives the orchestrator no delegation signal.
Goal: Write a one-page routing decision record for your router, with the fallback block rewritten.
Rewrite
router_settingsso the standby shares the primary's provider and tool-call format. Picknum_retriesandcooldown_timevalues on purpose, and write the reason beside them.config.yamlrouter_settings: fallbacks: [{"performance": ["balanced"]}] # same provider, same tool-call format num_retries: 2 # one retry storm is enough cooldown_time: 30 # seconds before the primary is tried again- Add the escalation signal your agent can emit: a schema failure, a parse error, or a confidence threshold. Limit escalation to one step.
- Confirm the proxy logs the
modelfield per request. Add an alert on fallback frequency. - Run the backfire checklist against your agent: gate cost, calls per day, roster churn, task interdependency.
- Run one chaos drill. Kill the model provider for the performance tier and assert that decisions route to the standby or to a human, rather than erroring out.
- Write the decision record in one page: the axis and the reason, the boundary rule, the fallback rule with its signal, standby, and log field, and the backfire checks you ran.
Expected result: A decision record a second engineer can reproduce your config from, and a fallback block where every value is a choice you can explain.
By this point you should have:
- An axis decision written into your config, with at most one extra route beside the complexity router.
- A cache-read measurement for three real sessions and a boundary rule that names when a switch is allowed.
- A fallback block on a same-format standby, an escalation signal, a logged model field, and an alert on fallback rate.
- A one-page routing decision record covering all three.
Your router now has defensible decisions behind it. The next module covers the controls that keep it honest over time: budgets and telemetry at the routing layer, and the review cadence that keeps your tiers current as models change.
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.