A model in production can be up, fast, and wrong at the same time. Ordinary SLOs (availability, latency) say nothing about whether its answers are any good, so ML services need ML SLOs as well: prediction quality measured against delayed ground truth, the freshness of its features, drift of its inputs and outputs, and fairness across groups. When one of them breaks, that is a model incident, with a severity, an incident commander, a mitigation (usually a rollback or a fallback), and a postmortem. This lesson follows one week of a credit-risk model in production, and shows the two failures that ordinary monitoring misses: accuracy that decays slowly while every dashboard is green, and a model that is fine on average and unfair to one group.
Difficulty: Advanced · Know this first: Lesson 333, Lesson 220
By the end of this lesson you can work at four levels:
This page teaches it with a plain-language analogy, an animated diagram with normal and failure scenarios, a simulator, a quiz, basic, intermediate, advanced, and master checks, the expert detail ("Go deeper"), a production incident, a hands-on lab with commands and their output, and a production design exercise.
This bar adds up minutes of review each week that keep a model inside its SLOs. It is a worked example, not a measurement. The quality and fairness hops are where a model goes wrong with every service dashboard green.
Pick what happens to the model and which monitors exist. Labels for this model arrive about 60 days after each decision.
Three questions. No score is saved anywhere — this is just you against the material.
ML reliability grows in four levels: reading the monitors, defining ML SLOs, responding to model incidents, and governing models.
At the basic level you can say whether a model is healthy, and on which measures.
Where it breaks: reading a green service dashboard as "the model is fine".
Try it: Basic
Which kind of drift can only be seen once labels arrive?
Now do it: Find the label delay for one model you run.
At the intermediate level every production model has quality and drift objectives with owners.
Try it: Intermediate
Labels arrive 60 days late. How do you watch quality in the meantime?
Now do it: Pick a proxy for your model's outcome.
At the advanced level a broken ML SLO is an incident with a tested response.
Try it: Advanced
Fairness by age breaches its threshold. What is the safest immediate mitigation?
Now do it: Write the mitigation section of a model runbook.
At the master level models are governed assets with records that stand up to an audit.
Trade-off: fairness and quality SLOs cost data work and slow some releases, and they are the only way to know a model is doing its job.
Try it: Master
A regulator asks which model version declined an applicant last March, and why. What do you need?
Now do it: Try to answer that question for one real decision.
ML SLOs for one model, written the way service SLOs are. The numbers are examples; set yours from history and from what the business needs.
model: credit-risk
owner: team-credit-ml # paged for quality and fairness breaches
slos:
- name: availability
sli: successful predictions / all requests
objective: 99.9% over 30 days
- name: latency
sli: predictions answered within 120 ms
objective: 99% over 30 days
- name: quality
sli: AUC on decisions with a 60-day delinquency label
objective: ">= 0.78, rolling 30 days, overall and per region"
- name: fairness
sli: approval rate of each age band / overall approval rate
objective: ">= 0.80 for every band, monthly"
- name: feature-freshness
sli: predictions whose features are under 2 hours old
objective: 99.5% over 7 days
early_warning: # investigated, not paged
- input PSI per top-10 feature > 0.2 against the training set
- score PSI > 0.1 week over week
- manual-review overturn rate > 8%
mitigations: [rollback to previous champion, rule-based fallback, review all borderline scores, pause auto-decline]
Population stability index for a score or feature, bucketed by the reference's deciles: PSI = Σ (actual% − expected%) × ln(actual% / expected%). A common reading: under 0.1 stable, 0.1 to 0.25 worth a look, over 0.25 a large shift.
Fairness measures pull in different directions; you usually cannot satisfy all at once. Demographic parity compares approval rates. Equal opportunity compares approval rates among people who would repay. Calibration within groups asks whether a score of 0.2 means the same risk in every group. Choose with legal and domain owners, write the choice down, and measure it.
This is a composite of a failure pattern that keeps repeating; the details are illustrative. Eleven green weeks.
The model has a quality SLO on labelled outcomes with a burn alert, weekly drift reports on inputs and scores with an owner who investigates each alert, early-delinquency proxies on the dashboard, and product changes that shift the applicant mix now notify the model owner.
Everything here runs on any Linux machine: your own laptop, WSL on Windows (run wsl --install in PowerShell once), or a small cloud VM. The Python needs only Python 3 and its standard library; check that you have it with python3 --version.
Before you start: Linux and Python 3. The optional steps use sqlite3 (sudo apt install sqlite3).
Type each one, read what it prints, and compare it with the note above it.
Make a small prediction log: decision time, model version, age band, score, decision, and the outcome when it is known.
mkdir -p ~/labs/mlslo && cd ~/labs/mlslo
python3 - <<'EOF'
import sqlite3, random
r = random.Random(1)
c = sqlite3.connect("predictions.db")
c.execute("create table p(day int, version text, age text, score real, approved int, defaulted int)")
for day in range(90):
for _ in range(200):
age = r.choice(["18-30", "31-60", "61+"])
risk = r.random()
score = min(1, max(0, risk + r.gauss(0, 0.25)))
label = int(r.random() < risk * 0.3) if day < 30 else None # labels only for decisions over 60 days old
c.execute("insert into p values(?,?,?,?,?,?)", (day, "v31", age, score, int(score < 0.5), label))
c.commit()
EOF
ls -la predictions.dbMeasure the label delay: how many decisions have an outcome yet?
sqlite3 predictions.db "select count(*) total, sum(defaulted is not null) labelled, max(day) - max(case when defaulted is not null then day end) days_without_labels from p;"
Approval rate by age band, the first fairness question to ask.
sqlite3 -header -column predictions.db "select age, count(*) n, round(avg(approved), 3) approval_rate from p group by age;"
ml_slo.pyThis program runs a week-by-week monitor for a model whose inputs drift after a pricing change: data drift (PSI of the score), the quality SLO (AUC on decisions old enough to have labels), and fairness (approval rate of each age band against the overall rate). It shows that drift raises the alarm weeks before the quality SLO can, because labels arrive 60 days late. Save it as ml_slo.py, then run it.
# ml_slo.py
import math
import random
rnd = random.Random(7)
LABEL_DELAY_WEEKS = 9
QUALITY_OBJECTIVE = 0.78
FAIRNESS_MIN_RATIO = 0.80
def week_of_decisions(week):
rows = []
shift = 0.0 if week < 4 else min(0.5, 0.08 * (week - 3)) # the pricing change starts in week 4
for _ in range(1500):
age = rnd.choice(["18-30", "31-60", "61+"])
risk = min(1.0, max(0.0, rnd.betavariate(0.5, 2.0) + shift * rnd.random()))
noise = 0.08 + 0.6 * shift # the model is less sure about new applicants
score = min(1.0, max(0.0, risk + rnd.gauss(0, noise)))
if age == "61+":
score = min(1.0, score + 0.15) # proxies for age push older applicants' scores up
rows.append((age, score, int(score < 0.2), int(rnd.random() < risk)))
return rows
def auc(pairs):
pos = [s for s, y in pairs if y]; neg = [s for s, y in pairs if not y]
ranked = sorted((s, y) for s, y in pairs)
rank_sum = sum(i + 1 for i, (s, y) in enumerate(ranked) if y)
return (rank_sum - len(pos) * (len(pos) + 1) / 2) / (len(pos) * len(neg))
def psi(ref, cur, edges=(0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9)):
def shares(xs):
counts = [0] * (len(edges) + 1)
for x in xs:
counts[sum(x >= e for e in edges)] += 1
return [max(c / len(xs), 1e-4) for c in counts]
e, a = shares(ref), shares(cur)
return sum((ai - ei) * math.log(ai / ei) for ei, ai in zip(e, a))
weeks = [week_of_decisions(w) for w in range(16)]
reference = [s for _, s, _, _ in weeks[0]]
print("week score PSI drift AUC (labelled) quality SLO approval 61+/all fairness")
for w in range(1, 16):
rows = weeks[w]
p = psi(reference, [s for _, s, _, _ in rows])
labelled = w - LABEL_DELAY_WEEKS
if labelled >= 0:
a = auc([(s, y) for _, s, _, y in weeks[labelled]])
quality = f"{a:.3f} (wk {labelled:>2})"
slo = "BREACH" if a < QUALITY_OBJECTIVE else "ok"
else:
quality, slo = "no labels yet", "-"
overall = sum(d for _, _, d, _ in rows) / len(rows)
older = [d for g, _, d, _ in rows if g == "61+"]
ratio = (sum(older) / len(older)) / overall
print(f"{w:>4} {p:9.3f} {'ALERT' if p > 0.25 else 'ok':<7} {quality:<15} {slo:<12} {ratio:16.2f} {'BREACH' if ratio < FAIRNESS_MIN_RATIO else 'ok'}")
Run it, and you should see this output:
$ python3 ml_slo.py week score PSI drift AUC (labelled) quality SLO approval 61+/all fairness 1 0.012 ok no labels yet - 0.53 BREACH 2 0.004 ok no labels yet - 0.60 BREACH 3 0.003 ok no labels yet - 0.56 BREACH 4 0.046 ok no labels yet - 0.59 BREACH 5 0.200 ok no labels yet - 0.55 BREACH 6 0.319 ALERT no labels yet - 0.53 BREACH 7 0.470 ALERT no labels yet - 0.68 BREACH 8 0.605 ALERT no labels yet - 0.69 BREACH 9 0.780 ALERT 0.828 (wk 0) ok 0.72 BREACH 10 0.871 ALERT 0.816 (wk 1) ok 0.71 BREACH 11 0.774 ALERT 0.812 (wk 2) ok 0.70 BREACH 12 0.801 ALERT 0.794 (wk 3) ok 0.61 BREACH 13 0.841 ALERT 0.738 (wk 4) BREACH 0.79 BREACH 14 0.891 ALERT 0.717 (wk 5) BREACH 0.76 BREACH 15 0.914 ALERT 0.686 (wk 6) BREACH 0.75 BREACH
The same Linux steps, made into a real script you can keep and run again. It uses the Bash features a production script needs: functions (one per step), an array of step names, arguments to choose steps, a case for options, exit codes recorded for each step, and a trap that prints a summary even when you stop it with Ctrl+C. Make a folder for this lesson (mkdir -p ~/labs/ml-slos-and-model-incidents && cd ~/labs/ml-slos-and-model-incidents) and save this as lab.sh.
#!/usr/bin/env bash
# The Linux steps of "ML SLOs and Model Incidents: Accuracy, Drift, Fairness, and Response", as one script (save it as lab.sh).
#
# ./lab.sh run every step, in order
# ./lab.sh 2 4 run only steps 2 and 4
# ./lab.sh --list list the steps
#
# The steps share one shell, so a later step can use what an earlier one set up (a folder,
# a variable, a container): run them all in order the first time. Your own scripts should
# start with "set -euo pipefail"; this one runs teaching commands, and some of them fail on
# purpose, so it records each step's exit code instead of stopping at the first failure.
STEPS=(
'Make a small prediction log: decision time, model version, age band, score, decision, and the outcome when it is known.'
'Measure the label delay: how many decisions have an outcome yet?'
'Approval rate by age band, the first fairness question to ask.'
)
step_1() {
mkdir -p ~/labs/mlslo && cd ~/labs/mlslo
python3 - <<'EOF'
import sqlite3, random
r = random.Random(1)
c = sqlite3.connect("predictions.db")
c.execute("create table p(day int, version text, age text, score real, approved int, defaulted int)")
for day in range(90):
for _ in range(200):
age = r.choice(["18-30", "31-60", "61+"])
risk = r.random()
score = min(1, max(0, risk + r.gauss(0, 0.25)))
label = int(r.random() < risk * 0.3) if day < 30 else None # labels only for decisions over 60 days old
c.execute("insert into p values(?,?,?,?,?,?)", (day, "v31", age, score, int(score < 0.5), label))
c.commit()
EOF
ls -la predictions.db
}
step_2() {
sqlite3 predictions.db "select count(*) total, sum(defaulted is not null) labelled, max(day) - max(case when defaulted is not null then day end) days_without_labels from p;"
}
step_3() {
sqlite3 -header -column predictions.db "select age, count(*) n, round(avg(approved), 3) approval_rate from p group by age;"
}
# print a step that has to be run by hand, instead of running it
by_hand() {
echo " (run this one yourself: $1)"
sed 's/^/ /'
}
RESULTS=()
run_step() {
local n=$1 start=$SECONDS code
printf '\n== step %d of %d: %s\n' "$n" "${#STEPS[@]}" "${STEPS[n-1]}"
"step_$n"
code=$?
RESULTS+=("step $n: exit code $code, $((SECONDS - start)) s")
}
summary() {
echo
echo "== summary"
local r
for r in "${RESULTS[@]}"; do echo " $r"; done
}
case "${1:-}" in
-h|--help) sed -n '2,6p' "$0"; exit 0 ;;
--list) for i in "${!STEPS[@]}"; do echo "$((i + 1)). ${STEPS[i]}"; done; exit 0 ;;
esac
[ $# -eq 0 ] && set -- $(seq 1 "${#STEPS[@]}")
for n in "$@"; do
if ! [[ $n =~ ^[0-9]+$ ]] || (( n < 1 || n > ${#STEPS[@]} )); then
echo "there is no step '$n'; try --list" >&2
exit 2
fi
done
trap summary EXIT
trap 'echo; echo "stopped with Ctrl+C"; exit 130' INT
for n in "$@"; do run_step "$n"; done
Then make it executable and run it:
chmod +x lab.sh ./lab.sh --list # the steps ./lab.sh # every step, then a summary of exit codes and times ./lab.sh 2 3 # only steps 2 and 3
New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.
mkdir, ls, cd, If...Else, Here documents.You own a credit-decision model that makes 40,000 decisions a day, and outcomes arrive 60 days later. Define its SLOs, monitors, and incident response.
Which SLOs does it need beyond availability and latency, with which objectives? What do you watch during the label delay? Which fairness measures apply, and who chose them? What does each alert trigger, and what are the mitigations? What records do you keep, and for how long?
Say 40,000 decisions a day, a 60-day label delay, 5% defaults, 4 regions, 6 age bands, and a regulator that may ask about any decision for 5 years.
Service SLOs with burn-rate alerts and a rule-based fallback; a prediction log with features, version, and reason codes kept 5 years under access controls; daily label joins and a 30-day AUC SLO overall and per region; weekly PSI on top features and the score; early proxies; monthly fairness SLOs by age band chosen with legal; a runbook with rollback, fallback, and review-all-borderline mitigations; model card and approval per version; quarterly review with the risk committee.
A tight quality objective pages more often, and lets you act weeks before finance does; fairness constraints can lower overall accuracy slightly, and that is a business and legal decision to make on purpose; five years of prediction logs cost storage and need strict access, and they are what an appeal or audit needs.
Each row is one way this system went wrong in the diagram's scenarios. The hop number is where to look first.
| Scenario | Where | Effect | What goes wrong |
|---|---|---|---|
| Silent accuracy decay | Hop 4: Quality SLO | Breaks | There is no quality SLO. After a pricing change attracts a different kind of applicant, the inputs drift and the model's ranking gets steadily worse: AUC falls from 0.81 to 0.71 over eleven weeks. Every dashboard is green. |
| Fair on average | Hop 6: Fairness | Breaks | Fairness is not measured by group. An external audit finds applicants over 60 with the same repayment record are approved at about half the rate of others: "years at current address" and "months since last new account" act as proxies for age. |
The official documentation and standards behind this lesson. Versions and defaults change; when a command or field here differs from them, trust the official page.
Last updated . Next review due by November 2027. Found something out of date? Tell me.