Sub topic 14
Route requests and cascade between models
This chapter assumes you can call an LLM API from Python, that you have a small evaluation set (see the chapter on protecting quality), and that you have a cost and latency baseline. Routing and cascading only work if you can measure whether the cheaper path is good enough.
Why one model for everything wastes money
Most applications receive a mix of requests. Some are easy, such as classifying a short message or reformatting a field. Others are hard, such as multi-step reasoning over a long document. If you send everything to your strongest model, you pay strong-model prices for easy work. If you send everything to a small model, the hard requests fail.
Two patterns split the traffic:
- Routing picks one model for each request before any model runs.
- Cascading runs a cheaper model first, checks the result, and escalates to a stronger model only if the check fails.
Both rely on the same fact: the price gap between model tiers is often large, so even a modest share of traffic moved to the cheaper tier lowers the average cost per request.
Routing: decide before calling
A router looks at the request and chooses a model. It costs little because it runs once and does not generate an answer. Common signals:
- Task type. Extraction, classification, and formatting go to a small model. Open-ended analysis goes to a larger one.
- Input size. Very long inputs may need a model with a larger context window.
- Customer tier or feature. A free-tier feature may be capped to the cheap model.
- A classifier. A small model or a simple trained classifier labels the request as easy or hard.
The simplest router is a rule table. Start there before adding a model-based router.
ROUTES = {
"classify": "small-model",
"extract": "small-model",
"summarize": "medium-model",
"analyze": "large-model",
}
def route(task_type: str, input_tokens: int) -> str:
model = ROUTES.get(task_type, "large-model")
if input_tokens > 100_000:
return "large-model"
return model
print(route("classify", 300))
print(route("analyze", 2_000))
print(route("unknown_task", 500))Notice the default. An unknown task falls back to the large model. A wrong default to the small model fails quietly, while a wrong default to the large model only costs money. The model names here are placeholders for whatever your provider offers.
Model-based routers
When task type is not known in advance, a small model can label the request. Its prompt asks for one word, such as easy or hard, and you cap the output at a few tokens. This adds a call, so it only pays off when the saving on the routed request exceeds the router's own cost and added latency. A router that costs 5% of a large-model call and moves 60% of traffic to a model that is 10 times cheaper is clearly worthwhile. A router that costs as much as a small-model answer is not.
Cascading: try cheap, verify, escalate
A cascade does not need to predict difficulty. It lets the cheap model try, then asks a check function whether the draft is acceptable.
def answer_with_cascade(question, cheap_fn, strong_fn, is_good_enough):
draft = cheap_fn(question)
if is_good_enough(question, draft):
return draft
return strong_fn(question)The strong model runs only for requests the check rejects. The cost of the check matters as much as the cost of the cheap model.
Choosing the check
The check decides whether a cascade is safe. Options, from cheapest and most reliable to most expensive and least reliable:
- Deterministic validation. Does the output parse as JSON, match a schema, fall in an allowed set of labels, or pass a regular expression? This is free and exact. Use it whenever the task allows.
- Verifiable constraints. For code, run the tests. For extraction, confirm the extracted value appears in the source text.
- Confidence signals. Some APIs return token log probabilities. Low probability on the key tokens suggests uncertainty. These signals are uneven across models and tasks, so calibrate them against your evaluation set before trusting them.
- A judge model. A second model grades the draft. This works for open-ended text but adds cost and its own errors. Use a model no weaker than the one that produced the draft, and test the judge against labeled examples.
A model asked "are you sure?" about its own answer is a poor check. It tends to agree with itself.
The cost math of a cascade
Escalated requests pay twice: once for the cheap attempt and once for the strong call. Let c be the cheap call cost, s the strong call cost, k the check cost, and p the share of requests that escalate. The expected cost per request is:
c + k + p × s
Compare that to always using the strong model, which costs s. The cascade wins when c + k + p × s < s.
def cascade_cost(cheap, strong, check, escalation_rate):
return cheap + check + escalation_rate * strong
strong = 1.00
for p in (0.1, 0.3, 0.6, 0.9):
expected = cascade_cost(cheap=0.10, strong=strong, check=0.01, escalation_rate=p)
print(f"escalation {p:.0%}: {expected:.2f} vs {strong:.2f}")With these numbers, the cascade saves money until the escalation rate nears 89%. In practice, set a safer threshold. Quality risk, extra engineering, and latency also count against it.
Latency cost
Cost is only half of the trade-off. An escalated request waits for the cheap model, the check, and then the strong model, so its latency is the sum of all three. If 30% of requests escalate, your p50 latency may fall while your p95 latency rises. Measure both percentiles. If the product needs predictable latency, prefer routing, which adds only the router's delay. Streaming does not help a cascade much, because you cannot show the draft to the user before you know whether you will discard it.
Failure modes
- Silent quality loss. The check accepts weak drafts. Guard against this by running the cascade over your evaluation set and comparing its scores to the strong model alone.
- Misrouted hard requests. A router sends difficult requests to a small model and nothing catches the failure. Sample routed traffic and score it regularly.
- Drift. Provider model updates, new prompt versions, and changing user behavior shift escalation rates. Track the escalation rate in production. A sudden rise means cost is climbing. A sudden drop may mean the check has become too lenient.
- Inconsistent behavior. Two models may format answers differently or follow instructions differently. Users may see different styles depending on the path. Keep prompts compatible and validate output format on both paths.
- Overfitting the router. A rule table tuned to a small test set may not match real traffic. Refresh the evaluation set with recent production examples.
Choosing between them
| Situation | Better fit |
|---|---|
| Task type is known and stable | Rule-based routing |
| Difficulty varies within one task | Cascade |
| A cheap exact check exists (schema, tests) | Cascade |
| Only an expensive judge can verify quality | Routing, or a cascade after measuring judge cost |
| Latency must be predictable | Routing |
| Most requests are easy and the strong model is much pricier | Either, and cascade gains most |
You can combine them. Route by task type first, then cascade inside the tasks where difficulty varies.
Measuring before you ship
Use the evaluation set to compare three setups: always strong, always cheap, and your router or cascade. Record for each one:
- Quality score on the evaluation set.
- Average cost per request, including check and router calls.
- p50 and p95 latency.
- For cascades, the escalation rate.
Accept the new design only if quality stays within the margin you set earlier and the cost or latency gain is real. Then log the chosen model and the escalation flag with every production request, so the monitoring described in the next chapter can detect drift.
import time
def logged_cascade(question, cheap_fn, strong_fn, is_good_enough, log):
start = time.perf_counter()
draft = cheap_fn(question)
escalated = not is_good_enough(question, draft)
answer = strong_fn(question) if escalated else draft
log.append({
"escalated": escalated,
"latency_s": time.perf_counter() - start,
})
return answer
log = []
logged_cascade(
"2+2?",
cheap_fn=lambda q: "4",
strong_fn=lambda q: "4",
is_good_enough=lambda q, d: d.strip().isdigit(),
log=log,
)
print(log)Exercise
Your strong model costs 1.00 per request. The cheap model costs 0.08, the check costs 0.02, and 40% of requests escalate. What is the expected cost per request for the cascade, and does it beat always using the strong model? What happens to p95 latency?
Show answer
Expected cost is 0.08 + 0.02 + 0.40 × 1.00 = 0.50, which is half the cost of always using the strong model, so the cascade wins on cost. The p95 latency is likely to rise, because the 40% of escalated requests wait for the cheap call, the check, and the strong call in sequence. Measure p95 on the evaluation set before shipping.
Exercise
A cascade uses the same cheap model to answer "Is this answer correct?" about its own draft. Why is this a weak check, and what would you use instead for a task that extracts an invoice number from a document?
Show answer
A model tends to agree with its own output, so it will accept many wrong drafts. For invoice extraction, use a deterministic check: confirm the extracted number appears in the source text and matches the expected format (for example with a regular expression). Escalate to the strong model only when that check fails.