Model Routing Should Be a Policy Engine, Not a Vibe Check
Not every AI request needs the strongest model, but routing by intuition creates silent quality regressions. A production model router that combines task class, risk, context, latency, budget, capability requirements, and evaluation data.
On this page
Using the strongest available model for every request is simple. It is also an expensive way to solve problems that may include intent classification, short extraction, deterministic formatting, and a handful of genuinely difficult reasoning tasks.
The obvious response is model routing.
That phrase can hide a lot of hand-waving.
I have seen designs that amount to:
if prompt.length < 500: use cheap modelelse: use smart modelLength is not difficulty. A 60-character permission question can be high risk. A 10,000-token document may require only straightforward extraction. A routing rule that saves money while quietly moving the hardest edge cases onto the wrong model is not an optimization.
I prefer to treat model selection as an application policy with measurable inputs, explicit constraints, and a fallback path.
The example here is a SaaS assistant that handles support questions, structured extraction, RAG answers, and tool-using workflows.
Start with capabilities, not prices
A model is eligible only if it can satisfy the technical contract of the task.
That can include:
required input modalityminimum context requirementstructured-output supporttool-calling supportregion / data-processing requirementlatency classapproved provider listI represent those constraints separately from quality tiers.
type ModelProfile = { id: string; tier: "fast" | "balanced" | "strong"; contextLimit: number; supportsTools: boolean; supportsStructuredOutput: boolean; approvedDataClasses: Set<"public" | "internal" | "restricted">; regions: Set<string>;};A cheaper model that cannot legally or technically process the request is not a candidate.
This is especially important in enterprise products where model routing can accidentally become data routing.
Classify the task before selecting a model
I want a small application-level task vocabulary.
type TaskClass = | "intent-classification" | "structured-extraction" | "rag-answer" | "tool-planning" | "complex-analysis";type TaskRequirements = { taskClass: TaskClass; risk: "low" | "medium" | "high"; inputTokens: number; needsTools: boolean; needsStructuredOutput: boolean; dataClass: "public" | "internal" | "restricted"; region: string; latencyBudgetMs: number; remainingBudgetMicros: bigint;};Some fields come from deterministic application state. Others may come from a lightweight classifier.
I do not ask the same model that wants to execute an expensive action to decide, without constraints, whether it deserves the expensive model.
The host owns the routing decision.
Filter impossible candidates first
Deterministic eligibility should happen before scoring.
function eligibleModels( models: ModelProfile[], task: TaskRequirements,): ModelProfile[] { return models.filter((model) => { if (task.inputTokens > model.contextLimit) return false; if (task.needsTools && !model.supportsTools) return false; if ( task.needsStructuredOutput && !model.supportsStructuredOutput ) { return false; } if (!model.approvedDataClasses.has(task.dataClass)) return false; if (!model.regions.has(task.region)) return false; return true; });}This keeps policy failures explainable.
If no model remains, I want no eligible model for restricted data in region X, not a mysterious provider error after the router silently picked something else.
Routing rules should encode risk
The cheapest reasonable model for a newsletter subject line is not necessarily the right model for a high-impact tool plan.
A simple baseline policy might be:
function requiredTier(task: TaskRequirements): ModelProfile["tier"] { if (task.risk === "high") return "strong"; if (task.taskClass === "complex-analysis") return "strong"; if (task.taskClass === "tool-planning") return "balanced"; if (task.taskClass === "rag-answer") return "balanced"; return "fast";}That is not sophisticated. It is intentionally inspectable.
I would rather begin with explicit routing rules and evaluation data than train a routing model before I understand which requests are being misrouted.
Cost is a constraint, not the only objective
Once candidate models pass technical and quality policy, cost can help choose among them.
I think of the objective roughly as:
minimize expected cost and latencysubject to: capability requirements data policy quality floor risk policy run/tenant budgetThat is different from pick cheapest.
The budget ledger from the previous article can expose a normal, conserve, or blocked state. In conserve mode, optional enrichment may move from balanced to fast models, but high-risk actions do not get downgraded below their quality floor just because the tenant is near a budget limit.
Sometimes the correct budget behavior is to stop or ask the user before spending more.
A cheap-first cascade needs an acceptance test
Another routing pattern is a cascade:
- try a fast model;
- accept the result if it meets a verifiable quality condition;
- escalate otherwise.
This works well when the acceptance test is strong.
Structured extraction is a good example. A smaller model can attempt the extraction. The application validates schema and domain invariants. If required fields are missing or inconsistent, escalate.
type ExtractionResult<T> = { value: T; validationErrors: string[];};async function extractWithCascade<T>(input: { fast: () => Promise<ExtractionResult<T>>; strong: () => Promise<ExtractionResult<T>>;}): Promise<T> { const first = await input.fast(); if (first.validationErrors.length === 0) { return first.value; } const second = await input.strong(); if (second.validationErrors.length > 0) { throw new Error("Extraction failed validation after escalation"); } return second.value;}The cascade is safe because the acceptance condition is external to the model.
Self-reported confidence is not enough
This pattern makes me nervous:
Ask small model to answer.Ask small model whether it is confident.If confidence > 0.8, trust it.The same failure that produced a wrong answer can produce confident self-assessment.
Confidence can be a feature, but I prefer stronger escalation signals:
schema/domain validationretrieval coveragecitation supportknown ambiguitymissing required fieldstool-policy conflictindependent classifier/judge calibrated on evalsFor high-risk cases, the route itself can bypass the cheap attempt entirely.
A cascade should not spend one extra model call just to discover something the application already knew was difficult.
Routing classification can be wrong too
If a classifier decides whether a task is “simple” or “complex,” that classifier becomes part of the quality system.
It needs an evaluation set.
type RoutingCase = { input: string; expectedMinimumTier: "fast" | "balanced" | "strong"; tags: string[];};I include edge cases where short text hides difficult semantics:
"Can I delete this production key?""Refund 8,400 EUR.""Which of these clauses wins if they conflict?"And long inputs whose task is mechanically simple:
"Extract invoice number, date, and total from this document."Length can remain one feature. It should not be the model of difficulty.
Evaluate quality by route, not only globally
Suppose overall answer quality remains flat after routing.
That can hide this:
low-risk support: improved cost, same qualityhigh-risk tool planning: 8% regressionI slice evaluation by:
task classrisk classchosen model/tierfallback/escalation statuslanguagecontext-size buckettenant policy classCritical slices can have independent release gates.
Routing is infrastructure that changes which intelligence handles which user. It deserves the same regression discipline as a model upgrade.
Log the reason for the route
A production trace should not merely say:
model = model-balanced-2I want:
route.task_class = rag-answerroute.risk = mediumroute.required_tier = balancedroute.selected_profile = balanced-euroute.reason = quality-floorroute.policy_version = 12If a user reports a bad answer, I can see whether the model underperformed or the router selected a weaker model than intended.
Do not log the entire private prompt to explain routing. The structured route decision is enough for most investigations.
Route failures need a fallback policy
A preferred model can be rate-limited or unavailable.
Fallback is not simply “pick anything else.”
type FallbackPolicy = { allowedProfiles: string[]; preserveMinimumTier: boolean; allowCrossProvider: boolean;};For a low-risk summarization task, falling back from balanced to fast may be acceptable.
For a high-risk approval proposal, I may preserve the minimum tier and return a temporary error if no equivalent model is available.
Availability should not silently lower safety requirements.
This connects directly to the circuit-breaker article: an unhealthy provider can be removed from the eligible set, but the remaining candidates still pass routing policy.
Provider diversity is not free resilience
Supporting two model providers can reduce dependency risk, but it also doubles integration surfaces:
message formatsstructured-output behaviortool schemasrate-limit semanticsstreaming eventssafety behaviorusage accountingregional availabilityI keep a provider adapter contract and run the same routing/evaluation cases across every eligible backend.
Do not claim “automatic provider failover” until the fallback has been tested with the exact tool and structured-output features the workflow uses.
A second provider that cannot execute the task is not a fallback.
Model changes should not require routing-code edits everywhere
Profiles belong in configuration or a registry.
type ModelRegistry = { byId(id: string): ModelProfile | undefined; active(): ModelProfile[];};Application workflows ask for capabilities/tier, not a hard-coded vendor model string.
That lets operations canary a new model, retire an old one, or change provider mappings without rewriting business logic.
The registry version should appear in traces and eval records.
Shadow routing before moving traffic
A useful rollout pattern is to run the new router in shadow mode.
Production still uses the current model, while the candidate router records what it *would* have selected.
For a sampled subset, I can also run the candidate model offline or asynchronously and compare:
route agreementquality deltacost deltalatency deltaescalation rateThis catches surprising traffic classes before the router changes the user experience.
I do not run expensive shadow inference on every request indefinitely. A bounded sample is enough to learn where the policy differs.
Route the whole workflow carefully
One agent run may contain several model roles:
intent classifierretrieval query rewriteplanneranswer generatorjudgeThey do not need the same model.
The biggest savings often come from moving narrow supporting tasks to smaller models while keeping the core difficult reasoning step strong.
That is usually safer than downgrading the entire agent because “the user request looks simple.”
It also produces clearer evaluation: each model has a job with a specific contract.
When routing is unnecessary
If one model already meets quality, latency, cost, and compliance requirements and traffic is modest, a router adds configuration, failure modes, and evaluation work.
Use the simple architecture until there is a measurable reason to split.
Routing becomes useful when task classes have genuinely different requirements or AI spend/latency is large enough that one-size-fits-all is wasteful.
The key is to make the decision explicit.
A model router is not a clever prompt that guesses which model feels appropriate. It is a policy boundary between product requirements and provider capabilities. Once it has eligibility rules, quality floors, budget constraints, fallbacks, traces, and evals, model selection becomes another production subsystem that can be tested rather than a cost-saving heuristic you hope is right.
KEEP READING
Related engineering notes
A Failover Route Is Not a Recovery Path: Proving Independence in AI Infrastructure
Two LLM providers can share the same failure domain. Build an evidence-backed recovery graph that checks cloud, networking, identity, control-plane and capacity dependencies before admitting fallback routes, then test correlated outages without weakening safety.
Read articleAn Eval Platform Sunset Can Erase Your Release Evidence: Build an Evidence-Escrow Migration Gate
When a hosted LLM evaluation platform retires, switching runners is not enough. Preserve the historical evidence, reconstruct grader semantics, validate scoring parity, and enforce a fail-closed release gate that survives the service shutdown.
Read articleWhen the Package Runs Before Your App: Quarantining AI Framework Releases
The 2026 agent-framework PyPI compromise exposed a blind spot in AI build pipelines: Python startup hooks execute before application imports. Design an artifact-quarantine gate, inspect wheels without installing them, separate credentials, and recover from suspected exposure.
Read article