Sub topic 11
Common pitfalls
This chapter lists the mistakes that most often make a routed system cost more, answer worse, or fail more often than a single model would. It assumes you have read the earlier chapters. You should know how rule-based routers, confidence-based cascades, threshold sweeps, and fallbacks work, and be comfortable with basic Python and per-token pricing. Each pitfall below has a symptom, a cause, and a fix.
Why routing fails quietly
A routed system rarely crashes when the policy is wrong. It returns answers, and the answers are a bit worse or a bit more expensive than you expected. Nothing raises an exception, so the problem shows up weeks later in a bill or a complaint.
Most pitfalls come from one of three sources:
- A signal the router trusts does not mean what you assumed.
- A number was measured on one population and applied to another.
- A failure path was written for one error and meets another.
The diagram shows where these problems enter a cascade.
Pitfall 1: Trusting confidence scores that are not calibrated
A confidence score is calibrated when answers scored 0.8 are right about 80% of the time. Many scores are not. Self-reported scores ("rate your confidence from 0 to 1") tend to cluster near the top. Token probabilities depend on the model, the prompt format, and the task. A score of 0.8 from one model does not match a 0.8 from another.
The cascade from earlier uses a fixed threshold=0.8. If the small model reports 0.9 for nearly everything, almost no request escalates. Quality drops, and the dashboards still look healthy because nothing is failing.
Check calibration before you trust a threshold. Group labeled records by confidence and compare each group's confidence to its actual accuracy:
def calibration_table(records, n_bins=5):
# Each record: {"confidence": float in [0, 1], "small_correct": bool}
bins = [[] for _ in range(n_bins)]
for r in records:
index = min(int(r["confidence"] * n_bins), n_bins - 1)
bins[index].append(r)
rows = []
for i, group in enumerate(bins):
if not group:
continue
low, high = i / n_bins, (i + 1) / n_bins
accuracy = sum(int(r["small_correct"]) for r in group) / len(group)
rows.append((low, high, len(group), accuracy))
return rows
sample = [
{"confidence": 0.95, "small_correct": True},
{"confidence": 0.93, "small_correct": False},
{"confidence": 0.91, "small_correct": False},
{"confidence": 0.55, "small_correct": True},
{"confidence": 0.35, "small_correct": False},
]
for low, high, count, accuracy in calibration_table(sample):
print(f"{low:.1f}-{high:.1f}: n={count}, accuracy={accuracy:.2f}")Look for a score that does not rise with accuracy, or for a high bucket whose accuracy is far below its confidence. In either case the score is a weak routing signal. Use a different signal, such as a verifier check, agreement across several samples, or a learned classifier. Or pick the threshold from measured accuracy and ignore the score's face value.
Pitfall 2: Ignoring what a cascade costs when it escalates
A cascade always pays for the small model. Every escalated request then pays for the large model as well. The expected cost function from earlier shows this:
def expected_cost_cascade(frac_answered_by_small, cost_small, cost_large):
return cost_small + (1 - frac_answered_by_small) * cost_largeIf too few requests stay with the small model, the cascade costs more than calling the large model directly. The break-even point is simple. The cascade is cheaper only when the fraction answered by the small model is greater than cost_small / cost_large.
def cascade_break_even(cost_small, cost_large):
# Minimum fraction the small model must answer for the cascade to beat large-only.
return cost_small / cost_large
print(cascade_break_even(0.2, 1.0)) # 0.2
print(cascade_break_even(0.5, 1.0)) # 0.5When the small model costs 20% of the large one, the cascade breaks even if the small model answers 20% of requests. When it costs 50%, it must answer half of them. Compute this number before you build the cascade. If your realistic answer rate is near it, the savings are too small to justify the added complexity.
Two other costs are easy to miss:
- Latency adds up. An escalated request waits for the small call, then the large call. Its latency can be well over the large model alone. If you have a latency target, check the 95th percentile of escalated requests, not the average.
- Input tokens are billed twice. A long prompt is sent to both models on escalation. For long-context workloads, this can erase most of the savings.
Pitfall 3: Rules that match words instead of difficulty
The keyword router from earlier sends a prompt to the large model if it contains words like "analyze" or is longer than 4000 characters. Those are proxies for difficulty, and proxies fail in both directions.
| Prompt | Rule decision | Actual need |
|---|---|---|
| "Analyze this sentence: 'I love pizza.' Positive or negative?" | large | small is enough |
| A 200-character request to find a subtle race condition | small | large |
| A 6000-character pasted log with "summarize in one line" | large | small is enough |
The first and third cases waste money. The second hurts quality, and that cost is invisible because the answer looks plausible.
A second problem is drift. Users learn what works and rephrase. Product teams add new request types. A rule set that was accurate at launch gets worse as traffic changes.
Treat each rule as a hypothesis. Log which rule fired for each request. Sample requests from each rule and check whether the decision was right. Measure the miss rate, meaning hard requests that went to the small model, separately from the waste rate, meaning easy requests that went to the large model. The two have different costs. If rules grow past a dozen or so, or if you keep adding exceptions, consider moving to a classifier trained on labeled examples.
Pitfall 4: Tuning a threshold on the wrong sample
The sweep function from the evaluation chapter replays labeled records at several thresholds. It is only as good as the records. Common mistakes:
- Unrepresentative sample. If the labeled set was collected from easy support tickets and production includes coding questions, the chosen threshold will be too low for production.
- Too few records. With 50 records, the difference between 0.78 and 0.82 accuracy is noise. Pick a size where a few records changing label does not move the result.
- Tuning and reporting on the same data. Choosing the best threshold on a sample and then quoting that sample's accuracy overstates quality. Hold out a second sample for the final number.
- Stale labels. If either model is upgraded,
small_correctandlarge_correctmay change. Re-label or at least re-run the evaluation. - Averages that hide segments. Overall accuracy of 92% can hide 70% on one request type. Compute the sweep per segment, such as per language, product area, or prompt length bucket.
Here is a segment-aware version of the sweep. It assumes each record also has a segment field.
from collections import defaultdict
def sweep_by_segment(records, thresholds):
# Each record: {"segment": str, "confidence": float,
# "small_correct": bool, "large_correct": bool}
by_segment = defaultdict(list)
for r in records:
by_segment[r["segment"]].append(r)
report = {}
for segment, group in by_segment.items():
rows = []
for t in thresholds:
correct = 0
escalated = 0
for r in group:
if r["confidence"] >= t:
correct += int(r["small_correct"])
else:
escalated += 1
correct += int(r["large_correct"])
rows.append((t, correct / len(group), escalated / len(group)))
report[segment] = rows
return reportIf one segment needs a much higher threshold than the others, give it its own threshold, or route it straight to the large model.
Pitfall 5: Judging quality with a weak or biased label
The sweep needs small_correct and large_correct. Where those come from matters.
- If the large model's answer is used as ground truth, the small model can only ever match it, and the large model scores 100% by definition. You are measuring agreement, not correctness.
- If a language model grades the answers, it may prefer longer or more confident text, or text from its own model family. Spot-check its grades against human labels on a sample.
- If correctness is a binary label for open-ended tasks, partial answers get forced into right or wrong, which shifts the apparent best threshold.
Use ground-truth labels from humans or from a checkable source, such as unit tests, known answers, or schema validation. Where you must use a model grader, validate it against a human-labeled subset and report the agreement rate.
Pitfall 6: Fallbacks that only handle one failure
The call_with_fallback function from earlier catches only TimeoutError:
def call_with_fallback(prompt, primary, secondary):
try:
return primary(prompt)
except TimeoutError:
return secondary(prompt)A real API can also fail with rate limits, server errors, malformed responses, or content-policy refusals. Those exceptions pass straight through, and the user sees a failure even though a healthy secondary exists. Catching everything is also wrong. A bug in your own code, such as a KeyError, should not trigger a model switch that hides it.
The version below handles a defined set of transient errors, bounds the retries, and reports which model answered. The exception classes here are placeholders. Replace them with your client's actual types.
class RateLimitError(Exception):
pass
class ServerError(Exception):
pass
TRANSIENT = (TimeoutError, RateLimitError, ServerError)
def call_with_fallback(prompt, primary, secondary):
try:
return primary(prompt), "primary"
except TRANSIENT:
# One fallback attempt only. Do not loop back to the primary.
return secondary(prompt), "secondary"
def flaky_primary(prompt):
raise RateLimitError("429")
def steady_secondary(prompt):
return "ok: " + prompt
print(call_with_fallback("hello", flaky_primary, steady_secondary))Keep three more points in mind:
- Retry storms. If every request retries on failure while the provider is overloaded, you add load to the system that is already failing. Cap retries, use backoff, and consider a circuit breaker that skips the primary for a short period after repeated failures.
- Silent quality change. Falling back from the large model to the small one lowers answer quality. Record it, and decide whether some request types should fail loudly instead.
- Cost surprises. If the fallback is the more expensive model, an outage on the cheap model raises your spend. Set an alert on it.
Pitfall 7: Treating two models as interchangeable
Small and large models can differ in output format, instruction-following, context length, and refusal behavior. Routing assumes either model can take the same request. If it cannot, you get bugs that only appear on one path.
- A prompt tuned for the large model may produce malformed JSON on the small one. Validate the output on both paths, and count validation failures per model.
- A request that fits the large model's context window may exceed the small one's. Check token counts before routing.
- A system prompt that relies on subtle phrasing may behave differently. Test the same prompt set against both models before you launch.
- Tool-calling or structured output may be supported differently. Confirm that each model handles every tool your application offers.
One useful habit is to run a fixed regression set through both models whenever you change a prompt or upgrade a model version.
Pitfall 8: Launching without monitoring the policy itself
A routing policy is a model of your traffic, and traffic changes. Monitoring only overall latency and spend misses the signals that show the policy going stale. Track these per day or week:
- The share of requests sent to each model, and the escalation rate for cascades.
- The distribution of confidence scores. A shift can mean the traffic changed or the model was updated.
- Quality on a small, regularly refreshed labeled sample, in each segment.
- The share of requests answered by a fallback.
- Cost per request, split into small-model, large-model, and wasted escalation spend.
When the escalation rate moves sharply, find the cause before changing the threshold. A provider silently updating a model, a new customer segment, and a prompt change can each produce the same graph with different fixes.
A short checklist
Before you ship a routing policy, you should be able to answer yes to each of these:
- Have you checked that confidence scores track accuracy, using a calibration table?
- Have you computed the break-even fraction for a cascade and compared it with your measured small-model answer rate?
- Is the threshold chosen on one labeled sample and reported on another?
- Do you have per-segment results, not just a global average?
- Do labels come from ground truth or a validated grader?
- Does the fallback handle every transient error type, with bounded retries?
- Have you tested both models on the same prompts and output validators?
- Are escalation rate, confidence distribution, and fallback share on a dashboard with alerts?
Exercise
A cascade's small model costs 0.4 per request and the large model costs 1.0. In production, the small model keeps its answer for 35% of requests. Is the cascade cheaper than always calling the large model? Give the expected cost per request and the break-even fraction.
Show answer
The expected cascade cost is 0.4 + (1 - 0.35) * 1.0 = 1.05 per request. Calling the large model alone costs 1.0, so the cascade is more expensive. The break-even fraction is 0.4 / 1.0 = 0.4, and the small model answers only 35%, which is below it. Either the small model must keep at least 40% of requests, or a router that sends clearly hard requests straight to the large model may do better.
Exercise
A cascade's small model reports a confidence of at least 0.9 on 95% of its answers, but a calibration table shows accuracy of 71% for that group. What is wrong, and what are two ways to fix it?
Show answer
The confidence score is not calibrated. It is high even when the answer is often wrong, so a threshold of 0.8 almost never escalates. Two fixes are to choose the threshold from measured accuracy on a labeled sample (for example by sweeping much higher thresholds), and to replace or supplement the score with a better signal, such as a verifier check, agreement across several samples, or a learned classifier.
Exercise
Why is except TimeoutError alone a weak fallback, and why is a bare except Exception also a bad choice?
Show answer
Timeouts are only one transient failure. Rate limits and server errors pass through and reach the user even though the secondary model is healthy. A bare except Exception also catches bugs in your own code, such as a KeyError or a bad parameter, and hides them behind a model switch. Catch a defined set of transient error types, limit retries to one fallback attempt, and log which model answered.