StackPractices
intermediate By Mathias Paulenko

LLM Router Pattern

Route queries to different LLM models based on complexity, cost, and latency requirements. Classify input before dispatching to the right model.

Overview

The LLM Router Pattern classifies each incoming query and dispatches it to the cheapest model that can handle it well. A question like “what is 2+2” doesn’t need a frontier model; “analyze this contract for liability clauses” shouldn’t go to the cheapest tier that will produce shallow output.

A router sits between the user and a pool of configured models. It inspects the query, applies a classifier (rules, embedding similarity, or a small model), and picks a tier. The cost asymmetry is what makes this pay: at current OpenAI pricing, a mini model costs an order of magnitude less per token than the flagship: routing 80% of traffic down a tier compounds into real money fast.

Two decisions carry the pattern. The first is the classifier: what signal tells you a query is hard. The second is the threshold: where you draw the line between tiers, knowing the two error directions don’t cost the same. Under-routing a complex query buys a cheap, wrong answer; over-routing a simple one buys a correct answer at 10-30x the necessary price.

When to Use

Use the LLM Router Pattern when:

  • You serve a mix of simple and complex queries and the cost gap between tiers is significant: a support chatbot where “what are your hours” sits next to “debug my integration”.
  • Models in your stack have different latency profiles and you want the fast path on the queries that don’t need depth.
  • You need graceful degradation when the primary model is overloaded or rate-limited; the router is a natural place to plug in the LLM Fallback Pattern.
  • Your app has distinct query categories (summarization, code, factual Q&A) that map to different model strengths, not just different sizes.
  • You run volume: below a few thousand calls a day, the engineering cost outweighs the savings.

Skip it (or keep it trivial) when:

  • Almost all your traffic is one complexity class: a router that sends 98% of queries to the same model is a function call wearing a costume.
  • Your “simple” queries are actually high-stakes. A misclassified medical or financial question costs more than the savings; route conservatively or don’t route at all.
  • You haven’t measured your traffic mix yet. Profile first; if the savings math doesn’t clear 2-3x the classifier’s own cost, skip it.

For the broader cost picture (caching, batching, prompt trimming), see the Complete Guide to LLM Cost Optimization. For alternatives at the retrieval layer, see the Embedding Cache Pattern.

Solution

Router pipeline — a query is classified by rules/embeddings/LLM, then routed to a small, medium, or large model. Low-confidence results cascade back to a bigger model.

Python

The canonical contract: a ModelConfig per tier, a classify_complexity that returns a level plus a confidence score, and an LLMRouter that maps levels to tiers. Confidence matters: it powers the cascade variant where a borderline classification can escalate:

from dataclasses import dataclass
from typing import Dict, List, Tuple
import re

@dataclass
class ModelConfig:
    name: str
    max_tokens: int
    cost_per_1k: float   # USD per 1K output tokens (illustrative)
    latency_ms: int

@dataclass
class Response:
    model: str
    content: str
    tokens_used: int
    cost: float

MODELS = {
    "small":  ModelConfig("gpt-4o-mini",  4096, 0.0006, 200),
    "medium": ModelConfig("gpt-4o",       8192, 0.005,  500),
    "large":  ModelConfig("o1",          16384, 0.015,  2000),
}

def classify_complexity(text: str) -> Tuple[str, float]:
    """Classify query complexity; return (level, confidence 0-1)."""
    lower = text.lower()
    word_count = len(text.split())
    score = 0

    complex_patterns = [
        r"analyze|design|architect|compare|evaluate",
        r"debug|refactor|optimize|review",
        r"step.by.step|detailed|thorough",
        r"legal|medical|financial|security",
    ]
    simple_patterns = [
        r"^\s*(what|who|when|where|is|are|can|do)\s",
        r"calculate|convert|format|translate",
        r"summarize|rewrite|paraphrase",
    ]

    for pattern in complex_patterns:
        if re.search(pattern, lower):
            score += 2
    for pattern in simple_patterns:
        if re.search(pattern, lower):
            score -= 2

    if word_count > 100:
        score += 2
    elif word_count < 20:
        score -= 1

    if score >= 2:
        return "high", min(0.5 + score * 0.15, 1.0)
    if score <= -2:
        return "low", min(0.5 - score * 0.15, 1.0)
    return "medium", 0.5  # the gray zone: no strong signal either way

def route_to_model(complexity: str) -> str:
    return {"low": "small", "medium": "medium", "high": "large"}.get(complexity, "medium")

def mock_generate(model: ModelConfig, prompt: str) -> Response:
    tokens = min(max(60, len(prompt.split()) * 2), model.max_tokens)
    cost = (tokens / 1000) * model.cost_per_1k
    return Response(
        model=model.name,
        content=f"[{model.name}] Response to: {prompt[:50]}...",
        tokens_used=tokens,
        cost=cost,
    )

class LLMRouter:
    def __init__(self, models: Dict[str, ModelConfig]):
        self.models = models
        self.stats = {"routed": 0, "escalated": 0, "total_cost": 0.0, "baseline_cost": 0.0}

    def handle(self, query_text: str) -> Response:
        complexity, confidence = classify_complexity(query_text)
        model_key = route_to_model(complexity)
        model = self.models[model_key]
        print(f"  [{complexity} @ {confidence:.2f}] -> {model.name}")
        response = mock_generate(model, query_text)

        self.stats["routed"] += 1
        self.stats["total_cost"] += response.cost
        self.stats["baseline_cost"] += (response.tokens_used / 1000) * self.models["large"].cost_per_1k
        return response

# Usage
router = LLMRouter(MODELS)

queries = [
    "What is the capital of France?",
    "Analyze this contract for liability clauses and suggest revisions",
    "Convert 100 degrees Celsius to Fahrenheit",
    "Design a microservices architecture for an e-commerce platform with 10M users",
    "Translate 'good morning' to Spanish",
]

for q in queries:
    response = router.handle(q)

savings = 1 - router.stats["total_cost"] / max(router.stats["baseline_cost"], 1e-9)
print(f"\n{router.stats['routed']} queries | routed cost ${router.stats['total_cost']:.6f}"
      f" vs always-large ${router.stats['baseline_cost']:.6f} | saved {savings:.0%}")

JavaScript

class ModelConfig {
  constructor(name, maxTokens, costPer1k, latencyMs) {
    this.name = name;
    this.maxTokens = maxTokens;
    this.costPer1k = costPer1k;
    this.latencyMs = latencyMs;
  }
}

const MODELS = {
  small:  new ModelConfig("gpt-4o-mini", 4096, 0.0006, 200),
  medium: new ModelConfig("gpt-4o",      8192, 0.005,  500),
  large:  new ModelConfig("o1",         16384, 0.015,  2000),
};

function classifyComplexity(text) {
  const lower = text.toLowerCase();
  const wordCount = text.split(" ").length;
  let score = 0;

  const complexPatterns = [
    /analyze|design|architect|compare|evaluate/,
    /debug|refactor|optimize|review/,
    /step.by.step|detailed|thorough/,
    /legal|medical|financial|security/,
  ];
  const simplePatterns = [
    /^\s*(what|who|when|where|is|are|can|do)\s/,
    /calculate|convert|format|translate/,
    /summarize|rewrite|paraphrase/,
  ];

  for (const p of complexPatterns) if (p.test(lower)) score += 2;
  for (const p of simplePatterns) if (p.test(lower)) score -= 2;

  if (wordCount > 100) score += 2;
  else if (wordCount < 20) score -= 1;

  if (score >= 2) return ["high", Math.min(0.5 + score * 0.15, 1.0)];
  if (score <= -2) return ["low", Math.min(0.5 - score * 0.15, 1.0)];
  return ["medium", 0.5];
}

function routeToModel(complexity) {
  return { low: "small", medium: "medium", high: "large" }[complexity] || "medium";
}

function mockGenerate(model, prompt) {
  const tokens = Math.min(Math.max(60, prompt.split(" ").length * 2), model.maxTokens);
  return {
    model: model.name,
    content: `[${model.name}] Response to: ${prompt.slice(0, 50)}...`,
    tokensUsed: tokens,
    cost: (tokens / 1000) * model.costPer1k,
  };
}

class LLMRouter {
  constructor(models) {
    this.models = models;
    this.stats = { routed: 0, totalCost: 0, baselineCost: 0 };
  }

  handle(queryText) {
    const [complexity, confidence] = classifyComplexity(queryText);
    const model = this.models[routeToModel(complexity)];
    console.log(`  [${complexity} @ ${confidence.toFixed(2)}] -> ${model.name}`);
    const response = mockGenerate(model, queryText);
    this.stats.routed++;
    this.stats.totalCost += response.cost;
    this.stats.baselineCost += (response.tokensUsed / 1000) * this.models.large.costPer1k;
    return response;
  }
}

// Usage
const router = new LLMRouter(MODELS);

const queries = [
  "What is the capital of France?",
  "Analyze this contract for liability clauses and suggest revisions",
  "Convert 100 degrees Celsius to Fahrenheit",
  "Design a microservices architecture for an e-commerce platform with 10M users",
  "Translate 'good morning' to Spanish",
];

for (const q of queries) router.handle(q);

const savings = 1 - router.stats.totalCost / Math.max(router.stats.baselineCost, 1e-9);
console.log(`\n${router.stats.routed} queries | routed cost $${router.stats.totalCost.toFixed(6)}`
  + ` vs always-large $${router.stats.baselineCost.toFixed(6)} | saved ${(savings * 100).toFixed(0)}%`);

A Java version of the same router, plus a runnable cascade demo, lives in the companion repository.

Explanation

The router runs in three steps:

  1. Classification. The classifier inspects the query and returns a level (low/medium/high) and ideally a confidence score. Rules-based heuristics are free and instant; embedding or model-based classifiers cost a little and catch what regex can’t.
  2. Routing. The level maps to a configured tier. The mapping table is policy, not code; it’s where you encode “this category always gets the big model”.
  3. Generation. The query goes to the selected model and the response flows back, along with the routing decision for your logs.

Three properties decide whether a router saves money or just adds a failure point:

The classifier is a ladder, not a choice. Rules → embeddings → small LLM is a progression in accuracy per unit of added latency, and you climb it only as far as the savings justify. Regex covers the obvious cases (“translate this”, “what is X”) for free; an embedding classifier adds ~5-20ms and handles paraphrase; a small LLM judge adds ~100-300ms and handles genuine ambiguity. Most production routers stop at embeddings: the jump to an LLM classifier only pays when the cost gap between tiers is large and queries are genuinely hard to bin.

The two error directions don’t cost the same. Under-routing (complex query → small model) produces a wrong or shallow answer the user may not notice, the worst kind of failure. Over-routing (simple query → large model) produces a correct answer at 10-30x the price: visible, measurable, recoverable. So thresholds should be biased: when the classifier is unsure, route up, or route small with a verification step. “When in doubt, spend a little more” is the safe default; the FAQ’s 40-70% savings figure survives conservative thresholds because most real traffic isn’t borderline.

A borderline classification is a quality signal, not noise. medium with confidence 0.5 is the classifier saying “I don’t know”. Treating it as a coin flip to medium loses information; treat it as the trigger for the cascade variant: try the small model, check the response, escalate if it’s thin. The structured function calling recipe composes well here: ask the classifier for {level, confidence, reason} as validated JSON instead of parsing free text.

Variants

VariantDescriptionUse Case
Embedding classifierCompare query embedding to category centroidsMore accurate than rules, ~5-20ms overhead
Small LLM classifierA cheap model classifies before routingHighest accuracy, ~100-300ms + small cost
Cascade with escalationTry small first, escalate on low confidenceSaves money without under-serving hard queries
Category-based routingRoute by task type (code, summary, translation)Models differ in strengths, not just size
Multi-objective routingScore cost + latency + quality togetherLatency-sensitive apps, SLA tiers

The cascade is the variant worth building once rules stop being enough. Route to the cheap tier, then apply a response check (length below a floor, a “I can’t help with that” match, a low self-reported confidence, or a cheap judge model asking “does this answer the question?”) and re-route the failures up one tier. It converts under-routing from a silent quality problem into a bounded cost: you pay for the small call plus the retry, but only on the minority of queries where it was wrong.

Category-based routing solves a different problem: not how hard the query is but what kind of query. Translation, code generation, and long-form summarization each have models that punch above their price; the classifier’s job changes from scoring difficulty to predicting intent, and per-category pools let you mix providers (the RouteLLM framework does exactly this).

What Works

  • Start with rules, measure, then upgrade. Regex heuristics are free and cover the obvious traffic; deploy them with logging first and let the misclassification data justify the embedding or LLM tier.
  • Log every routing decision with its reason. Level, confidence, chosen model, cost: you can’t tune thresholds you can’t see, and the log is how you prove the savings.
  • Bias thresholds toward the bigger model. Under-routing is the expensive error; a conservative bias costs a few percent of savings and prevents the silent-quality-degradation bug report.
  • Cache aggressively at the cheap tier. Simple queries repeat: “what are your hours” asked 400 times should hit the embedding cache, not even reach the router.
  • Track savings against an always-large baseline. The demo’s baseline_cost is the number that sells the pattern internally; without it you’re claiming savings you can’t show.
  • Re-evaluate on model releases. Tier boundaries shift as providers cut prices and ship new models: a routing table is a living config, not a decision you make once.

Common Mistakes

  • Routing everything to the expensive tier anyway. If your classifier sends >90% of traffic to large, the router is overhead, not savings: either the thresholds are broken or the traffic doesn’t justify a router.
  • Word count as the only signal. “Fix this bug” is 3 words; pasting a stack trace is 300. Length correlates weakly with difficulty, so combine signals or use a semantic classifier.
  • No escalation path. A misclassified complex query should escalate, not ship a shallow answer. Cascade or per-category confidence checks are the mitigation.
  • Classifiers that cost more than they save. An LLM-judge on every request adds latency and spend; if the classifier costs 15% of a large call, it needs to route really well to break even.
  • Treating the router as a reliability layer. Routing picks the cheapest adequate model; it doesn’t handle that model going down. Outages are a different pattern: pair routing with fallback, don’t conflate them.
  • Ignoring safety at the boundary. The router sees raw user input, so run input guardrails before classification, not after, so injection attempts never reach any model.

Advanced Solutions

The base router is one-shot and static. Production adds three capabilities:

Cascade with quality gates. Route cheap first, verify the response, escalate on failure; the verification is what makes under-routing safe to try:

class CascadeRouter(LLMRouter):
    TIERS = ["small", "medium", "large"]

    def _quality_ok(self, response: Response) -> bool:
        return response.tokens_used >= 30 and "I can't" not in response.content

    def handle(self, query_text: str) -> Response:
        complexity, confidence = classify_complexity(query_text)
        start = self.TIERS.index(route_to_model(complexity))
        if confidence < 0.7:
            start = max(start - 1, 0)  # unsure: start one tier lower, verify

        for tier in self.TIERS[start:]:
            response = mock_generate(self.models[tier], query_text)
            self.stats["routed"] += 1
            if self._quality_ok(response) or tier == "large":
                return response
            self.stats["escalated"] += 1
        return response

Learned routing. Logged decisions plus outcome feedback (thumbs, task success, judge scores) become training data: over time the classifier learns your actual distribution instead of generic difficulty. A bandit formulation (explore cheaper tiers on a fraction of traffic, exploit the best observed tier per category) automates the threshold tuning you’d otherwise do by hand — the RouteLLM paper formalizes this as learning to route from preference data.

Routing as one stage of a pipeline. In production the router rarely stands alone: guardrails sanitize input before classification (injection shouldn’t reach any tier), the embedding cache short-circuits repeated queries before the classifier runs, and a fallback chain wraps whichever model gets picked. Order matters: each layer before the classifier makes its job cheaper and safer.

Runnable versions of these implementations (including the Java router) live in the companion repository.

Frequently Asked Questions

How much cost can an LLM router actually save?

Typically 40-70% for apps with genuinely mixed query complexity. The math compounds: if 80% of queries route to a model that's 10-30x cheaper per token, savings scale with volume. Measure against an always-large baseline, not against your current bill; the baseline is what the alternative would have cost.

Should the classifier be a separate model?

For prototyping, no. Regex heuristics are free and cover the obvious cases. For production with real ambiguity, a small classifier (embeddings + cosine similarity, or a fine-tuned small model) earns its ~5-20ms. An LLM judge is only worth it when queries are hard to bin and the tier price gap is large.

What happens when the router misclassifies a complex query as simple?

The cheap model produces a shallow or wrong answer, the expensive kind of failure because it looks like a response. Mitigate with the cascade variant: response-quality checks (length floor, refusal match, judge model) that re-route failures up a tier. Bias thresholds toward bigger models so borderline queries err toward quality.

Can I route on user context instead of query text?

Yes, and sometimes you should: user tier, conversation history, or session metadata are legitimate routing signals. But keep complexity as the primary axis: a paid user asking "what's 2+2" doesn't need the frontier model, and routing purely on user tier recreates the cost problem with extra steps.

Does routing add meaningful latency?

Rules add microseconds. Embedding classification adds ~5-20ms (the embedding call is cheap and cacheable). An LLM classifier adds ~100-300ms, meaningful for interactive apps, which is why most production routers stop at embeddings or run the classifier in parallel with an optimistic cheap-model call.

How is this different from a fallback chain?

Routing is a cost and fit decision made before the call; fallback is a reliability decision made after a failure. They compose cleanly: router picks the tier, fallback handles that tier being down. Conflating them ("route to the next model if this one errors") works, but that's just a fallback chain wearing a router's name.