Sub topic 2
What to Monitor: Operational, Data, Prediction and Performance Layers
This chapter assumes you can train and evaluate a supervised model, read basic statistics (distributions, p-values), and have deployed a model as a batch job or an API. It covers the four layers of monitoring and what each one can and cannot tell you. Later chapters go deeper on individual tests and responses.
Why one dashboard is not enough
A deployed model can fail in ways that look nothing alike. The server can crash. An upstream team can rename a column. Customers can change their behavior. The relationship between inputs and outcomes can shift. Each failure shows up in a different place, and a single accuracy chart catches only some of them, usually late.
A practical way to organize monitoring is by layer. Each layer watches a different part of the path from raw input to business outcome. The layers differ in what they cost, how fast they react, and how much they need from you (for example, ground-truth labels).
The layers move from fast and cheap on the left to slow and informative on the right. Operational and data checks work on every request the moment it arrives. Performance checks need the true outcome, which may arrive days or months later.
Layer 1: Operational monitoring
Operational monitoring asks whether the service is running. It uses the same metrics as any production software.
- Latency is the time to answer a request. Track percentiles (p50, p95, p99), not only the mean, because slow outliers hide in averages.
- Error rate is the share of requests that fail or time out.
- Throughput is the number of requests or rows processed per unit of time. A sudden drop often means an upstream system stopped sending data. A sudden spike can mean a retry storm or abuse.
- Resource use covers CPU, memory, GPU, and queue depth.
- Batch job health covers whether the scheduled job ran, how long it took, and how many rows it scored.
A model that returns a fast, well-formed answer can still be wrong. Operational metrics tell you the system is alive, not that it is right. That is why the other three layers exist.
Layer 2: Data monitoring
Data monitoring asks whether the inputs look like what the model expects. It has two parts that are easy to confuse.
Data quality checks catch broken inputs. These are rule-based and have a clear right answer:
- Schema: expected columns exist, with the expected types.
- Missing values: the share of nulls per feature stays within a normal range.
- Ranges and domains: ages are not negative, a country code is in the known list, a probability lies in [0, 1].
- Freshness and volume: data is recent and the row count is plausible.
- Duplicates and units: a feature did not silently switch from dollars to cents.
Data drift checks catch changed distributions. These are statistical. The inputs are valid but look different from the training data, for example a shift in average basket size. Later chapters cover the tests for this.
The distinction matters for response. A quality failure usually means a bug, and the fix is in the pipeline. Drift usually means the world changed, and the fix may be in the model.
The following function shows a minimal data quality check on a pandas DataFrame. It returns a list of problems instead of raising, so a monitoring job can log all of them at once.
import pandas as pd
EXPECTED = {
"age": {"dtype": "int64", "min": 0, "max": 120, "max_null_rate": 0.01},
"income": {"dtype": "float64", "min": 0.0, "max": 1e7, "max_null_rate": 0.05},
}
def check_quality(df: pd.DataFrame) -> list[str]:
problems = []
for col, rules in EXPECTED.items():
if col not in df.columns:
problems.append(f"{col}: column missing")
continue
if str(df[col].dtype) != rules["dtype"]:
problems.append(f"{col}: dtype {df[col].dtype}, expected {rules['dtype']}")
null_rate = df[col].isna().mean()
if null_rate > rules["max_null_rate"]:
problems.append(f"{col}: null rate {null_rate:.1%} above limit")
values = df[col].dropna()
if len(values) and (values.min() < rules["min"] or values.max() > rules["max"]):
problems.append(f"{col}: values outside [{rules['min']}, {rules['max']}]")
return problems
batch = pd.DataFrame({"age": [34, 29, -5, 41], "income": [52000.0, None, 61000.0, 48000.0]})
for problem in check_quality(batch):
print(problem)On this batch the function reports the negative age and the 25% null rate in income. Rules like these should come from the training data and from domain knowledge, then be reviewed when the model is retrained.
Layer 3: Prediction monitoring
Prediction monitoring watches the model's outputs. It needs no labels, so it reacts as fast as the data layer.
Track these for each prediction run or time window:
- For classifiers: the distribution of predicted scores, the share of each predicted class, and the share of predictions above the decision threshold.
- For regressors: the mean, spread, and quantiles of predictions.
- For confidence: the share of low-confidence predictions, or the entropy of predicted probabilities.
- For ranking and recommendation: the diversity of items shown and the share of fallback results.
A change in the output distribution is a useful symptom. If a fraud model flagged 1% of transactions for months and now flags 6%, something changed. It could be a real fraud wave, a drifted input, or a broken feature. Prediction monitoring does not say which. It says where to look.
It also works as a compact summary. A model may take 200 input features, and testing each one produces many alerts. One score distribution is a single series that reflects the combined effect of all inputs as the model sees them.
A limit applies. The output can stay stable while the model gets worse, for example when two shifts cancel out. A stable output distribution is weak evidence of health.
Layer 4: Performance monitoring
Performance monitoring compares predictions to the true outcomes. It is the only layer that measures what you care about: whether the model is right. It uses the same metrics as offline evaluation, such as precision, recall, ROC AUC, RMSE, or calibration error, computed on recent production data.
The cost is the labels. Ground truth often arrives late (a loan default shows up months later), partially (only reviewed cases get a label), or with bias (you only see outcomes for approved applicants). A later chapter covers how to estimate performance when labels are late or missing.
When you compute performance, slice it. A global accuracy of 91% can hide a segment at 60%. Useful slices include region, device, customer segment, and model version.
Comparing the layers
| Layer | Needs labels? | Typical delay | Catches | Misses |
|---|---|---|---|---|
| Operational | No | Seconds | Outages, slowness, failed jobs | Wrong but well-formed answers |
| Data quality | No | Seconds to minutes | Schema breaks, nulls, bad ranges | Valid but shifted inputs |
| Data drift | No | Minutes to days | Changed input distributions | Whether the shift hurts the model |
| Prediction | No | Minutes to days | Output shifts from any cause | Cancelling shifts, the cause |
| Performance | Yes | Days to months | Real accuracy loss | Anything before labels arrive |
No layer replaces another. The fast layers give early, noisy warnings. The slow layer gives the confirmed answer. A good setup uses the fast layers as triggers and the slow layer as the judge.
Deciding what to log
You can only monitor what you recorded. Decide logging before deployment, because you cannot reconstruct missing data later. For each prediction, log:
- A unique request or prediction ID, so labels can be joined back later.
- A timestamp for the prediction.
- The input feature values as the model received them, after preprocessing.
- The model version and feature pipeline version.
- The prediction and, for classifiers, the score.
- Later, the ground-truth label and the time it arrived.
Two cautions apply. First, features often contain personal data, so apply the same access controls, retention limits, and masking rules you use for the source data. Second, at high volume you can log a random sample instead of every row. Sample uniformly, not "the first N per hour", or you will bias the statistics you compute from the log.
import json
import time
import uuid
def log_prediction(features: dict, score: float, model_version: str, path="predictions.jsonl"):
record = {
"prediction_id": str(uuid.uuid4()),
"timestamp": time.time(),
"model_version": model_version,
"features": features,
"score": score,
}
with open(path, "a") as f:
f.write(json.dumps(record) + "\n")
return record["prediction_id"]
pid = log_prediction({"age": 34, "income": 52000.0}, score=0.18, model_version="2026-11-01")
print(pid)A JSON-lines file is enough to show the idea. In production, send the same record to a log pipeline, a message queue, or a table that your monitoring jobs read.
Common mistakes
- Monitoring only operations. The service is green while the model quietly degrades. Add at least data quality and prediction checks.
- Treating every drift alert as an incident. A distribution can change without hurting accuracy. Later chapters cover when drift matters.
- Computing metrics on unrepresentative samples. If labels come only for a biased subset, the performance number is biased too.
- Not logging the model version. After a retrain you cannot tell which model produced which prediction.
- Using only means. A feature mean can stay constant while its spread doubles. Track quantiles and rates too.
Summary
Operational monitoring tells you the service runs. Data monitoring tells you the inputs are valid and familiar. Prediction monitoring tells you the outputs changed. Performance monitoring tells you whether the model is still right. The first three react quickly without labels. The fourth confirms the damage but arrives late. Log inputs, outputs, versions, and IDs from day one so every layer is possible.
Exercise
A fraud model's API shows normal latency and a 0.1% error rate. Its share of transactions flagged as fraud rises from 1% to 6% over one week. No labels are available yet. Which layers raised or could raise a signal, and what would you check first?
Show answer
The operational layer shows nothing, since the service is healthy. The prediction layer raised the signal (flag rate 1% to 6%). Check the data quality layer first, because a broken or changed feature (nulls, a unit change, a new category) is the cheapest explanation and has a clear fix. If inputs are valid, run drift checks on the features to see which shifted. The performance layer cannot confirm anything until labels arrive, so use fast layers to decide whether to investigate now.
Exercise
Why must you log a prediction ID and the model version with every prediction, even if you do not plan to compute performance yet?
Show answer
The ID lets you join true labels to predictions when they arrive later, which performance monitoring needs. The model version lets you separate results by model after a retrain or rollback. Neither can be recovered afterward if not logged at prediction time.