Sub topic 10
Monitoring a Routed System Over Time
Assumed background
This chapter assumes you have read the earlier chapters on rule-based routing, cascades, and evaluating a threshold. You should be comfortable with basic Python and with the idea that a routing policy has a threshold, an escalation rate, and an expected cost per request. Here the policy is already deployed, and the question is how you find out that it has stopped working well.
Why a routing policy decays
You chose your routing rules and threshold using a labeled sample from some past period. That sample describes the traffic, the models, and the confidence scores of that period. Four things change after launch:
- Traffic changes. Users start asking different things. A new feature, a marketing campaign, or a new customer can shift the mix toward harder or easier prompts.
- Models change. A provider updates a hosted model, or you swap one tier for a cheaper one. The same prompt can now get a different answer and a different confidence score.
- Confidence drifts. A confidence score is only meaningful relative to the model that produced it. If the small model becomes more or less sure of itself, a fixed threshold of 0.8 no longer sends the same share of traffic to the large model.
- Prices and limits change. A price cut or a new rate limit changes which routing policy is cheapest.
None of these raises an exception. The system keeps returning answers, so the failure shows up as a slow rise in cost or a slow fall in quality. Monitoring is how you notice it.
What to measure
Group your metrics by the question they answer.
| Question | Metric | How to compute it |
|---|---|---|
| Is traffic changing? | Prompt length distribution, share of requests matching each rule | Log `prompt_chars` and the rule that fired |
| Is the router behaving as before? | Share routed to small, escalation rate | Count routes per window |
| Is the small model's confidence shifting? | Mean confidence, share of requests near the threshold | Log the confidence score for every cascade request |
| Is it costing what we expected? | Realized cost per request vs. expected cost | Sum logged cost, compare with the cost formula |
| Is it fast enough? | p50 and p95 latency per route | Log latency per request, compute percentiles per route |
| Are failures handled? | Timeout rate, fallback rate, error rate | Log `fell_back` and exception types |
| Are the answers good? | Estimated accuracy of small-answered requests | Labeled or graded sample (see below) |
The first six come from logs and cost nothing extra. The last one needs ground truth, which is why it gets its own section.
Track latency per route, not only overall. An escalated cascade request pays for the small call and then the large call, so its latency is roughly the sum of the two. The overall average can look fine while the escalated requests, which are often the hardest ones, are slow.
Log one record per request
Every other technique in this chapter depends on a consistent log. Write one structured record per request, with enough fields to recompute any metric later. Include the policy version and the model versions, so that a change in behavior can be tied to a change in configuration.
The script below defines the record, a rolling window that summarizes the most recent requests, and a comparison against a baseline. It runs as written and ends with a small simulation.
import json
import random
from collections import deque
from dataclasses import dataclass, asdict
from typing import Optional
@dataclass
class RouteRecord:
ts: float
route: str # "small" or "large"
escalated: bool # True if the small model ran first and was not trusted
confidence: Optional[float] # None when no confidence was computed
fell_back: bool # True if a timeout or error triggered the fallback
latency_s: float
cost: float
prompt_chars: int
policy_version: str
def to_json_line(rec: RouteRecord) -> str:
return json.dumps(asdict(rec))
class Window:
"""Keeps the most recent `size` records and summarizes them."""
def __init__(self, size: int = 1000):
self.records = deque(maxlen=size)
def add(self, rec: RouteRecord) -> None:
self.records.append(rec)
def summary(self) -> Optional[dict]:
n = len(self.records)
if n == 0:
return None
latencies = sorted(r.latency_s for r in self.records)
confs = [r.confidence for r in self.records if r.confidence is not None]
return {
"n": n,
"escalation_rate": sum(r.escalated for r in self.records) / n,
"fallback_rate": sum(r.fell_back for r in self.records) / n,
"mean_confidence": sum(confs) / len(confs) if confs else None,
"mean_cost": sum(r.cost for r in self.records) / n,
"p95_latency_s": latencies[min(n - 1, int(0.95 * n))],
}
def check_drift(current: dict, baseline: dict, tolerances: dict) -> list:
"""Return a message for every metric that moved more than its tolerance."""
alerts = []
for name, tol in tolerances.items():
if current.get(name) is None or baseline.get(name) is None:
continue
diff = current[name] - baseline[name]
if abs(diff) > tol:
alerts.append(f"{name}: baseline {baseline[name]:.3f}, now {current[name]:.3f}")
return alerts
def simulate(n: int, escalation_prob: float, rng: random.Random) -> Window:
window = Window(size=n)
for i in range(n):
escalated = rng.random() < escalation_prob
window.add(RouteRecord(
ts=float(i),
route="large" if escalated else "small",
escalated=escalated,
confidence=rng.uniform(0.4, 0.7) if escalated else rng.uniform(0.8, 1.0),
fell_back=rng.random() < 0.01,
latency_s=rng.uniform(1.5, 3.0) if escalated else rng.uniform(0.3, 0.8),
cost=0.012 if escalated else 0.002,
prompt_chars=rng.randint(50, 3000),
policy_version="v3",
))
return window
if __name__ == "__main__":
rng = random.Random(0)
baseline = simulate(2000, escalation_prob=0.25, rng=rng).summary()
today = simulate(2000, escalation_prob=0.45, rng=rng).summary()
tolerances = {"escalation_rate": 0.05, "mean_cost": 0.001, "mean_confidence": 0.05}
for alert in check_drift(today, baseline, tolerances):
print("ALERT", alert)The simulated escalation rate jumps from 25% to 45%, so the script prints alerts for the escalation rate, the mean cost, and the mean confidence.
Choosing a baseline and tolerances
Take the baseline from the labeled sample you used to pick the threshold, or from the first week or two of stable production traffic. Set each tolerance wider than normal fluctuation. If the escalation rate moves between 22% and 28% on an ordinary day, a tolerance of 0.01 will page someone every morning. Look at a few weeks of history before you set alert limits, and compare windows of the same length and the same time of day when traffic has a daily cycle.
Reading the signals
A single alert rarely names its own cause. The combinations below are a starting point for diagnosis.
| Pattern | Likely cause | First thing to check |
|---|---|---|
| Escalation rate up, mean confidence down, prompt lengths unchanged | Small model got worse, or the topic mix got harder | Model version in logs, a sample of recent prompts |
| Escalation rate up, prompt lengths up | Traffic shifted toward long or complex requests | Distribution of `prompt_chars` and rule hits |
| Escalation rate down, mean confidence up, accuracy sample down | Small model is more confident but not more correct | Graded sample (see next section) |
| Fallback rate up, latency p95 up | Provider slowness or rate limiting | Timeout rate per provider |
| Cost up, escalation rate flat | Price change, or longer outputs | Per-token price and output token counts |
| Router sends far more traffic to large, small share falls | A rule marker now matches common text | Which rule fired most often |
The third row matters most. Confidence-based alerts only detect that the score changed. They cannot tell you whether the answers are still correct, because the score is the thing that might have drifted. You need a check that does not depend on the confidence score.
Estimating quality in production
Production traffic has no labels. You can still get a usable estimate of quality by sampling a small share of requests and grading them. Grading can be human review, an automatic check where the task has a verifiable answer, or a comparison against the large model's answer.
Sample by hashing the request ID, not by calling a random number generator. A hash gives the same decision for the same request every time, so retries and replays do not change the sample.
import hashlib
import math
def in_sample(request_id: str, rate: float = 0.02) -> bool:
digest = hashlib.sha256(request_id.encode("utf-8")).digest()
value = int.from_bytes(digest[:8], "big") / 2**64
return value < rate
def wilson_interval(correct: int, n: int, z: float = 1.96):
"""95% confidence interval for a proportion."""
if n == 0:
return (0.0, 1.0)
p = correct / n
denom = 1 + z**2 / n
center = (p + z**2 / (2 * n)) / denom
margin = z * math.sqrt(p * (1 - p) / n + z**2 / (4 * n**2)) / denom
return (center - margin, center + margin)
if __name__ == "__main__":
ids = [f"req-{i}" for i in range(10000)]
sampled = [i for i in ids if in_sample(i, rate=0.02)]
print(len(sampled), "requests sampled")
low, high = wilson_interval(correct=171, n=200)
print(f"accuracy between {low:.3f} and {high:.3f}")Report an interval, not a single number. With 200 graded requests, a measured accuracy of 85.5% is consistent with a true value anywhere from about 80% to 90%. A drop from 88% to 86% on that sample is noise. A drop from 88% to 78% is not.
Sample from two groups, and keep them separate:
- Requests the small model answered. These estimate the accuracy your users actually received from the small tier. If this number falls below your target, the threshold is too low or the small model has degraded.
- Requests that were escalated. For a slice of these, also run the small model's answer through grading. If the small answer would have been correct most of the time, you are paying for the large model without need, and the threshold is too high.
Sampling only the first group finds quality problems but never finds wasted spend. Sampling both lets you rerun the threshold sweep from the evaluation chapter on fresh data.
Tracking cost against the formula
You already have formulas for the expected cost of a cascade and of a router. Monitoring turns them into a check. Each window, compute the fraction answered by the small model, put it into the formula, and compare the result with the realized mean cost from the logs.
If the two disagree, something outside the formula is happening. Common causes are fallbacks that call a second model, retries that bill twice, output lengths that differ between tiers, and prices that changed. The formula tells you what the cost should be given the escalation rate, and the gap tells you how much comes from other causes.
Also keep a running comparison against the all-large baseline: what the same traffic would have cost if every request went to the large model. The routing system exists to beat that number. If the savings shrink toward zero, the router is adding complexity and latency without paying for itself.
The monitoring loop
Monitoring is useful only if it feeds changes back into the policy. The cycle below is the one to build.
Each step has a concrete output. After a deploy, record a new baseline for the new policy version. Otherwise the old baseline will keep firing alerts about a change you made on purpose.
Changing the policy safely
When monitoring tells you to change the threshold or a rule, treat the change as a release:
- Version the policy. The
policy_versionfield in the log lets you split any metric by version and see the effect of each change. - Replay before you ship. Logged requests with graded outcomes can be run through the new policy offline, as in the earlier threshold sweep. This catches obvious mistakes before any user sees them.
- Roll out to a slice. Send 5% to 10% of traffic to the new version and compare both the cost and quality metrics against the rest. Use the same hash-based assignment as for sampling, so each request stays on one version.
- Keep a rollback. Store the previous version's configuration, so reverting is a configuration change and not a code change.
Common monitoring mistakes
- Alerting on the average only. An average escalation rate can stay flat while one customer's traffic escalates 90% of the time. Break metrics down by customer, task type, or rule when you have enough volume.
- Trusting confidence as quality. Mean confidence rising is not good news until a graded sample agrees.
- Not logging model versions. When a provider silently updates a model, the only evidence is a change in your metrics. Without the version in the log, you cannot match them.
- Windows too small. A window of 50 requests gives a noisy escalation rate and constant false alarms. Choose a size where a normal day stays inside the tolerance.
- Forgetting the feedback loop. If you retrain a classifier router on its own routing decisions, it learns only about requests it already sent to a given tier. Keep a random slice of traffic that gets graded regardless of the route, so training data is not biased by the policy itself.
- Logging prompts without care. Prompt text may contain personal data. Log lengths, rule hits, and request IDs by default, and store text only where your data policy allows it.
Exercise
Over a week, your cascade's mean confidence rises from 0.82 to 0.90, and the escalation rate falls from 25% to 12%. Cost per request drops. A graded sample of 200 small-answered requests shows accuracy of 76%, compared with 88% a month ago. What is the most likely explanation, and what do you do first?
Show answer
The small model is more confident without being more correct, for example after a provider update. Because the confidence score changed, it no longer separates good answers from bad ones, so fewer requests escalate and the answers sent to users are worse. Confirm using the logged model version, then re-run the threshold sweep on fresh labeled data. Probably raise the threshold, and consider a different confidence estimate. Record a new baseline after deploying.
Exercise
A monitoring window of 1,000 requests shows 270 escalations. The baseline escalation rate is 25% with a tolerance of 0.05. Does it alert? If the small model costs 0.002 and the large model 0.012 per request, what is the expected cascade cost per request at this window's rate?
Show answer
The escalation rate is 270 / 1000 = 0.27. The difference from the baseline is 0.02, which is below 0.05, so there is no alert. The fraction answered by the small model is 0.73. Expected cost = costsmall + (1 - 0.73) * costlarge = 0.002 + 0.27 * 0.012 = 0.00524 per request.