Sub topic 13
Monitoring models in production
This chapter assumes you can deploy a model behind an API or a batch job. It also assumes you know basic Python and have seen a metrics dashboard such as Grafana. The next chapter covers drift tests in detail. This one covers what to measure and how to turn measurements into alerts.
Why a healthy service can hide a failing model
A deployed model can fail without any error. The service returns HTTP 200, latency is normal and CPU is calm, yet the predictions are wrong. Ordinary software fails loudly. A model fails silently, because its output is always a valid-looking number or label.
Monitoring for ML therefore watches two things at once:
- The service: whether the system is up and fast.
- The model: whether its inputs and outputs still look like what it was built for, and whether its predictions are still correct.
The four layers of monitoring
Each layer answers a different question. Lower layers are cheaper and faster to measure. Higher layers matter more to the business but arrive later.
| Layer | Example signals | Available | Needs labels |
|---|---|---|---|
| Service health | p95 latency, error rate, requests per second, memory | Immediately | No |
| Data quality | Share of missing values, out-of-range values, schema violations | Immediately | No |
| Prediction behavior | Mean score, share of each predicted class | Immediately | No |
| Model performance | Accuracy, precision, recall, error in a business metric | Delayed | Yes |
Service health
Use the same practices as any web service. Track latency percentiles instead of averages, because a mean hides slow tails. Track error rates and throughput, and add resource metrics such as memory and GPU use.
Two ML-specific points apply:
- Model loading and cold starts can dominate latency after a deploy. Record them separately from steady-state latency.
- Batch jobs need their own signals: job duration, rows scored, and whether the job finished on schedule. A batch job that silently scores zero rows is a common failure.
Data quality at the serving boundary
Validate every request or batch against the expectations you recorded at training time. Typical checks are:
- Schema: required columns exist and have the expected types.
- Completeness: the share of null or missing values per feature.
- Range and category checks: values fall within observed bounds, and categorical values were seen in training.
- Freshness: upstream data arrived on time. Stale features are a frequent cause of bad predictions.
These checks catch upstream pipeline bugs, such as a unit change from meters to feet or a renamed column filled with defaults. They catch such bugs before any statistical drift test would.
Prediction behavior
You often cannot see correctness right away, but you can see what the model outputs. Watch the distribution of predicted scores and the share of each predicted class. A fraud model that flagged 1% of transactions last month and flags 9% today needs investigation, even without labels. Either the world changed or something upstream broke.
This is a proxy signal. It tells you something moved, not which direction is correct.
Model performance and the label delay problem
True performance needs ground truth, and ground truth often arrives late. A loan default label may take months. A recommendation click arrives in seconds. Plan for this:
- Log predictions with a stable ID so labels can be joined to them later.
- Compute metrics on a lag. Report accuracy for predictions made N days ago, once their labels have arrived.
- Use proxies in the gap, such as the data quality and prediction behavior signals above.
- Sample for labeling when labels are costly. Route a random slice of traffic to human reviewers and treat their answers as ground truth.
Be careful with feedback loops. If the model decides which cases get labeled, such as only approved loans, the labels are biased. A random sample of traffic avoids this.
Code: a window summary with alert thresholds
The script below summarizes one window of logged traffic and compares it to thresholds. It uses only NumPy, so you can run it as shown.
import numpy as np
THRESHOLDS = {
"p95_latency_ms": 250.0,
"missing_rate": 0.02,
"out_of_range_rate": 0.01,
"positive_rate_shift": 0.05,
}
def summarize_window(latencies_ms, feature, predictions, expected_range, baseline_positive_rate):
latencies_ms = np.asarray(latencies_ms, dtype=float)
feature = np.asarray(feature, dtype=float)
predictions = np.asarray(predictions, dtype=int)
present = feature[~np.isnan(feature)]
low, high = expected_range
if present.size == 0:
out_of_range = 1.0
else:
out_of_range = float(((present < low) | (present > high)).mean())
return {
"p95_latency_ms": float(np.percentile(latencies_ms, 95)),
"missing_rate": float(np.isnan(feature).mean()),
"out_of_range_rate": out_of_range,
"positive_rate_shift": abs(float(predictions.mean()) - baseline_positive_rate),
}
def find_alerts(summary):
return [name for name, limit in THRESHOLDS.items() if summary[name] > limit]
rng = np.random.default_rng(1)
n = 2000
latencies = rng.gamma(shape=4.0, scale=30.0, size=n)
feature = rng.normal(loc=5.0, scale=1.0, size=n)
feature[rng.random(n) < 0.05] = np.nan # simulate an upstream bug: 5% missing
predictions = (rng.random(n) < 0.12).astype(int)
summary = summarize_window(latencies, feature, predictions, (0.0, 10.0), baseline_positive_rate=0.10)
for key, value in summary.items():
print(f"{key}: {value:.3f}")
print("alerts:", find_alerts(summary))With these inputs, missing_rate is about 0.05, so it exceeds the 0.02 limit and appears in the alert list. The 12% positive rate against a 10% baseline gives a shift near 0.02, which stays under the limit. Latency depends on the random draw. The point is that a simple summary, computed per window, already catches an upstream data bug that no HTTP monitor would see.
Designing alerts that people act on
Too many alerts teach a team to ignore them. A few rules help:
- Alert on symptoms with a clear owner and action. "Missing rate above 2% for three consecutive windows" is better than "feature distribution changed."
- Set thresholds from history. Use the normal range of each metric, including its weekly and daily cycles, instead of a guess.
- Separate paging from ticketing. Page for outages and broken pipelines. Create tickets for slow degradation.
- Attach context. Include the model version, data window, and a link to the dashboard.
- Slice your metrics. An overall accuracy of 92% can hide a 70% accuracy for one region or customer segment. Monitor key slices separately.
Common errors
- Monitoring only infrastructure, so model failures go unseen.
- Not logging the model version and input features with each prediction. Without them you cannot debug or compute lagged metrics.
- Comparing production to the wrong baseline. Use the training or validation data of the version that is actually deployed.
- Treating every statistical change as an incident. A shift is a prompt to investigate, not proof that the model is wrong.
- Ignoring privacy. Logged features can contain personal data, so apply the same retention and access rules as the source data.
What to carry forward
Monitoring turns a deployed model from a one-time release into a managed system. The signals you collect here feed the next two chapters. Drift detection formalizes the "did the inputs change" question with statistical tests. Retraining decides what to do when monitoring says the model has degraded.
Exercise
A churn model's service dashboard shows normal latency and zero errors. Labels (whether a customer actually left) arrive about 60 days after each prediction. Last week the share of customers predicted as "will churn" jumped from 8% to 21%. Name two monitoring layers that could have caught this, and list two things you would check first.
Show answer
The prediction behavior layer caught it directly, through the predicted-class share. The data quality layer could also catch it if an upstream bug caused it, for example through a rise in missing values or a changed feature range. Service health would not catch it. Model performance would show it only 60 days later. First check recent data quality, meaning missing rates, ranges, freshness and schema on each feature, and any recent upstream pipeline or deployment change, including the model version in use. If the inputs are clean and nothing changed, investigate whether the customer population genuinely shifted, and sample cases for early labels.
Exercise
Why should each logged prediction include a stable ID and the model version?
Show answer
The ID lets you join the prediction to its ground-truth label when the label arrives later, which is needed to compute accuracy on a lag. The model version lets you attribute metrics and failures to the specific version that produced them, and compare versions during a rollout or rollback.