TL;DR
- A router is a front desk. It reads each request and sends it to the cheapest place that can answer well.
- Use three tiers, cheapest first. Rules check exact facts. A small router matches the request to example sentences. An LLM handles whatever is left.
- Local steps are fast; remote steps are slow. On my laptop, a small local classifier took 1.87 ms at the median. One call to a remote embedding service took 250.6 ms in a published benchmark.
- Watch the slow requests, not the average. The slowest 1 in 100 requests is what users feel.
- Let the router say “I don’t know”. When it is unsure, send the request to the LLM instead of guessing.
The Front Desk Problem
Picture a hospital front desk. Most visitors need a simple answer, such as “pharmacy, second door on the left”. A few need a specialist. A good desk sends each person to the right place in seconds, and it never sends a broken arm to the pharmacy.
An LLM gateway has the same problem. Some requests are cheap to answer. A plain translation engine handles “translate this button label” well. Other requests need a large model that takes seconds and costs real money. The Google Translate article ends with a box labeled “Routing policy: length, domain, SLA”. It looks like an if statement. It is the part that decides whether a request costs 5 ms or 5 seconds.
This article opens that box. You will see one small router you can run, learn where the time goes, and learn how to tell when the router is wrong.
Two terms first:
- p50 and p99 are speed percentiles. p50 is the median: half the requests are faster. p99 is the slow end: 99 out of 100 requests finish before this time. Users remember the slow ones, so p99 is the number to watch.
- A budget is the time you allow the routing step. This article uses 100 ms, which is a fraction of what an LLM call takes.
Three Tiers, Cheapest First
Route each request through three tiers. Stop at the first tier that can decide.
| Tier | What it checks | Cost | Example |
|---|---|---|---|
| 1. Rules | Exact facts: tenant, length, language | Almost free | ”Tenant has a locked glossary” |
| 2. Router | Closest match to example sentences | Milliseconds | ”Translate this button label” |
| 3. LLM | Everything else | Seconds | ”Who should I vote for?” |
Tier 1 is plain code. A reviewer can read it in a minute. Tier 2 is where the two other tools from the wider field fit in. A classifier is a small model trained to pick one label from a fixed list. An embedding router turns the request and your example sentences into lists of numbers, then picks the closest match. “Embedding” just means “a list of numbers that captures meaning”. Tier 3 is the expensive model you were trying to protect.
Choose the tool per kind of request, not per product:
- Hard guards (tenant, login, input length): rules. Reviewers can read them.
- Fuzzy requests with stable labels and lots of labeled data: a classifier. You train it once.
- Fuzzy requests with few examples that change often: an embedding router. Adding a route means adding sentences, not retraining.
A Router You Can Run
The code below uses only the Python standard library, so you can paste it into a file and run it. The tier-2 “router” counts shared words. That is a toy. A real system uses an embedding model in the same place, and the structure stays the same.
import re
# Tier 1: rules. Cheap, exact, easy to read.
def rules(query: str, tenant: str) -> str | None:
if tenant == "locked-glossary":
return "nmt_with_glossary"
if len(query) > 4000:
return "llm_translate"
return None
# Tier 2: a tiny "router". Real systems use an embedding model here.
# This toy version counts shared words with example sentences.
ROUTES = {
"nmt_fast": ["translate this button label", "translate this word", "how do you say this"],
"llm_general": ["who should I vote for", "explain this contract clause"],
}
THRESHOLD = 0.5 # below this, the router abstains
def score(query: str, example: str) -> float:
q = set(re.findall(r"\w+", query.lower()))
e = set(re.findall(r"\w+", example.lower()))
return len(q & e) / max(len(e), 1)
def router(query: str) -> str | None:
best_route, best = None, 0.0
for route, examples in ROUTES.items():
s = max(score(query, ex) for ex in examples)
if s > best:
best_route, best = route, s
return best_route if best >= THRESHOLD else None
# Tier 3: the fallback. It is always the safe default.
def route(query: str, tenant: str) -> str:
hit = rules(query, tenant)
if hit:
return hit
hit = router(query)
if hit:
return hit
return "llm_general"
if __name__ == "__main__":
cases = [
("anything", "locked-glossary", "nmt_with_glossary"),
("x" * 5000, "acme", "llm_translate"),
("Translate this button label to German", "acme", "nmt_fast"),
("Who should I vote for?", "acme", "llm_general"),
("Tell me a joke about tensors", "acme", "llm_general"),
]
for query, tenant, expected in cases:
got = route(query, tenant)
print(f"{got:20} expected={expected:20} {'OK' if got == expected else 'MISMATCH'}")
Run it with python3 router.py. All five cases print OK. Look at what each line teaches:
- Order matters. Rules run first because they are free and certain. A tenant with a locked glossary never reaches the router.
- Abstaining is a feature. “Tell me a joke about tensors” shares no words with any example, so the router abstains and the request falls through to the LLM. A wrong guess here would send a joke to a translation engine.
- The fallback is explicit. Every path ends in a named route. No request disappears.
So what: you can build the whole decision in one screen of code. Start there before you add a model.
Where the Milliseconds Go
Here are real numbers so you can see the gap. They come from two sources, and I label each one.
My measurements (Apple M2 Max laptop, one request at a time, n=500 per row, warm):
| Step | p50 (ms) | p99 (ms) |
|---|---|---|
| Plain rules (length check, regex) | under 0.01 | under 0.01 |
| Small classifier, INT8 quantized | 1.87 | 2.90 |
| Local embedding router | 4.43 | 19.22 |
Published benchmark (Semantic Router project, n=20, one provider, undated):
| Step | p50 (ms) |
|---|---|
| Local index lookup | 0.1 |
| One remote embedding call | 250.6 |
| Hosted decision model (LLM-based router) | 351.4 |
Two things stand out. Local steps stay in single-digit milliseconds. The remote call alone takes more than twice the whole 100 ms budget. The benchmark does not split network time from provider processing, so treat its exact numbers as one example, not a constant.
Real traffic also arrives in bursts. In my test with 16 requests running at once, the classifier’s median rose from 1.8 ms to 11.3 ms, and its p99 rose from 2.8 ms to 80.8 ms. The slow end grew much faster than the middle. I did not find out why, and I did not tune the thread count. The lesson holds anyway: measure the slow end under your real load, not in a quiet test.
So what: keep the router local, and measure p99 with concurrency before you trust the 100 ms budget.
Knowing When the Router Is Wrong
A router that is wrong fails quietly. It sends a request to the wrong place, and the logs still say 200. Track three things:
- Speed. One duration per request, so you can compare p99 with your budget.
- Decisions. How often the router abstains, and how often it falls back to the LLM. A sudden change in either is a warning sign.
- Correctness. Sample some routed requests and have a person check them. Speed numbers cannot tell you a route was wrong.
Record the speed with a histogram, which counts how many requests fall into each time bucket. The bucket edges matter. The default edges in many libraries are too coarse around 100 ms, so you cannot read p99 precisely there. Use finer edges near your budget, and keep buckets above it for slow tails.
from opentelemetry import metrics
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.export import InMemoryMetricReader
from opentelemetry.sdk.metrics.view import ExplicitBucketHistogramAggregation, View
# Seconds. Fine steps around the 100 ms budget, finite buckets above it.
BUCKETS_S = [0.001, 0.002, 0.005, 0.01, 0.02, 0.05, 0.075, 0.1, 0.2, 0.5, 1, 2, 5]
reader = InMemoryMetricReader() # use an OTLP or Prometheus exporter in production
metrics.set_meter_provider(MeterProvider(
metric_readers=[reader],
views=[View(instrument_name="router.request.duration",
aggregation=ExplicitBucketHistogramAggregation(BUCKETS_S))],
))
request_duration = metrics.get_meter("router").create_histogram("router.request.duration", unit="s")
Then, in your request handler, record the time around route(...). I ran this setup with an in-memory reader to confirm the custom buckets appear. The bucket list is my suggestion, not a standard.
So what: one histogram per request, plus a count of decisions, tells you most of what you need on day one.
Common Mistakes
- A remote call in the first tier by default. The remote embedding call alone was 250.6 ms at the median in the benchmark. Start local. Add a remote call only after you measure its slow end.
- Trusting vendor numbers. Vendor speed claims come from the vendor’s own machines. Check them against your own traffic.
- Confusing “same answer” with “right answer”. Two versions of a router agreeing with each other proves nothing about correctness. You need human-labeled examples.
- Unpinned dependencies. The Semantic Router release notes report that a LiteLLM release on PyPI contained malware on 2026-10-21, and the project now excludes it. Pin your versions and keep a lockfile.
Going Deeper
Once the three-tier path works, these topics matter. Each one has more detail in the sources.
- Calibration. A raw similarity score means something different for every encoder, so “0.8” does not mean “80% sure”. Calibration learns a map from raw scores to real chances. Fit it on held-out queries, never on the example sentences themselves. In the Semantic Router project’s own calibration example, accuracy on 39 held-out queries rose from 66.67% to 84.62% after fitting and adding a 0.5 threshold. That example shows the mechanism, not a general benchmark.
- Choosing the threshold. Price the two mistakes. A wrong route often costs more than an abstention that sends a request to the LLM. That is my judgment, not a measurement, so choose the threshold from your own costs, using held-out data.
- Overload. When the router is busy, decide ahead of time what happens: skip the router and use the default, wait in a short bounded queue, or reject. Never skip the rules that enforce policy. vLLM Semantic Router’s v0.4 docs describe an
admissionsetting per model that does this, but its behaviour is version-specific. - Testing a cascade against a simpler design. A three-tier design only earns its extra hop if it beats one well-tuned classifier at the same p99. Test both on labeled queries you did not tune on.
What I Would Do Next
Copy the example, replace the toy word-matching with a real embedding model, and label a few hundred real queries. Measure p99 at your real concurrency. Then decide whether the third tier needs its own router at all.
For the decision-model tier and how thinking budgets interact with routing, see Do We Need Deep Thinking?. For flag-rate and threshold pitfalls in guardrails, see Agent Risk Flags Are a Setting.
Sources
- Semantic Router latency.json: remote embedding, local index, decision-model latency. Undated, n=20, one provider.
- Semantic Router calibration notebook: held-out calibration example, 66.67% to 84.62%. Undated.
- Semantic Router releases: LiteLLM exclusion (2026-10-22 release note, incident 2026-10-21). Read 2026-11-11.
- vLLM Semantic Router: router latency on CPU: sequential p99 105.9 ms, 2026-10-05, historical.
- vLLM Semantic Router v0.4 operations and troubleshooting: admission configuration. Undated.
- JsonLogic and Adding Operations: rule model and its limits. Undated.
- TypeSafe: Introducing System One Models and Jev: 2026-09-15, vendor-reported.
- OpenTelemetry GenAI metrics conventions: status Development. Undated.
- Own measurements: Apple M2 Max, 2026-11-11, Python 3.11.13,
semantic-router1.1.2,fastembed0.9.1,onnxruntime1.31.1. Figures are not portable to other CPUs. The runnable example was executed on 2026-11-11 with Python 3.