TExcelTAD
Home › Deployment & MLOps: Serving, Pipelines, Monitoring › Monitoring Models in Production

Monitoring Models in Production

A web service fails loudly: it times out, returns 500, runs out of memory. A model fails quietly. It keeps answering in 20 milliseconds with status 200, and the answers are wrong, because a column upstream changed units, because the customers changed, or because the world did. Ordinary service monitoring sees none of that. Monitoring a model means watching several layers at once, from the HTTP endpoint down to the business outcome the model exists for, and keeping a log of every prediction so that you can judge it later, when the truth arrives.

This lesson sets up those layers for the course's running example, the risk-model service (a Pipeline(StandardScaler, LogisticRegression) that scores loan applications), computes a daily monitoring summary from a prediction log with pandas, joins delayed outcomes onto it, and turns the summary into alerts.

The layers

1 servicelatency, errors, traffic, saturation (CPU, memory, queue)seconds 2 data qualitymissing values, ranges, types, unknown categoriesper request 3 inputs and predictionsfeature drift, score distribution, positive ratehours to days 4 model qualityaccuracy, calibration, per segment: needs labelsdays to months 5 business KPIsapproval rate, losses, revenue, complaintsweeks to months slower,needs labels,closer towhat matters
  1. Service health is the same as for any API: request rate, error rate and latency percentiles (the RED method), plus utilisation and saturation of CPU, memory and queues (USE), as in RED and USE. Targets for them are SLOs: "99 % of requests answer within 300 ms". A model adds its own causes (a cold model load, a huge batch, a feature lookup that times out), but the measurements are the usual ones.
  2. Data quality catches the most common production failure: bad inputs. Missing rates per feature, values out of the training range, unknown categories, wrong types. These checks run per request or per batch and are the runtime side of data validation.
  3. Input and prediction distributions compare live traffic with a reference: feature drift (PSI and KS) and, cheapest of all, the distribution of the model's own score and its positive rate. If the approval rate jumps from 70 % to 85 % overnight, something changed, whatever the cause.
  4. Model quality (accuracy, AUC, calibration, error per segment) is the real target, but it needs labels, and labels are delayed: a default shows up months after the loan. That delay is why layers 2 and 3 exist. The next lessons treat delayed labels and concept drift.
  5. Business KPIs are what the model is for: losses, revenue, conversion, manual review load. They move slowly and for many reasons, but they are the final check that a "better" model actually helps.

The prediction log

Every layer below the first needs a record of what the model saw and said. Log one row per prediction with:

  • a request id (unique, generated by the service or passed in by the caller), so that the outcome can be joined later, and so that a complaint can be traced to the exact prediction;
  • the timestamp and the model version (the registry version or alias it resolved to), so that metrics can be split by version during a canary;
  • the inputs as the model received them (after the client's transformations, before the model's own), and the output: score, decision, threshold;
  • latency and status, so the same log serves layer 1.

Write it as structured logs or to a table, not as free text. Two cautions: inputs are often personal data, so the log needs the same access control and retention limits as the source (governance); and high-traffic services usually log a sample of full inputs and every score.

From scratch: a monitoring summary in pandas

A simulated week of the risk-model log, 400 requests a day. Two things go wrong, as they would in real life: on day 5 an upstream change sends debt_ratio as missing for about 30 % of the requests, and the service fills a missing value with 0, which makes applicants look safer; on day 6 a slow feature store raises latency and causes some timeouts (status 503).

python · try it yourself
import numpy as np
import pandas as pd

rng = np.random.default_rng(0)
parts = []
for day in range(1, 8):
    n = 400
    income = rng.lognormal(10.6, 0.35, n).round(-2)
    debt_ratio = rng.beta(2, 5, n)
    if day == 5:                                  # upstream bug: the field arrives empty
        debt_ratio[rng.random(n) < 0.3] = np.nan
    latency = rng.lognormal(np.log(40), 0.3, n)   # milliseconds
    status = np.full(n, 200)
    if day == 6:                                  # slow feature store
        latency *= rng.choice([1, 6], n, p=[0.85, 0.15])
        status[latency > 250] = 503
    filled = np.nan_to_num(debt_ratio, nan=0.0)   # the service's (bad) default
    z = -2.2 + 6.0 * filled - 1.5 * (np.log(income) - 10.6)
    score = 1 / (1 + np.exp(-z))                  # probability of default
    parts.append(pd.DataFrame({
        "request_id": [f"d{day}-{i:04d}" for i in range(n)], "day": day,
        "model_version": "risk-model:7", "status": status, "latency_ms": latency.round(1),
        "income": income, "debt_ratio": debt_ratio.round(3),
        "score": np.where(status == 200, score.round(4), np.nan)}))
log = pd.concat(parts, ignore_index=True)
log["approved"] = log["score"] < 0.5

ok = log[log["status"] == 200]
summary = pd.DataFrame({
    "requests": log.groupby("day").size(),
    "err_rate": log.groupby("day")["status"].apply(lambda s: (s != 200).mean()),
    "p50_ms": log.groupby("day")["latency_ms"].median(),
    "p95_ms": log.groupby("day")["latency_ms"].quantile(0.95),
    "debt_missing": log.groupby("day")["debt_ratio"].apply(lambda s: s.isna().mean()),
    "mean_score": ok.groupby("day")["score"].mean(),
    "approval": ok.groupby("day")["approved"].mean(),
})
print(log.shape, list(log.columns[:4]))
print(summary.round(3).to_string())
(2800, 9) ['request_id', 'day', 'model_version', 'status']
     requests  err_rate  p50_ms   p95_ms  debt_missing  mean_score  approval
day
1         400     0.000   39.00   68.120         0.000       0.397     0.698
2         400     0.000   40.30   62.905         0.000       0.420     0.650
3         400     0.000   40.20   69.610         0.000       0.411     0.678
4         400     0.000   40.85   66.605         0.000       0.405     0.660
5         400     0.000   40.15   64.220         0.288       0.313     0.782
6         400     0.065   43.85  275.410         0.000       0.412     0.676
7         400     0.000   39.05   63.235         0.000       0.406     0.670

The two incidents look completely different in the summary. Day 6 is a service problem: 6.5 % of requests failed and the p95 latency went from about 65 ms to 275 ms while the median barely moved (43.85 ms), the typical signature of a slow dependency hitting part of the traffic. Every RED dashboard shows it. Day 5 is invisible there: no errors, normal latency. Only the data and prediction layers react: debt_missing is 0.288, the mean score falls from about 0.41 to 0.313, and the approval rate rises from 0.65 to 0.70 on normal days to 0.782. Without the missing-rate column, a rising approval rate could pass for a good week. Note that mean_score and approval use only the successful requests; mixing in the failed ones (score NaN) would hide a real number behind a missing one.

Joining delayed outcomes

Outcomes arrive later and carry the request id. Here the "defaulted within 90 days" label is known for days 1 to 5 (in reality, for loans old enough). A left join keeps every prediction, so the label coverage per day is visible, and the error is computed only where a label exists.

python · try it yourself
import numpy as np
import pandas as pd

rng = np.random.default_rng(1)
n, days = 400, 7
log = pd.DataFrame({"request_id": [f"d{d}-{i:04d}" for d in range(1, days + 1) for i in range(n)],
                    "day": np.repeat(np.arange(1, days + 1), n)})
true_risk = rng.beta(2, 6, len(log))                       # what really drives default
noise = rng.normal(0, 0.08, len(log))
log["score"] = np.clip(true_risk + noise - np.where(log["day"] == 5, 0.12, 0.0), 0, 1)

# the outcome table: one row per matured loan, produced by another system weeks later
matured = log[log["day"] <= 5]
outcomes = pd.DataFrame({"request_id": matured["request_id"],
                         "defaulted": (rng.random(len(matured)) < true_risk[: len(matured)]).astype(int)})

joined = log.merge(outcomes, on="request_id", how="left", validate="one_to_one")
joined["pred_default"] = (joined["score"] >= 0.5).astype(int)
lab = joined.dropna(subset=["defaulted"])
per_day = pd.DataFrame({
    "label_coverage": joined.groupby("day")["defaulted"].apply(lambda s: s.notna().mean()),
    "mean_score": joined.groupby("day")["score"].mean(),
    "default_rate": lab.groupby("day")["defaulted"].mean(),
    "brier": lab.groupby("day").apply(lambda g: ((g["score"] - g["defaulted"]) ** 2).mean(),
                                      include_groups=False),
})
print(per_day.round(3).to_string())
     label_coverage  mean_score  default_rate  brier
day
1               1.0       0.245         0.242  0.169
2               1.0       0.264         0.232  0.158
3               1.0       0.241         0.245  0.172
4               1.0       0.256         0.242  0.176
5               1.0       0.145         0.272  0.192
6               0.0       0.250           NaN    NaN
7               0.0       0.239           NaN    NaN

Days 6 and 7 have a label coverage of 0.0: their loans have not matured, so their quality columns are NaN instead of a misleading number. For the matured days, the comparison of mean_score (the predicted default rate) with default_rate (the observed one) is a calibration check per day. On days 1 to 4 they agree within about 0.03; on day 5, where this simulation lowered the score by 0.12, the model predicted 0.145 and 0.272 defaulted, and the Brier score (mean squared error of the probability) rose to 0.192 from 0.158 to 0.176. Months later, the labels confirm what the data quality alarm said on the day.

Dashboards and alerts

A useful model dashboard has one row per layer, the same time axis on every panel, and a split by model version: request rate, error rate and p95 latency; missing rates of the top features; score distribution and positive rate against the reference band; quality metrics once labels mature, with the label coverage next to them; and the business KPI. Annotate deployments on the time axis, since most incidents start at one.

Alerts follow the rules in alert design: alert on symptoms users feel, page a human only for what needs action now, send the rest to a ticket queue, and give every alert a runbook. For models that usually means:

  • Page: the service is down or failing its latency SLO, or the model returns invalid output (NaN, out of range), or a data quality check fails on a large share of traffic.
  • Ticket: drift on an important feature, the positive rate outside its normal band for a day, a quality metric worse than the gate for a full label cohort.
  • Report: everything else (weekly drift report, per-segment quality).

The rules can live in code and be tested like code. Here they are evaluated on the daily summary printed by the first example (copied in, rounded):

python · try it yourself
import pandas as pd

summary = pd.DataFrame({
    "day": [1, 2, 3, 4, 5, 6, 7],
    "err_rate": [0.000, 0.000, 0.000, 0.000, 0.000, 0.065, 0.000],
    "p95_ms": [68.1, 62.9, 69.6, 66.6, 64.2, 275.4, 63.2],
    "debt_missing": [0.0, 0.0, 0.0, 0.0, 0.288, 0.0, 0.0],
    "approval": [0.698, 0.650, 0.678, 0.660, 0.782, 0.676, 0.670],
})
REFERENCE_APPROVAL = 0.67                 # from the validation period of this model version

rules = [  # (name, severity, condition on one day's row)
    ("error rate above 1 % (SLO)", "page",   lambda r: r.err_rate > 0.01),
    ("p95 latency above 200 ms",   "page",   lambda r: r.p95_ms > 200),
    ("debt_ratio missing > 5 %",   "page",   lambda r: r.debt_missing > 0.05),
    ("approval rate off by > 5 pts", "ticket", lambda r: abs(r.approval - REFERENCE_APPROVAL) > 0.05),
]
for r in summary.itertuples(index=False):
    fired = [f"{sev.upper()}: {name}" for name, sev, cond in rules if cond(r)]
    print(f"day {r.day}: " + ("; ".join(fired) if fired else "ok"))
day 1: ok
day 2: ok
day 3: ok
day 4: ok
day 5: PAGE: debt_ratio missing > 5 %; TICKET: approval rate off by > 5 pts
day 6: PAGE: error rate above 1 % (SLO); PAGE: p95 latency above 200 ms
day 7: ok

Each incident triggers the alert that names its cause. Day 5 pages for the missing field and opens a ticket for the approval rate (0.782 against the reference 0.67): one of them is the symptom, the other the explanation, and an on-call engineer reading both knows where to look. Day 6 pages twice for the same slow dependency; a real alerting system would group related alerts into one incident.

Pitfalls

  • Only service metrics. A model that answers fast and wrong is green on every RED panel. Layers 2 and 3 are cheap; add them on day one.
  • No request id, no join. Without an id on both the prediction and the outcome, model quality can never be measured. Adding it later does not recover the past.
  • Logging what the client sent instead of what the model saw. If imputation or feature lookup happens inside the service, log the values after it, or you will not see that the service filled 30 % of a column with zeros.
  • Comparing quality across unequal label maturity. A week with 20 % of its labels in is not comparable with a fully labelled month.
  • Alerting on every drift statistic. Dozens of features times daily tests produce noise (why); page on symptoms, ticket the rest.
  • Averages hide segments. A stable overall error can hide a collapse in one region or product. Slice quality metrics by the segments that matter, as governance does for fairness.

Practice

  1. In the first example, which layer would have caught the day 5 problem first, and which signal shows that it was not real customer change?
  2. Add a check to the alert rules that fires when the model returns a score below 0 or above 1, or a NaN, for a request that returned status 200. Which severity should it get?
  3. Why does the join in the second example use how="left" and validate="one_to_one"?
Answers
  1. Data quality (layer 2): debt_missing went from 0 to about 0.3 on day 5. The prediction layer also saw it (mean score down, approval up), but the missing rate points to the cause: the applicants did not change, a field went empty and the default of 0 made them look safe.
  2. For example ("invalid score", "page", lambda r: r.invalid_scores > 0), with invalid_scores counted per day as ((ok.score < 0) | (ok.score > 1) | ok.score.isna()).sum(). Page: invalid output is served to users right now and no label delay is involved.
  3. A left join keeps every prediction, including those without an outcome yet, so label coverage can be measured instead of silently shrinking the data. validate="one_to_one" makes pandas raise an error if a request id appears twice on either side, which would otherwise duplicate rows and distort every metric.

Test yourself

A model service shows 0 % errors and a stable p95 latency, but the approval rate jumped from about 0.67 to 0.78. Which layer flagged the problem?

  1. Service health
  2. Inputs and predictions (the prediction distribution)
  3. Business KPIs
  4. None, everything is fine

What must a prediction log contain so that model quality can be computed later?

  1. Only the score
  2. A request id that the outcome also carries, plus the model version and the output
  3. The training data
  4. The full HTTP headers

Which of these should page a human at night?

  1. PSI of 0.12 on a minor feature
  2. A weekly per-segment report
  3. The service returning NaN scores on 5 % of requests
  4. A label coverage of 40 % for last week

Why are data quality and prediction monitors needed if model quality is what matters?

  1. They are more accurate
  2. Labels arrive late, so these label-free signals are the only same-day view
  3. Regulators require them
  4. They replace labels