Detecting Data Drift in Production
Compare live feature and prediction distributions against training baselines, choose tests that catch real drift, and alert only when the shift matters.
On this page
Introduction
A model that scored well in evaluation can quietly degrade in production because the world moved and the data no longer resembles what it was trained on. Users change behaviour, upstream systems change formats, and seasonal patterns shift the input distribution. Data drift is the divergence between what the model sees now and what it learned from, and detecting it early is what lets you retrain or fall back before users notice wrong answers. The challenge is separating meaningful drift from harmless noise.
What Drift Actually Means
Data drift is a change in the distribution of inputs; concept drift is a change in the relationship between inputs and the correct output. The first is observable from inputs alone, the second requires labels and therefore lags. Covariate shift, a special case, keeps the relationship but changes the input mix. Distinguishing these matters because the remedy differs: input drift may need data collection, concept drift needs retraining, and a format change needs a bug fix in the parser rather than the model.
import numpy as np
from scipy.stats import ks_2samp
def numeric_drift(baseline: np.ndarray, current: np.ndarray, warn: float = 0.1, alarm: float = 0.2):
# KS gives a statistic in [0,1] interpretable as a max CDF gap (effect size).
stat, p = ks_2samp(baseline, current)
level = "ok"
if stat >= alarm:
level = "alarm"
elif stat >= warn:
level = "warn"
return {"statistic": float(stat), "p_value": float(p), "level": level}
def categorical_drift(baseline_freq: dict, current_freq: dict):
keys = set(baseline_freq) | set(current_freq)
tvd = 0.5 * sum(abs(baseline_freq.get(k, 0) - current_freq.get(k, 0)) for k in keys)
unseen = [k for k in current_freq if k not in baseline_freq]
return {"total_variation": tvd, "novel_categories": unseen}
Establishing a Baseline
You cannot detect drift without a reference. Freeze the distribution of each feature from the training or validation set and store summary statistics such as quantiles, category frequencies and missing rates. Also store a sample of raw values so you can recompute different statistics later without re-reading history. Version the baseline alongside the model, because a new model has a new baseline and comparing against the old one produces false alarms.
def monitor(features: dict, baselines: dict, model_feature_importance: dict):
findings = []
for name, values in features.items():
b = baselines[name]
if b["kind"] == "numeric":
d = numeric_drift(b["sample"], values)
d["weight"] = model_feature_importance.get(name, 0.0)
else:
d = categorical_drift(b["freq"], values)
d["weight"] = model_feature_importance.get(name, 0.0)
# Only escalate when the shifted feature actually matters to the model.
d["actionable"] = d["weight"] >= 0.05 and d.get("level") in {"warn", "alarm"}
findings.append({"feature": name, **d})
return findings
# A sudden jump to a new scale is a bug signature, not gradual drift.
def looks_like_unit_change(baseline_median: float, current_median: float) -> bool:
ratio = current_median / baseline_median if baseline_median else 0
return ratio > 50 or ratio < 0.02
Choosing Drift Statistics
For numeric features, compare distributions with a population stability index, a Kolmogorov-Smirnov statistic or a Wasserstein distance, each sensitive to different kinds of shift. For categorical features, compare frequency tables with a chi-squared test or total variation distance. Report effect size, not only a p-value, because with large samples even trivial differences become statistically significant. A test that flags every large-sample difference generates alarm fatigue and gets ignored.
Sampling and Windows
Compare a recent window against the baseline, but decide the window by the business cadence rather than the ingestion rate. A daily window detects fast changes but is noisy; a weekly window is stable but slow. Guard against seasonality by comparing the same weekday and hour, because traffic that doubles every Monday is not drift. Downsample the current window to the baseline size so the comparison is not dominated by volume, and be explicit about how missing values count.
Separating Drift from Bugs
A sudden, total shift in one feature is more likely a pipeline bug than genuine drift: a unit change from dollars to cents, a timezone change, or a renamed category. Sudden jumps with no gradual ramp should page rather than open a drift ticket, because the model is now receiving wrong data. Track schema and format violations next to distribution metrics, since the parser is often the real culprit and the model is merely the messenger.
Linking Drift to Outcomes
Not all drift matters. A feature can shift substantially while predictions and errors stay fine, in which case alarming is wasteful. Monitor model output distributions and, where labels arrive, error metrics, and treat input drift as a leading indicator to investigate rather than an incident by itself. Prioritise features by their importance to the model, because drift in a dominant feature is far more consequential than in a negligible one.
Alert Thresholds and Fatigue
Set thresholds from the baseline variability, not from a textbook constant, by measuring how the statistic behaves on normal data across many windows. Use hysteresis so an alert clears only when drift returns well below the trigger, avoiding flapping. Route different severities to different channels and require an owner for each alert. An alert nobody acts on is worse than no alert, because it trains the team to ignore the channel.
Responding to Detected Drift
When drift is confirmed and consequential, the responses in order of preference are often: fix the upstream bug if it is one, retrain on recent data, widen the training distribution, or degrade to a simpler safer model. Re-evaluate the model on a recent labelled slice before retraining blindly, because the labels may have changed and retraining on them perpetuates a new mistake. Record the drift event and the action so the next occurrence is faster to resolve.
Testing the Drift Pipeline
Feed synthetic windows that are identical to, slightly shifted from, and drastically different from the baseline, and assert that the detector stays quiet, warns and pages respectively. Include a window with a unit change and a window with missing values to prove these are classified as bugs rather than gradual drift. These tests keep the detector honest as thresholds and features evolve, which is when drift monitoring most often quietly stops working.
Sources
Sources: scipy ks_2samp, Evidently drift detection, Population stability index.
FAQ
- Is a significant p-value enough to alert on drift?
- No. With large samples even trivial differences are significant. Report an effect size such as a KS statistic or PSI and threshold on that, otherwise you will alert on everything and ignore it.
- What if drift is detected but predictions are fine?
- Investigate rather than page. Input drift is a leading indicator; only escalate to an incident when output or error metrics move, or when the shift looks like a data bug.
Report a problem with this articleOpens a pre-filled issue on GitHub.