Sub topic 5
Choosing metrics and guardrails
This chapter assumes you can read short Python snippets, you know metrics such as precision, recall, and p95 latency, and you understand what a proportion is. Shadow, canary, and A/B rollouts all end in the same question: did the candidate model do well enough to keep going? Metrics and guardrails are how you answer that with numbers you chose before the rollout began.
Three layers of metrics
A model in production is judged at three layers. Each layer fails in a different way and is noticed at a different speed.
| Layer | Examples | How fast it reacts | What it catches |
|---|---|---|---|
| System | error rate, timeouts, p95 and p99 latency, CPU and memory, cost per 1,000 requests | seconds to minutes | crashes, slow inference, bad resource sizing |
| Model | score distribution, null or out-of-range feature rate, prediction agreement with stable, precision and recall when labels exist | minutes to weeks, depending on labels | broken features, drift, a model that behaves differently from the one you tested |
| Business | conversion, fraud losses, revenue per session, support tickets, retention | hours to months | a model that is "correct" but does not help the product |
Each layer can look healthy while another fails. A model with 100% availability and a 90 ms p95 can still approve fraud, because the system layer says nothing about prediction quality. A model with excellent offline AUC can raise the checkout abandonment rate, because the model layer says nothing about user behavior. You need at least one metric per layer for any rollout that matters.
Goal, guardrail, and diagnostic metrics
Separately from the layers, each metric has a role in the decision.
- Goal metric (also called the primary or success metric). The one number the candidate is supposed to improve, such as fraud recall at a fixed false-positive rate or click-through rate. Pick one. If you pick five, you will find at least one that moved in your favor by chance.
- Guardrail metric. A number that must not get worse, even if the goal metric improves. Guardrails encode "do no harm": latency, error rate, cost, fairness across segments, complaint rate.
- Diagnostic metric. A number you read to understand why the goal or a guardrail moved, such as per-feature null rates or score histograms. Diagnostics explain. They do not gate.
The distinction matters because guardrails and goals are tested differently. A goal needs evidence of improvement, which takes a significance test and a sample size (see the later chapters on statistical testing and A/B tests). A guardrail only needs evidence that the candidate has not crossed a limit, so it is often a simple threshold check.
Writing guardrail thresholds
A threshold needs four decisions: a direction, a size, a baseline, and a minimum sample.
Direction. For errors and latency, lower is better. For approval rate or conversion, higher is usually better. Say which, so the check does not fire on improvements.
Size. Choose the smallest change that you would act on, not the smallest change you can measure. The canary gate in the spine allows an absolute error-rate increase of 0.005 and a p95 latency ratio of 1.10. Absolute limits suit rates that sit near zero, where a ratio is unstable: going from 0.001 to 0.002 is "double" but harmless. Ratio limits suit quantities with a natural scale, such as latency.
Baseline. Compare the candidate to the stable model at the same time, not to last week's numbers. Traffic mix, time of day, and upstream incidents move metrics for both versions together. A fixed historical baseline will blame the candidate for a bad Monday.
Minimum sample. A guardrail computed on 40 requests is noise. Set a minimum request count before the check can pass or fail, and return "wait" until it is reached.
The following code implements all four decisions. It returns one of three outcomes: wait, advance, or rollback.
from dataclasses import dataclass
@dataclass(frozen=True)
class Guardrail:
metric: str
mode: str # "abs": allowed absolute change; "ratio": allowed multiple of stable
limit: float
higher_is_better: bool = False
def evaluate(stable, candidate, guardrails, min_requests=2000):
if candidate["requests"] < min_requests:
return "wait", []
violations = []
for g in guardrails:
s, c = stable[g.metric], candidate[g.metric]
if g.higher_is_better:
floor = s - g.limit if g.mode == "abs" else s * g.limit
if c < floor:
violations.append(g.metric)
else:
ceiling = s + g.limit if g.mode == "abs" else s * g.limit
if c > ceiling:
violations.append(g.metric)
return ("rollback" if violations else "advance"), violations
guardrails = [
Guardrail("error_rate", "abs", 0.005),
Guardrail("p95_latency_ms", "ratio", 1.10),
Guardrail("approval_rate", "abs", 0.02, higher_is_better=True),
Guardrail("null_feature_rate", "abs", 0.01),
]
stable = {"requests": 50000, "error_rate": 0.002, "p95_latency_ms": 120,
"approval_rate": 0.31, "null_feature_rate": 0.010}
candidate = {"requests": 2500, "error_rate": 0.003, "p95_latency_ms": 128,
"approval_rate": 0.30, "null_feature_rate": 0.040}
print(evaluate(stable, candidate, guardrails))This prints ('rollback', ['null_feature_rate']). The system metrics look fine, since the error rate and latency are within limits. The candidate is failing on its input features, and only a model-layer guardrail sees that. A feature pipeline that works for the stable model but returns nulls for the candidate is a common cause.
Guardrails that depend on delayed labels
Some of the most important metrics, such as precision or fraud loss, need ground truth that arrives days later. You cannot gate a 30-minute canary stage on them. Handle this with proxies and two-speed gating:
- Fast guardrails use signals available immediately: errors, latency, null rates, score distribution shift, and the rate at which the candidate's decisions disagree with the stable model's.
- Slow guardrails use labeled outcomes and are checked when labels mature, often during a longer A/B phase or after full promotion, with a rollback path kept open.
A proxy is only useful if you have checked that it moves with the real metric. Agreement with the stable model is a safety signal, not a quality signal. A candidate that agrees 99% of the time cannot have changed much, and a candidate that agrees 60% of the time is either much better or much worse, and the proxy cannot tell you which.
Segments and tail behavior
An average can hide a failing slice. Candidate and stable may have equal overall error rates while the candidate fails for one country, one device type, or one rare input class. Add guardrails for the segments that matter to the product or to fairness requirements, and for tail latency (p99) as well as p95. Each added segment multiplies the number of checks, and small segments have small samples, so give each segment its own minimum sample size. Otherwise a tiny segment will trigger false rollbacks all day.
Multiple checks have a cost. If you run 20 independent guardrail checks at a 5% false-alarm rate each, you should expect about one false alarm per evaluation round. Practical remedies are to use wider thresholds for low-risk metrics, require a breach on two consecutive evaluation windows before rolling back, and keep the hard, instantly actionable guardrails (errors, crashes) few.
Common errors
- Choosing metrics after seeing results. Write the goal metric, guardrails, and thresholds into the rollout plan before traffic is sent. Otherwise you will pick whichever metric looks best.
- Treating a guardrail as a goal. Latency staying flat does not show the model is better. It shows the model is not worse in one respect.
- Optimizing a proxy that has drifted from the real aim. Click-through can rise while satisfaction falls. Review the link between proxy and outcome periodically.
- Comparing to a stale baseline. Use the stable model's concurrent numbers.
- No minimum sample. The first few hundred requests fire spurious alarms or pass things that are not yet measured.
- Alerting without an action. Every guardrail should name what happens on a breach: pause, roll back, or page someone.
Putting it together
For a fraud model update, a reasonable plan might look like this:
| Role | Metric | Rule |
|---|---|---|
| Goal | fraud recall at 1% false-positive rate | candidate improves, tested after labels mature |
| Guardrail (fast) | error rate | at most +0.005 absolute vs. stable |
| Guardrail (fast) | p95 latency | at most 1.10x stable |
| Guardrail (fast) | null feature rate | at most +0.01 absolute vs. stable |
| Guardrail (slow) | false-positive rate on chargeback-free customers | no more than 5% relative increase |
| Diagnostic | score histogram, per-feature null rate | read when a guardrail trips |
Each row has a role, a rule, and a data source. Write the table into the rollout ticket, and implement the fast rows as code like evaluate above.
Exercise
A candidate model's overall error rate matches the stable model's, but you worry it fails for mobile users, who are 4% of traffic. Name two changes you would make to the guardrail setup, and one risk of making them.
Show answer
Add a segment guardrail for mobile users with its own error-rate limit, and give that segment its own minimum sample size so it is only evaluated once enough mobile requests have arrived. You could also add a p99 latency guardrail for the segment. The risk is more false alarms: every added check and every small segment gives noise another chance to trip a rollback, so require a breach on consecutive windows or use wider limits for low-risk segments.
Exercise
In the evaluate function, why does it return "wait" when the candidate has fewer than min_requests requests, instead of "advance" when no guardrail is violated?
Show answer
With very few requests, rates are too noisy to show a breach, so "no violation" would mean "not enough data" rather than "safe". Returning "wait" stops the canary from advancing on an unmeasured candidate.