In short
An LLM router decides which model handles each request, so easy requests go to a small, fast model and hard ones go to a stronger, slower one. Routers range from fixed rules by task type, through classifiers, embedding similarity and learned routers, to cascades that try a small model first and escalate when its answer looks unreliable. Fallbacks are the other half: on timeouts, overload and rate limits, a client retries with backoff and then moves to another model or provider, while telling apart the errors that a retry can fix from the ones it cannot.
Key points
- Route to trade quality against latency and spend: most traffic rarely needs the largest model, and some of it truly does.
- Rules are the simplest router; classifiers, embedding similarity and learned routers decide before calling a model; cascades decide after seeing a cheap answer.
- A cascade is only as good as its confidence signal. Calibrate the threshold on labeled data, not on a number the model writes about itself.
- Retry timeouts, 5xx and rate-limit 429s with exponential backoff and jitter, honor retry-after, and never retry quota, billing or authentication errors.
- Prompts are not portable by default: tool and schema formats differ between providers, so keep one internal format and an adapter per provider.
- Evaluate a router as a curve of quality against the share of traffic sent to the strong model, and trace every route decision and fallback.
Why route requests between models
Most applications that call a language model send it a mix of work. A support assistant answers "where is my order" a thousand times for every request that needs careful reasoning over a long policy. Sending all of it to the largest model pays the top rate in latency and spend for answers a small model gets right, and sending all of it to a small model fails the hard cases. A router sits between the application and the models and makes that choice per request.
Three things are in tension, and a router trades them explicitly:
- Quality: the share of answers that are correct, complete and in the right format. Larger models are usually better on hard inputs, and often no better on easy ones.
- Latency: time to first token and total time. Smaller models are usually faster, and a router that adds its own model call adds its own delay.
- Spend: providers bill by input and output tokens, and the rate per token differs widely between model sizes and providers, a gap the FrugalGPT authors build their whole method on.
Routing also covers availability. A model can be overloaded, rate-limited, deprecated or down, and the same layer that chooses the best model can choose the next best one when the first fails. The rest of this post covers both halves: choosing a model, and surviving when the choice is unavailable. For the wider set of levers on spend, see how to reduce LLM costs.
Routing strategies compared
| Strategy | How it decides | Added latency | What it needs | Weak spot |
|---|---|---|---|---|
| Rules by task type | Fixed mapping from endpoint, feature, tenant, input size or modality to a model | None | Knowing your traffic | Coarse: every request of a type gets the same model, easy or hard |
| Classifier router | A small model predicts the category or difficulty of the request, and a table maps that to a model | One small model call | Labeled examples of requests | Labels drift as traffic and models change |
| Semantic routing | Embeds the request and picks the route whose example requests are most similar | One embedding call and a vector lookup | A handful of example requests per route | Similar topic does not mean similar difficulty |
| Learned router | A model trained to predict whether the strong model would beat the weak one on this request | One router call | Preference or correctness data across models | Tied to the models it was trained on; needs retraining or checking when they change |
| Cascade | Calls the small model first and escalates when a check on its answer fails | The small model's full latency on every escalated request | A reliable confidence signal and a threshold | Slow and wasteful when many requests escalate |
Rules are the right first router. If summaries of long documents go to a long-context model, requests with images to a vision model and a background classification job to the smallest model that passes its evals, much of the benefit is already there, with nothing to train and nothing to explain.
Classifier and semantic routers decide before any answer exists. A classifier is trained on labeled requests, for example "lookup", "rewrite", "multi-step reasoning", and its label picks the model. Semantic routing skips training: each route keeps a few example requests, their embeddings are stored, and an incoming request goes to the route with the highest cosine similarity above a threshold, or to a default route below it. It is fast and easy to extend, and it is best at deciding what kind of request this is; it is weaker at deciding how hard it is, because two requests on the same topic can need very different models. For how the vectors behave, see text embeddings explained.
Learned routers predict the outcome directly. RouteLLM (Ong and colleagues, 2024) trains routers that choose between one strong and one weak model, using human preference data, mainly 80,000 Chatbot Arena battles, augmented with benchmark labels and judged comparisons. The router estimates the probability that the strong model wins on a given query and sends the query to the strong model when that probability is above a threshold, so one number trades quality against spend. The paper compares four router designs: similarity-weighted ranking, matrix factorization, a BERT classifier and a causal LLM classifier. The authors report cutting spend by more than half in some cases without lowering response quality, and routers that kept their performance when routing between models that were not in their training data.
Cascades: try the small model first, escalate when unsure
A cascade decides after seeing an answer. FrugalGPT (Chen, Zaharia and Zou, 2023) sends a query through an ordered list of models. After each answer, a scoring function rates its reliability from 0 to 1; if the score clears that stage's threshold the answer is returned, and otherwise the next model is called. In the paper the scorer is a small regression model, DistilBERT in their case study, trained to predict whether an answer is correct, and the order of models and the thresholds are learned by optimizing expected quality under a spending budget across 12 APIs from 5 providers. The authors report that the learned cascade can match the best single model's performance at a much lower spend, or improve accuracy over GPT-4 by 4 percent at the same spend.
The structure is a loop over (model, threshold) pairs. The stub models below stand in for real calls; the small one is sure of short questions and unsure of long ones:
from collections import namedtuple
Answer = namedtuple('Answer', 'text confidence') # confidence: a scorer, log-probs or a verifier
def small(q): # stub: sure of short factual questions, unsure of long ones
return Answer(f'small: {q}', 0.93 if len(q.split()) <= 6 else 0.42)
def large(q): # stub: slower and more capable
return Answer(f'large: {q}', 0.97)
CASCADE = [(small, 0.80), (large, 0.0)] # (model, accept threshold); the last always accepts
def route(q):
tried = []
for model, threshold in CASCADE:
a = model(q)
tried.append(f'{model.__name__} {a.confidence:.2f}')
if a.confidence >= threshold and a.text.strip():
return a, tried
for q in ['What is the capital of Peru?', 'Is 7919 prime?',
'Compare the termination clauses in these two supplier contracts']:
a, tried = route(q)
print(f'{" -> ".join(tried):24} {q[:34]}')
# small 0.93 What is the capital of Peru?
# small 0.93 Is 7919 prime?
# small 0.42 -> large 0.97 Compare the termination clauses inOutput from running it is shown at the end. Everything depends on the confidence signal, and there are several, from weakest to strongest:
- A confidence number the model writes about itself. Easy to get and not a calibrated probability; treat it as a weak hint.
- Token log-probabilities, where the API returns them: low average probability on the answer tokens is a usable warning sign for short answers such as labels and extracted values.
- A trained scorer, as in FrugalGPT: a small model that takes the query and the answer and predicts correctness, trained on your own labeled outputs.
- A verifier: checks that do not need a model, such as JSON that parses against the schema, code that compiles and passes tests, a cited passage that exists, or two samples that agree.
The cost of a cascade is latency on the escalated requests: they pay for the small model's answer and then the large model's. If a third of traffic escalates, that third is slower than it would have been with an up-front router. Cascades suit traffic where most requests are easy and the check is cheap, and up-front routing suits traffic where the hard requests can be spotted from the input alone. Many systems combine the two: rules or a classifier pick a tier, and a verifier inside the tier escalates the failures.
Fallbacks on errors and timeouts
A fallback chain is an ordered list of models or providers to try when a call fails. The design question is which failures deserve another try on the same provider, which should move on at once, and which should stop and alert someone. The two largest providers document their errors in similar terms:
| Signal | What it usually means | What to do |
|---|---|---|
| Timeout or dropped connection | The provider is slow or the network failed; the request may still be running | Retry once with backoff, then fall back. Stream long outputs so a timeout means silence, not a long answer |
| 429 with a retry-after header | A rate limit, or a ramp limit after a sharp rise in traffic | Wait at least that long before retrying, or send this request to the next provider now |
| 429 for quota, billing or a spend cap | An account limit. OpenAI says retrying these will not restore access; Anthropic's spend-cap 429 carries no retry-after | Do not retry. Fall back and alert a person |
| 500, 502, 503, and Anthropic's 529 | A server error or temporary overload | Retry with exponential backoff and jitter, then fall back |
| 400 or 413 | The request is invalid or too large for this model | Do not retry it unchanged. A fallback with different limits may accept it, but fix the cause |
| 401 or 403 | Key, permission or region problem | Do not retry. Fall back if another provider is set up, and alert a person |
A chain that applies those rules, with a timeout per provider, a bounded number of retries and a log of every attempt:
type Provider = { name: string; timeoutMs: number; retries: number;
call: (prompt: string, signal: AbortSignal) => Promise<string> };
class ProviderError extends Error {
status: number; retryAfterS: number;
constructor(status: number, retryAfterS = 0) { super(`HTTP ${status}`); this.status = status; this.retryAfterS = retryAfterS; }
}
const RETRY_SAME = new Set([408, 429, 500, 502, 503, 504, 529]); // transient: back off, try again
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
export async function complete(prompt: string, chain: Provider[]) {
const log: string[] = [];
for (const p of chain) {
for (let attempt = 0; attempt <= p.retries; attempt++) {
try {
const text = await p.call(prompt, AbortSignal.timeout(p.timeoutMs));
return { provider: p.name, text, log };
} catch (e) {
const err = e instanceof ProviderError ? e : new ProviderError(0); // 0 = timeout or network
log.push(`${p.name}#${attempt} ${err.status || 'timeout'}`);
if (err.status && !RETRY_SAME.has(err.status)) break; // auth, quota, bad request: move on
if (attempt === p.retries) break;
const backoff = 250 * 2 ** attempt * (0.5 + Math.random()); // exponential, with jitter
await sleep(err.retryAfterS ? err.retryAfterS * 1000 : backoff);
}
}
}
throw new Error(`all providers failed: ${log.join(', ')}`);
}The call function wraps a provider SDK and throws ProviderError with the HTTP status and the retry-after value; anything else, including the abort from AbortSignal.timeout, is treated as a timeout. Several details matter in practice:
- Count retries across layers. Anthropic's documentation says its SDK already retries connection errors, 429s and 5xx twice by default with exponential backoff, honoring
retry-after. Wrapping that in your own loop of three multiplies the attempts; turn one layer off. - Give the whole request a deadline as well as each attempt, so a chain of slow providers cannot exceed what the user will wait.
- Add a circuit breaker. After repeated failures, skip a provider for a cooldown period instead of paying its timeout on every request, then let one probe request through to test recovery.
- Decide what happens mid-stream. Anthropic notes that an error can arrive after a 200 response has started streaming. If tokens have already reached the user, a fallback means restarting the answer, which the interface has to handle.
- Hedging, sending a second request to another provider when the first is slow, cuts tail latency at the price of paying for both. Use it only for short, latency-critical calls.
Rate limits and 429 handling
Rate limits are the most common failure in a busy LLM application, and they are not one thing. OpenAI measures requests and tokens per minute and per day, and images per minute, at organization and project level. Anthropic measures requests per minute, input tokens per minute and output tokens per minute per model class, enforces them with a token bucket that refills continuously rather than resetting each minute, and adds ramp limits that can return a 429 after a sharp rise in traffic even below the stated limits. Both return headers with the limit, the remaining capacity and the reset time, and a retry-after header on many 429s.
The client-side rules follow from the documentation:
- Read the error code, not only the status. OpenAI's guide separates retryable rate limits from quota and billing 429s, and Anthropic gives its spend-cap and ramp-limit 429s their own error codes.
- Honor
retry-afterwhen it is present, and add jitter so many clients do not retry at the same instant. - Without
retry-after, back off exponentially with jitter, and cap both the number of attempts and the total time. - Do not hammer. OpenAI notes that unsuccessful requests count toward the per-minute limit, so fast retries make the problem worse.
- Shape traffic before it fails: track the remaining-tokens headers, queue background work behind interactive work, and ramp up batch jobs gradually.
- Spread load deliberately. A second provider, region or model class has its own limits, so a router can send overflow there before the first one starts returning 429s.
A client-side limiter that mirrors the provider's limits, usually a token bucket per model counting both requests and estimated tokens, keeps most 429s from happening at all. The mechanics of token buckets, sliding windows and distributed counters are in rate limiter system design.
Keeping prompts portable across models
A fallback is useless if the request it receives only works on the primary model. Prompts tuned for one model often degrade on another, and the structured parts of a request differ in format between providers:
- Tool definitions: OpenAI function tools describe their arguments under
parameters, while Anthropic tools useinput_schema, and the shapes of tool calls and tool results in the conversation differ too. - Structured outputs: both providers accept a JSON Schema and constrain the output to it, but each supports a different subset. OpenAI requires every field to be listed in
required, emulates optional fields with a union type, and requiresadditionalProperties: falseon every object. Anthropic also requiresadditionalProperties: false, and its documentation lists numeric constraints such asminimumand string length constraints as unsupported. - Model features such as prefilled assistant turns, reasoning settings and forced tool choice are supported on some models and rejected with a 400 on others.
The usual remedy is one internal request format: messages, tool definitions and an output schema written once, plus a thin adapter per provider that translates them and maps errors back into one set of codes. Keep schemas inside the subset that every model in the chain accepts, and enforce anything outside it, such as numeric bounds, in your own validator after the response. Each fallback model also needs its own pass through the evals: a prompt that works on the primary may need a different instruction or example on the backup. How providers enforce schemas during generation is covered in constrained decoding and structured outputs, and what happens when a model in the chain is retired is covered in AI model deprecation.
Evaluating a router
A router is a model of its own and needs its own evaluation. Its output is not one score but a curve: answer quality against the share of requests sent to the strong model. The RouteLLM paper reports routers this way, comparing them with a random router that sends the same share of traffic to the strong model; on MT Bench the authors report that their matrix factorization router needed half as many GPT-4 calls as the random router to close half of the quality gap between the two models, a score 95 percent of GPT-4's.
- Collect a few hundred real requests that cover the traffic mix, including the hard and the rare ones.
- Run every request through every candidate model once and score each answer with the checks you trust: exact match, a rubric, unit tests or a judge model calibrated against human labels.
- Replay routing policies offline against those stored answers. Each threshold gives one point: quality, the share of traffic per model, and the expected latency.
- Compare against the baselines: always the strong model, always the weak one, and a random split at the same share. A router that does not beat the random split is not routing.
- Pick the threshold from the curve, then check the slices: a router that is fine on average can fail one customer, one language or one task type.
- Re-run the whole evaluation whenever a model in the pool changes, because thresholds tuned on one model's confidence do not carry over to the next.
Before switching live traffic, run the router in shadow mode: log the decision it would make while every request still goes to the current model, and compare. Put the offline replay into CI so a prompt, threshold or model change that lowers routed quality fails the build; see AI agent evals in CI.
Observability for routing and fallbacks
When routing goes wrong, it goes wrong quietly: answers get slightly worse, or slower, and nothing errors. Record every decision on the request's trace:
- The route chosen and why: the rule name, the classifier label, the similarity score, the router probability or the cascade confidence.
- Every attempt: provider, model, status or timeout, latency, retries and whether a fallback served the answer.
- Tokens in and out per attempt, so spend can be attributed to routes.
- A quality signal per route: sampled human review, judge scores or downstream outcomes such as a user retrying the question.
From those, a few metrics tell most of the story: escalation rate per route, fallback rate and 429 rate per provider, p95 latency per route, and quality per route over time. A jump in fallback rate is often the first sign that a provider is degrading; a creeping escalation rate usually means traffic has shifted or a model was updated. For spans, attributes and sampling, see LLM observability and tracing.
If you are building an AI agent or assistant that has to stay fast and available across models and providers, see our AI agent development service: the code lives in your GitHub from day one, AI-assisted work is reviewed by an engineer, and the founders are on the calls.
Sources
Checked when this post was written.
- Chen, Zaharia and Zou, FrugalGPT: How to Use Large Language Models While Reducing Cost and Improving Performance (arXiv, 2023)
- Ong et al., RouteLLM: Learning to Route LLMs with Preference Data (arXiv, 2024)
- OpenAI API documentation: Error codes
- OpenAI API documentation: Rate limits
- OpenAI API documentation: Structured outputs
- Claude API documentation: Errors
- Claude API documentation: Rate limits
- Claude API documentation: Structured outputs