Sub topic 14
Setting thresholds and limiting false alarms
Drift tests produce numbers. An alert is a decision to interrupt a person based on one of those numbers. This chapter covers how to choose the cutoff, how to estimate how often it will fire when nothing is wrong, and how to reduce noise without hiding real problems.
This chapter assumes you can compute the Kolmogorov-Smirnov (KS) statistic, a chi-square test and the Population Stability Index (PSI) for one feature, and that you know what a p-value is. It builds on the earlier chapters on univariate tests, PSI and data quality checks.
Why drift alerts become noise
A monitoring system that cries wolf gets muted. Three mechanisms cause most false alarms.
- Large samples make tiny shifts significant. A p-value answers "is there any difference?", not "is the difference big enough to matter?". With 100,000 rows per window, a shift of 0.01 standard deviations can give p < 0.001. The test is correct, but the alert is useless.
- Many features multiply the chances. At a significance level of 0.05, a test on data with no drift still fires 5% of the time. With 50 features per window, you expect about 2.5 false alarms every window.
- Normal variation is not drift. Weekday versus weekend traffic, month-end spikes and holiday seasons shift distributions on a regular schedule. A reference window that ignores them makes every cycle look like an incident.
The goal is not zero false alarms. It is a false alarm rate the on-call person can tolerate, while still catching the shifts that cost money.
Use an effect size, not only a p-value
Prefer a statistic that measures how large the change is, and set the threshold on that. The KS statistic (the maximum gap between the two cumulative distributions) and PSI both do this. A p-value can still be a secondary filter.
Common PSI conventions are:
| PSI | Usual reading |
|---|---|
| Below 0.1 | No meaningful change |
| 0.1 to 0.25 | Moderate change, worth watching |
| Above 0.25 | Large change, investigate |
These cutoffs come from credit-scoring practice. They are starting points, not laws. PSI also has a noise floor that depends on window size and bin count. For two samples from the same distribution, the expected PSI is roughly (bins - 1) * (1/n_ref + 1/n_cur). With 10 bins and 1,000 rows in each window, that is about 0.018. With 100 rows each it is about 0.18, which already looks "moderate" with no drift at all. Small windows need higher thresholds or wider windows.
Calibrate the threshold on your own history
The reliable way to set a threshold is to measure what "no drift" looks like for your data and window size. Take periods you know were healthy, compare windows from them, and choose a high quantile of the resulting scores.
import numpy as np
def psi(reference, current, bins=10, eps=1e-6):
edges = np.quantile(reference, np.linspace(0, 1, bins + 1))
edges[0], edges[-1] = -np.inf, np.inf
edges = np.unique(edges)
ref_pct = np.histogram(reference, bins=edges)[0] / len(reference)
cur_pct = np.histogram(current, bins=edges)[0] / len(current)
ref_pct = np.clip(ref_pct, eps, None)
cur_pct = np.clip(cur_pct, eps, None)
return float(np.sum((cur_pct - ref_pct) * np.log(cur_pct / ref_pct)))
def null_scores(history, window_size, n_trials, rng):
"""PSI between two disjoint random windows drawn from healthy history."""
scores = []
for _ in range(n_trials):
idx = rng.choice(len(history), size=2 * window_size, replace=False)
scores.append(psi(history[idx[:window_size]], history[idx[window_size:]]))
return np.array(scores)
rng = np.random.default_rng(0)
history = rng.normal(0, 1, 100_000)
for window_size in (200, 1000, 5000):
scores = null_scores(history, window_size, n_trials=300, rng=rng)
print(f"window={window_size:>5} median={np.median(scores):.4f} "
f"p99={np.quantile(scores, 0.99):.4f}")The 99th percentile at each window size is a threshold that, on healthy data, fires about once per 100 windows. It shrinks as windows grow, which shows why one fixed number such as 0.2 fits some pipelines badly.
Random sampling treats rows as independent. Real traffic has daily and weekly structure. Where you can, calibrate with real consecutive windows, such as last week against the week before, across several healthy months. That includes the seasonal swings in your noise estimate instead of surprising you with them later.
Control the number of tests
When you test many features, correct for it or aggregate. There are three options.
- Bonferroni correction. Divide the significance level by the number of tests. It is simple and strict, and it can miss real drift in one feature.
- Benjamini-Hochberg (BH). It controls the expected share of false discoveries among the features you flag. It usually fits monitoring better because you accept a few wrong flags in exchange for power.
- Aggregate rules. Alert when more than a set share of features exceed their thresholds, or only on features that matter, ranked by model importance.
import numpy as np
from scipy.stats import ks_2samp, false_discovery_control
rng = np.random.default_rng(1)
n_features = 50
p_values = []
for j in range(n_features):
reference = rng.normal(size=2000)
shift = 0.3 if j < 3 else 0.0 # only features 0, 1, 2 truly drifted
current = rng.normal(loc=shift, size=2000)
p_values.append(ks_2samp(reference, current).pvalue)
p_values = np.array(p_values)
adjusted = false_discovery_control(p_values, method="bh")
print("raw p < 0.05: ", np.flatnonzero(p_values < 0.05))
print("BH-adjusted < 0.05:", np.flatnonzero(adjusted < 0.05))false_discovery_control requires SciPy 1.11 or later. The raw list can include features other than 0, 1 and 2, because about 5% of the 47 unshifted features fall under 0.05 by chance. The adjusted list removes most of them.
Add time: persistence and severity
A single window over the line is weak evidence. Requiring persistence removes one-off spikes, such as a batch job that ran late. A common rule is "score above the threshold in 3 of the last 5 windows". The cost is delay. If windows are daily, you wait about three days to confirm a slow drift, so tune it against how quickly the model's errors cost you.
def persistent_alert(recent_flags, k=3, n=5):
"""recent_flags: list of booleans, oldest first. True means over threshold."""
return sum(recent_flags[-n:]) >= k
print(persistent_alert([False, True, False, True, True])) # True
print(persistent_alert([False, False, False, False, True])) # FalseUse more than one level of severity. Different problems need different urgency.
| Signal | Type of threshold | Action |
|---|---|---|
| Schema break, unexpected nulls above a hard limit | Fixed rule, no statistics | Page immediately |
| Large PSI on an important feature, persistent | Calibrated, persistence required | Ticket, investigate same day |
| Moderate PSI or a few minor features | Calibrated, lower level | Dashboard and weekly review |
| Performance metric below its agreed floor (when labels arrive) | Business-defined | Page, follow the response playbook |
Data quality failures such as a missing column are not statistical questions. They are either true or false, so use fixed rules and alert on the first occurrence. Reserve calibrated, persistent thresholds for drift.
The decision flow
Review the thresholds regularly
Thresholds are not set once. Keep a record of each alert and what happened afterward: real problem, harmless shift, or noise. Then act on it.
- If most alerts for a feature were harmless, raise its threshold, require longer persistence, or drop the feature from paging.
- If a performance drop was not preceded by any alert, you have a missed detection. Look at whether the feature set, window length or reference window needs changing.
- After a retrain or a known business change, rebuild the reference window and recalibrate. Old thresholds describe the old data.
The next chapter covers what to do when an alert is confirmed: investigate, retrain or roll back.
Exercise
A team monitors 40 features daily with a KS test at p < 0.05 and pages on any single flagged feature. They get a page most days, and almost all turn out to be harmless. Name two causes and a fix for each.
Show answer
First, multiple testing: with 40 independent tests at 0.05, about 2 features are expected to be flagged each day even with no drift. Fix it with Benjamini-Hochberg correction, or by alerting on an aggregate rule such as "several important features flagged". Second, p-values respond to sample size, not importance, so large daily windows flag trivial shifts. Fix it by thresholding an effect size (KS statistic or PSI) calibrated on healthy history, and by requiring persistence over several windows before paging.
Exercise
You compare two windows of 100 rows each using PSI with 10 bins and see 0.17 with no known change. Is this drift? What would you change?
Show answer
Probably not. The expected PSI between two same-distribution samples is about (10 - 1) * (1/100 + 1/100) = 0.18, so 0.17 is at the noise floor. Use larger windows, fewer bins, or a threshold calibrated for this window size by comparing healthy historical windows and taking a high quantile such as the 99th.