Model Routing & Cost/Latency

Send each request to the right model - not the biggest one

Most production traffic doesn't need your most expensive, slowest model. Model routing inspects each request and dispatches it to the cheapest model that can do the job well - using classifiers, cascades, semantic caches, and fallbacks. The payoff is dramatic cost and latency savings without sacrificing quality on the requests that actually need it.

Classifier routing Cascading / escalation Semantic caching Provider fallback
01 - What

What is model routing?

Model routing is the layer between your application and the model providers that decides which model handles each request. Instead of hard-wiring every call to one flagship model, a router assesses the incoming request - its difficulty, cost budget, and latency target - and picks from a fleet of models that trade off price, speed, and capability. The best routers make requests cheaper and faster on average while keeping quality where it matters.

๐Ÿงญ Assess (classify)

Score the request's difficulty and requirements - length, task type, required reasoning - before choosing a model.

๐ŸŽš๏ธ Dispatch (route)

Send simple requests to a small, cheap, fast model and hard ones to a larger, stronger model.

๐Ÿ›Ÿ Protect (fallback)

On error, rate-limit, or timeout, retry on another model or provider so a single outage never takes you down.

The core routing strategies

StrategyWhat it doesBest for
Classifier / predictiveAssess difficulty up front, then pick a model per requestMixed traffic with easy + hard queries
Cascade / escalationTry a cheap model, escalate only on low confidenceWhen most requests are easy but some aren't
Semantic cacheServe a stored answer for semantically similar queriesRepetitive, high-volume, FAQ-style traffic
Fallback routingSwitch provider on error, rate-limit, or timeoutReliability and multi-provider resilience
Rule / metadataRoute by tenant, region, tier, or data-sensitivityCompliance, SLAs, and cost tiers
Key mental model: routing is a bet. You trade a tiny bit of overhead (a classifier call, a cache lookup) for a much cheaper or faster path on the majority of requests. The router's job is to be right often enough that the savings dwarf the cost of being occasionally wrong - and to escalate gracefully when it is.
02 - Why

Why routing exists

Flagship models can cost 10โ€“30ร— more per token and run several times slower than small ones. When every request hits the biggest model, you overpay massively for the easy 80% of traffic - and users wait longer than they need to. Routing recovers that waste.

๐Ÿ’ธ Cuts cost dramatically

Serving simple queries from a small model or a cache - instead of a flagship - can slash spend by large multiples on high-volume traffic.

โšก Lowers latency

Small models and cache hits return in a fraction of the time. Users get faster answers on the requests that don't need deep reasoning.

๐ŸŽฏ Preserves quality where it counts

Hard requests still reach the strong model. You protect quality on the queries that matter instead of flattening everything to one tier.

๐Ÿ›Ÿ Improves reliability

Multi-provider fallback means a single provider's outage, rate-limit, or timeout doesn't break your product - traffic reroutes automatically.

In Plain Terms

Model routing explained with analogies

Same idea, four ways to picture it, so it clicks whoever you are.

๐ŸŽ“ For a student

Routing is like knowing when to use a calculator versus scratch paper. Easy arithmetic you do in your head; only the hard problems get the heavy tool. You match the effort to the question instead of reaching for the biggest tool every time.

๐Ÿ‘ฉโ€๐Ÿ’ป For a developer

It's a load balancer for intelligence. Just as you route cheap reads to a replica and heavy writes to the primary, the router sends easy prompts to a small model and hard ones to the flagship, with a fallback pool when one backend is down.

๐Ÿข For a professional

Think of a manager delegating work. Routine tasks go to a junior who is fast and inexpensive; only the tricky, high-stakes cases escalate to the senior expert. You reserve the pricey specialist for where it truly pays off.

๐Ÿš‘ Everyday version

A triage nurse at the ER sends each patient to the right level of care. Minor cuts go to a quick station; serious cases go straight to the specialist. Nobody wastes the surgeon's time on a scraped knee.

03 - How

How it works under the hood

A router sits in front of the model providers and juggles three concerns at once - the cost / latency / quality triangle. You can optimize any two, but tightening one usually pressures the others, so routing is about landing each request at the right point on that triangle.

๐Ÿ”บ The trade-off triangle

Cost, latency, and quality pull against each other. A cheap fast answer may be lower quality; a top-quality answer costs more and takes longer. Routing places each request where its SLA and budget allow.

๐Ÿ“ Measure, then set SLAs

Log cost, p50/p95 latency, and a quality score per route. Set a latency SLA and a per-request budget, then let the router optimize within those guardrails and alert when they're breached.

The router architecture at a glance

Architecture - the router inspects a request, checks the cache, then dispatches to the right model with fallback
flowchart LR
    Q["โ“ Request"] --> R{"๐Ÿงญ Router"}
    subgraph Fast["โšก Fast paths"]
        C[("๐ŸงŠ Semantic cache")]
        SM["๐Ÿฃ Small model"]
    end
    subgraph Strong["๐Ÿง  Strong paths"]
        LG["๐Ÿฆพ Large model"]
        FB["๐Ÿ›Ÿ Fallback provider"]
    end
    R --> C
    C -->|hit| ANS["โœ… Response"]
    C -->|miss| CL["๐Ÿ“Š Classify difficulty"]
    CL -->|easy| SM
    CL -->|hard| LG
    SM -->|low confidence| LG
    LG -->|error / timeout| FB
    SM --> ANS
    LG --> ANS
    FB --> ANS
        

Routing logic in pseudocode

def route(request):
    # 1. Semantic cache: serve similar past answers
    hit = cache.lookup(embed(request), threshold=0.92)
    if hit:
        return hit.answer

    # 2. Predictive routing: assess difficulty, pick a tier
    score = classifier.difficulty(request)      # 0.0 .. 1.0
    model = small_model if score < 0.5 else large_model

    # 3. Cascade: try cheap first, escalate on low confidence
    resp = call(model, request)
    if model is small_model and resp.confidence < 0.7:
        resp = call(large_model, request)       # escalate

    # 4. Fallback: on error / rate-limit / timeout, switch provider
    if resp.error:
        resp = call(fallback_provider, request)

    cache.store(embed(request), resp.answer)
    return resp.answer

Notice the ordering: cheapest checks first (cache), then a light classifier, then the cascade, with fallback wrapping everything. Each layer only pays for the next when it has to - that's what keeps average cost and latency low.

04 - Sequence Diagrams

Detailed sequence diagrams

Three views: a classifier dispatching to the right model, a cheap-first cascade with confidence-based escalation, and a semantic cache with provider fallback on failure.

Diagram 1 - Classifier routing: assess difficulty, then dispatch to the right model
sequenceDiagram
    autonumber
    participant U as ๐Ÿ‘ค User
    participant R as ๐Ÿงญ Router
    participant C as ๐Ÿ“Š Classifier
    participant S as ๐Ÿฃ Small model
    participant L as ๐Ÿง  Large model

    U->>R: Send request
    R->>C: Score difficulty
    C-->>R: score plus task type
    alt easy request
        R->>S: Dispatch to small model
        S-->>R: Fast cheap answer
    else hard request
        R->>L: Dispatch to large model
        L-->>R: High quality answer
    end
    R-->>U: Response plus route metadata
        
Diagram 2 - Cascade: cheap model first, confidence check, escalate when unsure
sequenceDiagram
    autonumber
    participant U as ๐Ÿ‘ค User
    participant R as ๐Ÿงญ Router
    participant S as ๐Ÿฃ Small model
    participant J as ๐Ÿ” Confidence check
    participant L as ๐Ÿง  Large model

    U->>R: Send request
    R->>S: Try cheap model first
    S-->>R: Draft answer plus signal
    R->>J: Evaluate confidence
    J-->>R: score
    alt confident enough
        R-->>U: Return cheap answer
    else low confidence
        R->>L: Escalate to strong model
        L-->>R: Higher quality answer
        R-->>U: Return escalated answer
    end
    Note over R,L: Only hard requests pay for the big model
        
Diagram 3 - Semantic cache hit/miss plus provider fallback on failure
sequenceDiagram
    autonumber
    participant U as ๐Ÿ‘ค User
    participant R as ๐Ÿงญ Router
    participant C as ๐ŸงŠ Semantic cache
    participant P as ๐ŸŸฃ Primary provider
    participant F as ๐Ÿ›Ÿ Fallback provider

    U->>R: Send request
    R->>C: Lookup similar query
    alt cache hit
        C-->>R: Stored answer
        R-->>U: Instant cached response
    else cache miss
        C-->>R: No match
        R->>P: Call primary provider
        alt provider healthy
            P-->>R: Answer
        else error or rate limit or timeout
            P-->>R: Failure
            R->>F: Retry on fallback
            F-->>R: Answer
        end
        R->>C: Store answer for reuse
        R-->>U: Fresh response
    end
        
05 - Step by Step

The 0 โ†’ 100 flow

From a raw request to a delivered response - every decision the router makes, in order.

00
Receive

Accept the request

A request arrives at the routing layer with its prompt, tenant, and any SLA or budget hints attached as metadata.

10
Normalize

Canonicalize & embed

Normalize the prompt and compute an embedding so it can be compared against the semantic cache and scored for difficulty.

20
Cache

Check the semantic cache

Look up semantically similar past queries. If one is close enough above the similarity threshold, serve its stored answer and skip the model entirely.

30
Classify

Assess difficulty

On a cache miss, a lightweight classifier scores the request - task type, reasoning depth, length - to predict which model tier can handle it.

40
Budget

Apply SLA & budget guardrails

Combine the difficulty score with the request's latency SLA and cost budget to choose a candidate model within the allowed envelope.

50
Dispatch

Route to the chosen model

Send easy requests to a small, cheap, fast model and hard ones straight to a stronger model. Metadata records the route taken.

60
Evaluate

Check the confidence signal

For cascade routes, inspect the cheap model's confidence - self-reported score, logprobs, or a cheap judge - to decide if the answer is good enough.

70
Escalate

Promote hard cases

If confidence is below the threshold, escalate to a larger model. Only the genuinely hard requests pay the premium price and latency.

80
Fallback

Handle failures

On error, rate-limit, or timeout, retry on an alternate model or provider with backoff so a single outage never surfaces to the user.

90
Store

Cache the result

Write the final answer back to the semantic cache so the next similar query is served instantly and cheaply.

100
Deliver

Return & measure

Return the response with route metadata, and log cost, latency, and quality per route so dashboards and evals can tune thresholds over time.

Common Pitfalls

Pitfalls & anti-patterns

Routing saves money right up until it quietly breaks quality or reliability. These are the usual culprits.

๐ŸŽฏ Misclassified hard queries

A router that underestimates difficulty sends genuinely hard requests to the small model and never escalates. The result looks cheap on the dashboard but underserves exactly the users who needed the strong model most.

๐Ÿชœ Cascade latency stacking

Too many escalation hops mean a request runs the small model, fails a confidence check, then reruns the large model - paying for both and doubling latency. Deep cascades can be slower and costlier than going big up front.

๐ŸงŠ Stale or overbroad cache

A semantic cache with a loose similarity threshold returns a stored answer for a subtly different question, or serves outdated content after the source changed. Wrong-but-fast is worse than slow-but-right.

๐Ÿšซ No fallback on outage

Routing to a single provider with no alternate means one outage, rate-limit, or timeout takes the whole product down. Cost optimization is meaningless if the service isn't available.

๐Ÿ“‰ Silently dropping quality

Optimizing purely for cost, with no quality signal in the loop, degrades answers so gradually nobody notices until users churn. Cheap traffic that quietly regresses is a hidden tax on trust.

๐ŸŒ The router as the bottleneck

A heavy classifier, embedding call, or cache lookup on every request adds its own latency and cost. If the routing overhead rivals the savings, the layer is defeating its own purpose.

How to Measure

How to measure routing

Track cost and latency alongside quality, so savings never come at the expense of the answers.

MetricWhat it tells youGood sign
Cost per requestAverage spend per call across the whole route mixLow: routing is capturing the savings
p50 / p95 latencyTypical and tail response time, including routing overheadWithin your SLA at both percentiles
Quality / win-rate vs always-big-modelHow often routed answers match or beat sending everything to the flagshipHigh: little quality lost for the savings
Escalation rateShare of requests the cascade promotes to a stronger modelStable and moderate: not too eager, not starving hard queries
Cache hit rateFraction of requests served from the semantic cacheHigh without wrong-answer complaints
Fallback / error rateHow often the primary path fails and reroutesLow, with fallbacks catching what does fail
Rule of thumb: never watch cost or latency without a quality metric beside them. If cost per request drops but win-rate slips, the router is trading answers for savings; tune thresholds until both hold before pushing cost lower.
06 - Case Studies

Real-world case studies

Three representative patterns showing routing in production-style use.

๐Ÿ’ฌ

1 ยท High-volume chatbot cutting cost

Pattern: cache + classifier routing

A consumer chatbot handles millions of messages a day, most of them simple greetings, FAQs, and short follow-ups.

  • A semantic cache absorbs repetitive questions, serving a large share of traffic with no model call at all.
  • A difficulty classifier sends casual chit-chat to a small model and reserves the flagship for complex, multi-step requests.
  • Route mix and quality are monitored so thresholds can be retuned as traffic patterns shift.
โœ… Outcome: The majority of requests never touch the expensive model, driving a large drop in cost per conversation while flagship quality is preserved for the hard tail.
๐Ÿท๏ธ

2 ยท Bulk classification job optimizing latency

Pattern: cascade with escalation

A data team must label millions of documents overnight within a fixed batch window.

  • A fast small model labels every document first, emitting a confidence signal per item.
  • Only low-confidence items escalate to a stronger model, keeping the strong model's slow, costly calls to a minimum.
  • High parallelism plus the cheap-first cascade keeps end-to-end throughput inside the batch window.
โœ… Outcome: The job finishes well within its window at a fraction of the cost of running everything through the large model, with accuracy held up by targeted escalation.
๐Ÿ›ก๏ธ

3 ยท Multi-provider reliability setup

Pattern: fallback routing across providers

A business-critical product cannot afford downtime when a single model provider degrades.

  • A primary provider serves normal traffic; health, error rate, and latency are tracked continuously.
  • On errors, rate-limits, or timeouts, requests reroute to an equivalent model on a second provider with backoff.
  • A circuit breaker sheds load from an unhealthy provider until it recovers, then restores normal routing.
โœ… Outcome: Provider outages and rate-limit spikes become invisible to users, with the product staying available by seamlessly shifting traffic across providers.
07 - Future

Where routing is heading

Routing is evolving from static rules into learned, adaptive systems that optimize cost, latency, and quality in real time.

๐Ÿง  Learned routers

Models trained on real traffic that predict the cheapest model likely to satisfy each request - replacing hand-tuned rules with data-driven policies.

๐ŸŽ›๏ธ Budget-aware routing

Routers that optimize against an explicit cost ceiling and latency SLA per request, spending the budget only where quality demands it.

๐ŸงŠ Smarter semantic caching

Caches that reason about freshness and partial reuse - serving cached fragments and refreshing only what has changed.

๐Ÿ”€ Cross-provider abstraction

Unified gateways that treat many providers as one fleet, load-balancing and failing over transparently across vendors.

๐Ÿ“ˆ Continuous route evals

Online quality scoring per route so the system detects drift and re-tunes thresholds automatically instead of on a manual cadence.

๐Ÿค Speculative & hybrid decoding

Small models drafting for large ones, blurring the line between routing and generation to cut latency without losing quality.

Bottom line: routing is how you make LLM products economical at scale - matching each request to the cheapest model that meets its bar, and staying reliable when providers wobble. As models proliferate and prices shift, the routing layer becomes the control plane for cost, latency, and quality.