TExcelTAD
Home › ML Projects: 15 End-to-End Builds › Project 15: Production ML Platform

Project 15: Production ML Platform

TAD Retail, a fictional retailer, has three teams with a model each: payments runs a card-fraud scorer (the kind built in Project 6), stores run a daily sales forecast (Project 7), and customer service a spam filter (Project 5). Each team has its own scripts, and last quarter brought three incidents: a fraud feature computed differently in training and in serving, a forecast deployed from a laptop without any evaluation, and a monitoring channel with so many drift alerts that nobody read the one that mattered. You are the platform engineer. Your job is not a better model; it is the shared machinery that makes every team's model safe to ship and to run. Level: expert. Main skills: feature pipelines with point-in-time correctness and parity tests, a model registry with lineage, a CI gate that each team configures, shadow and canary releases, fleet-level monitoring and alert policy, a retraining policy and a runbook.

The deployment course's mini project built the loop for one model: package, serve, log, detect drift, retrain, gate, roll back. This project is one level up. Every technique is taught in Deployment and MLOps; here they become contracts between a platform and several teams, and the hard questions are the ones that only appear with more than one model: whose features, whose gate, and how many alerts per day a human can read.

Goal and success criteria

Fixed before anything was built:

Criterion Target Measured on
Training-serving skew of shared features 0 mismatches parity test, 200 sampled events per feature set
Models in production that passed their team's gate 100 % the registry: every champion has gate = passed
Every version traceable data hash, code commit, feature set, artifact hash the registry
Release shadow first; canary on a stable 10 % of customers; rollback is one alias move the router
Alert load under 0.1 false pages per day for the whole fleet 30 monitors, 60 simulated days
Real drift paged within 14 days of its onset the same simulation
Runbook written for each alert type review

The data

Everything is generated with fixed seeds, so the scores are about the generators, not about any real retailer. The fraud data is make_classification with 3 % positives, 4,000 rows in time order (the first 3,000 for training, the last 1,000 as holdout and as traffic); the sales data is two years of one store's daily sales with a trend, a weekly cycle, promotions and noise; the transaction log for the feature pipeline has 1,500 card transactions over 60 days. Real card and customer data is personal data under strict rules (payment-card standards, data-protection law): the platform's job includes access control on feature tables, retention limits on prediction logs and pseudonymised ids in every log (governance, ML security).

featuresbatch + online team training3 models CI gateper-team rules registryaliases, lineage release routershadow, canary 10 % fleet monitor30 drift monitors alert policyrunbook, retraining online features at request time rollback = move thechampion alias back

Step 1: one feature definition, two implementations, a parity test

Fraud features such as "transactions of this card in the last 7 days" are computed twice: by a batch job over history for training, and by an online service at request time. If the two disagree, the model is trained on one feature and served another: training-serving skew, the first incident. Feature stores (Feast, Tecton, the cloud platforms' feature stores) exist mostly to solve this, with point-in-time joins for training and a low-latency store for serving. The platform rule is simpler and works with or without one: a named, versioned feature set, and a CI test that compares the two implementations on sampled events. The windows must end before the event (leakage rules, lag and rolling features).

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

rng = np.random.default_rng(0)
n = 1500                                                       # card transactions over 60 days
log = pd.DataFrame({"card": rng.integers(0, 120, n),
                    "ts": pd.Timestamp("2026-01-01") + pd.to_timedelta(np.sort(rng.uniform(0, 60, n)), unit="D"),
                    "amount": rng.lognormal(3.5, 0.8, n).round(2)}).sort_values(["card", "ts"]).reset_index(drop=True)

FEATURES = {"tx_count_7d": "number of the card's transactions in the 7 days before this one",
            "amount_mean_30d": "mean amount of the card's transactions in the 30 days before this one (NaN if none)"}
FEATURE_SET = "card_activity:v3"

def offline_buggy(log):                                       # a first batch job: aggregates over the whole history,
    g = log.groupby("card")                                    # future transactions included
    return pd.DataFrame({"tx_count_7d": g["ts"].transform(lambda s: s.diff().lt(pd.Timedelta("7D")).sum()),
                         "amount_mean_30d": g["amount"].transform("mean")})

def offline_point_in_time(log):                               # batch job: windows that end just before each event
    out = []
    for _, grp in log.groupby("card"):
        s = grp.set_index("ts")
        out.append(pd.DataFrame({"tx_count_7d": s["amount"].rolling("7D", closed="left").count().fillna(0).to_numpy(),
                                 "amount_mean_30d": s["amount"].rolling("30D", closed="left").mean().to_numpy()},
                                index=grp.index))
    return pd.concat(out).sort_index()

def online(history, card, ts):                                # serving: what the feature service computes per request
    h = history[(history["card"] == card) & (history["ts"] < ts)]
    last7, last30 = h[h["ts"] >= ts - pd.Timedelta("7D")], h[h["ts"] >= ts - pd.Timedelta("30D")]
    return {"tx_count_7d": float(len(last7)), "amount_mean_30d": float(last30["amount"].mean()) if len(last30) else np.nan}

sample = log.sample(200, random_state=0)                      # the parity test a CI job runs on every change
ref = pd.DataFrame([online(log, r.card, r.ts) for r in sample.itertuples()], index=sample.index)
for name, table in [("buggy batch job", offline_buggy(log)), ("point-in-time batch job", offline_point_in_time(log))]:
    t = table.loc[sample.index]
    bad = {f: int((~np.isclose(t[f], ref[f], equal_nan=True)).sum()) for f in FEATURES}
    print(f"{FEATURE_SET} {name:24}: mismatches with the online service in 200 events {bad}")
card_activity:v3 buggy batch job         : mismatches with the online service in 200 events {'tx_count_7d': 199, 'amount_mean_30d': 200}
card_activity:v3 point-in-time batch job : mismatches with the online service in 200 events {'tx_count_7d': 0, 'amount_mean_30d': 0}

The first batch job aggregates over each card's whole history: the 30-day mean includes transactions after the event, and the count is not a 7-day window at all. It disagrees with the online service on 199 and 200 of 200 events, yet it would train fine and score well offline, because it sees the future. The point-in-time job (rolling(..., closed="left"), which leaves the current row and everything later out) matches the service on all 200. This test runs in CI whenever either implementation changes, and the feature set's version (card_activity:v3) is recorded with every model trained on it.

Step 2: the registry and a gate each team declares

The second incident was a model that skipped evaluation. The platform answers with a rule: a version reaches staging only through CI, and CI runs the gate that the owning team declared in its repository: which metric, which direction, the margin over the champion, an absolute floor, a size limit, and that the version was trained on the feature set that serving provides. The platform enforces the rules; the teams own them (model registry, CI/CD for ML). The fraud team gates on PR-AUC on a time-ordered holdout, the right metric at 3 % positives (ROC and PR curves); the stores team on MASE, the mean absolute error divided by the in-sample error of the "same as 7 days ago" forecast, so that MASE below 1 means better than seasonal naive (time-series backtesting):

MASE⁡=1h∑t=1h∣yt−y^t∣1n−7∑t=8n∣yt−yt−7∣\operatorname{MASE} = \frac{\frac{1}{h} \sum_{t=1}^{h} \lvert y_t - \hat{y}_t \rvert}{\frac{1}{n - 7} \sum_{t=8}^{n} \lvert y_t - y_{t-7} \rvert}
python · try it yourself
import hashlib, io, pickle
import numpy as np
from sklearn.datasets import make_classification
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.linear_model import LinearRegression, LogisticRegression, Ridge
from sklearn.metrics import average_precision_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

# two teams' data, both in time order; the last part is the holdout the gate evaluates on
X, y = make_classification(n_samples=4000, n_features=8, n_informative=5, weights=[0.97], flip_y=0.01,
                           class_sep=0.8, random_state=0)
Xf_tr, yf_tr, Xf_ho, yf_ho = X[:3000], y[:3000], X[3000:], y[3000:]
rng = np.random.default_rng(1)
t = np.arange(730)                                                # two years of daily sales of one store
sales = 200 + 0.05 * t + 30 * np.sin(2 * np.pi * t / 7) + 20 * (rng.random(730) < 0.1) + rng.normal(0, 8, 730)
lags = np.column_stack([np.roll(sales, k) for k in (7, 14, 21)])[21:]
ys, Xs = sales[21:], lags
Xs_tr, ys_tr, Xs_ho, ys_ho = Xs[:-90], ys[:-90], Xs[-90:], ys[-90:]

def mase(y_true, y_pred, y_train, m=7):                          # error relative to the seasonal-naive error in training
    return np.mean(np.abs(y_true - y_pred)) / np.mean(np.abs(y_train[m:] - y_train[:-m]))
def seasonal_naive():                                             # "same as 7 days ago" as a fixed linear model
    m = LinearRegression()
    m.coef_, m.intercept_, m.n_features_in_ = np.array([1.0, 0.0, 0.0]), 0.0, 3
    return m

def evaluate(name, model):
    if name == "fraud-scorer":
        return {"pr_auc": round(float(average_precision_score(yf_ho, model.predict_proba(Xf_ho)[:, 1])), 3)}
    return {"mase": round(float(mase(ys_ho, model.predict(Xs_ho), ys_tr)), 3)}

registry = {}                                                     # (model, version) -> record
def register(name, model, data, feature_set, commit):
    blob = pickle.dumps(model)
    v = 1 + sum(1 for (n, _) in registry if n == name)
    registry[(name, v)] = {"stage": "candidate", "metrics": evaluate(name, model), "feature_set": feature_set,
                           "data_sha": hashlib.sha256(data.tobytes()).hexdigest()[:8], "commit": commit,
                           "artifact_sha": hashlib.sha256(blob).hexdigest()[:8], "bytes": len(blob)}
    return v

GATES = {   # declared by each team in its repository, enforced by the platform's CI
    "fraud-scorer":   {"metric": "pr_auc", "better": "higher", "margin": 0.01, "floor": 0.30, "max_bytes": 2_000_000},
    "sales-forecast": {"metric": "mase", "better": "lower", "margin": 0.02, "floor": 1.00, "max_bytes": 100_000},
}
SERVING_FEATURE_SET = {"fraud-scorer": "card_activity:v3", "sales-forecast": "store_daily:v1"}

def gate(name, cand, champ):
    g, c, ch = GATES[name], registry[(name, cand)], registry[(name, champ)]
    m, sign = g["metric"], 1 if g["better"] == "higher" else -1
    checks = {f"{m} beats champion by {g['margin']}": sign * (c["metrics"][m] - ch["metrics"][m]) >= g["margin"],
              f"{m} meets floor {g['floor']}": sign * (c["metrics"][m] - g["floor"]) >= 0,
              "feature set matches serving": c["feature_set"] == SERVING_FEATURE_SET[name],
              f"artifact under {g['max_bytes']:,} bytes": c["bytes"] <= g["max_bytes"]}
    return all(checks.values()), checks

register("fraud-scorer", make_pipeline(StandardScaler(), LogisticRegression()).fit(Xf_tr, yf_tr), Xf_tr, "card_activity:v3", "a41f2c0")
register("fraud-scorer", HistGradientBoostingClassifier(random_state=0).fit(Xf_tr, yf_tr), Xf_tr, "card_activity:v3", "b7e9d13")
register("sales-forecast", seasonal_naive(), Xs_tr, "store_daily:v1", "0c55e8a")
register("sales-forecast", Ridge(alpha=1.0).fit(Xs_tr, ys_tr), Xs_tr, "store_daily:v2", "91d0b4f")   # new feature set
registry[("fraud-scorer", 1)]["stage"] = registry[("sales-forecast", 1)]["stage"] = "production"

exit_code = 0
for name in GATES:
    ok, checks = gate(name, 2, 1)
    registry[(name, 2)]["stage"] = "staging" if ok else "rejected"
    exit_code |= not ok
    print(f"{name}: v1 {registry[(name, 1)]['metrics']} -> v2 {registry[(name, 2)]['metrics']}: {'PASS' if ok else 'FAIL'}")
    for k, passed in checks.items():
        print(f"   [{'x' if passed else ' '}] {k}")
for (name, v), r in registry.items():
    print(f"{name:14} v{v} {r['stage']:10} data {r['data_sha']} commit {r['commit']} artifact {r['artifact_sha']} ({r['bytes']:,} B)")
print("CI exit code:", int(exit_code))
fraud-scorer: v1 {'pr_auc': 0.582} -> v2 {'pr_auc': 0.628}: PASS
   [x] pr_auc beats champion by 0.01
   [x] pr_auc meets floor 0.3
   [x] feature set matches serving
   [x] artifact under 2,000,000 bytes
sales-forecast: v1 {'mase': 1.047} -> v2 {'mase': 0.824}: FAIL
   [x] mase beats champion by 0.02
   [x] mase meets floor 1.0
   [ ] feature set matches serving
   [x] artifact under 100,000 bytes
fraud-scorer   v1 production data ba30aa5c commit a41f2c0 artifact d9af9fd2 (1,353 B)
fraud-scorer   v2 staging    data ba30aa5c commit b7e9d13 artifact 7983dc0c (349,215 B)
sales-forecast v1 production data 02884714 commit 0c55e8a artifact 01687351 (370 B)
sales-forecast v2 rejected   data 02884714 commit 91d0b4f artifact dd45aa13 (464 B)
CI exit code: 1
  • Fraud: the gradient-boosted v2 reaches PR-AUC 0.628 against the champion's 0.582 on the 1,000 holdout rows, passes all four checks and moves to staging. It is 349,215 bytes against 1,353 for the logistic regression, well inside the team's limit.
  • Forecast: the ridge model on lags v2 has the better MASE (0.824 against 1.047 for seasonal naive, which, measured on the holdout, is slightly worse than its own training-period error) but is rejected: it was trained on store_daily:v2, and serving still provides store_daily:v1. Deploying it would recreate the skew of step 1. The fix is a feature-set release first, then a re-run of the gate.
  • The exit code is 1, so the pipeline stops; nothing reaches production without passing. Every version carries a data hash, a commit, an artifact hash and its size, which answers the first question of any incident: what exactly is running?

Step 3: the same registry in MLflow (recorded)

The dictionary above is the idea; in practice the registry is a service. Recorded with MLflow 3.17.2 and a local SQLite store: the four versions of step 2 are registered under two model names, with team, feature set and gate result as tags and the stages as aliases. Serving code asks for models:/<name>@champion and never for a number (MLflow tracking).

python · try it yourself
import logging, os
os.environ["MLFLOW_ENABLE_ARTIFACTS_PROGRESS_BAR"] = "false"
import mlflow
from mlflow import MlflowClient
logging.getLogger("mlflow").setLevel(logging.ERROR)
import numpy as np
from sklearn.datasets import make_classification
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.linear_model import LinearRegression, LogisticRegression, Ridge
from sklearn.metrics import average_precision_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

X, y = make_classification(n_samples=4000, n_features=8, n_informative=5, weights=[0.97], flip_y=0.01,
                           class_sep=0.8, random_state=0)                 # the same data as step 2
rng = np.random.default_rng(1)
t = np.arange(730)
sales = 200 + 0.05 * t + 30 * np.sin(2 * np.pi * t / 7) + 20 * (rng.random(730) < 0.1) + rng.normal(0, 8, 730)
Xs, ys = np.column_stack([np.roll(sales, k) for k in (7, 14, 21)])[21:], sales[21:]
naive = LinearRegression()
naive.coef_, naive.intercept_, naive.n_features_in_ = np.array([1.0, 0.0, 0.0]), 0.0, 3
pr = lambda m: average_precision_score(y[3000:], m.predict_proba(X[3000:])[:, 1])
scale = np.mean(np.abs(ys[7:-90] - ys[:-97]))
mase = lambda m: np.mean(np.abs(m.predict(Xs[-90:]) - ys[-90:])) / scale

mlflow.set_tracking_uri("sqlite:///platform.db")
client = MlflowClient()
TRUSTED = ["sklearn.ensemble._hist_gradient_boosting.predictor.TreePredictor"]
def log_version(name, team, model, metric, feature_set, gate):
    mlflow.set_experiment(name)
    with mlflow.start_run():
        mlflow.log_params({"feature_set": feature_set, "estimator": type(model[-1] if hasattr(model, "steps") else model).__name__})
        mlflow.log_metric(metric[0], metric[1](model))
        info = mlflow.sklearn.log_model(model, name="model", registered_model_name=name, pip_requirements=["scikit-learn==1.7.0"],
                                        skops_trusted_types=TRUSTED)     # we trained it ourselves; see model-registry
    client.set_registered_model_tag(name, "team", team)
    v = info.registered_model_version
    client.set_model_version_tag(name, v, "feature_set", feature_set)
    client.set_model_version_tag(name, v, "gate", gate)
    return v

alias = client.set_registered_model_alias
alias("fraud-scorer", "champion", log_version("fraud-scorer", "payments",
    make_pipeline(StandardScaler(), LogisticRegression()).fit(X[:3000], y[:3000]), ("pr_auc", pr), "card_activity:v3", "passed"))
alias("fraud-scorer", "staging", log_version("fraud-scorer", "payments",
    HistGradientBoostingClassifier(random_state=0).fit(X[:3000], y[:3000]), ("pr_auc", pr), "card_activity:v3", "passed"))
alias("sales-forecast", "champion", log_version("sales-forecast", "stores", naive, ("mase", mase), "store_daily:v1", "passed"))
log_version("sales-forecast", "stores", Ridge(alpha=1.0).fit(Xs[:-90], ys[:-90]), ("mase", mase), "store_daily:v2", "rejected")

print("\nplatform inventory")
for rm in client.search_registered_models(order_by=["name ASC"]):
    print(f"{rm.name} (team {rm.tags['team']})")
    for mv in sorted(client.search_model_versions(f"name = '{rm.name}'"), key=lambda m: int(m.version)):
        mv = client.get_model_version(rm.name, mv.version)
        run = client.get_run(mv.run_id)
        metrics = {k: round(val, 3) for k, val in run.data.metrics.items()}
        print(f"   v{mv.version} {run.data.params['estimator']:32} aliases {sorted(mv.aliases)} {mv.tags} {metrics}")
for name in ["fraud-scorer", "sales-forecast"]:
    print(f"serving resolves {name}@champion -> version {client.get_model_version_by_alias(name, 'champion').version}")
Successfully registered model 'fraud-scorer'.
Created version '1' of model 'fraud-scorer'.
Registered model 'fraud-scorer' already exists. Creating a new version of this model...
Created version '2' of model 'fraud-scorer'.
Successfully registered model 'sales-forecast'.
Created version '1' of model 'sales-forecast'.
Registered model 'sales-forecast' already exists. Creating a new version of this model...
Created version '2' of model 'sales-forecast'.

platform inventory
fraud-scorer (team payments)
   v1 LogisticRegression               aliases ['champion'] {'feature_set': 'card_activity:v3', 'gate': 'passed'} {'pr_auc': 0.582}
   v2 HistGradientBoostingClassifier   aliases ['staging'] {'feature_set': 'card_activity:v3', 'gate': 'passed'} {'pr_auc': 0.628}
sales-forecast (team stores)
   v1 LinearRegression                 aliases ['champion'] {'feature_set': 'store_daily:v1', 'gate': 'passed'} {'mase': 1.047}
   v2 Ridge                            aliases [] {'feature_set': 'store_daily:v2', 'gate': 'rejected'} {'mase': 0.824}
serving resolves fraud-scorer@champion -> version 1
serving resolves sales-forecast@champion -> version 1

The inventory is the platform's view of the fleet: two registered models, their owners, every version with its estimator, alias, tags and metric. The metrics are the same as in step 2 (same data, same split). Fraud v2 has the alias staging and waits for release; forecast v2 has no alias and gate = rejected. The skops_trusted_types argument is needed because this MLflow version saves scikit-learn models with skops and refuses tree-based models unless you vouch for them; model registry explains why. A platform check worth adding to CI: no version may carry champion unless its gate tag is passed.

Step 4: shadow, then canary

Fraud v2 passed its gate on historic data. Before it decides anything, the router runs it in shadow: v1 answers every request, v2 scores the same request, and both scores are logged with the row id so outcomes can be joined later (deployment strategies). After the shadow review, the canary sends a stable 10 % of cards to v2: the bucket is a hash of the card id, so a customer never flips between models mid-session.

python · try it yourself
import asyncio, hashlib
import httpx
import numpy as np
from fastapi import FastAPI
from pydantic import BaseModel, Field
from sklearn.datasets import make_classification
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

X, y = make_classification(n_samples=4000, n_features=8, n_informative=5, weights=[0.97], flip_y=0.01,
                           class_sep=0.8, random_state=0)                 # the same data as step 2
MODELS = {1: make_pipeline(StandardScaler(), LogisticRegression()).fit(X[:3000], y[:3000]),
          2: HistGradientBoostingClassifier(random_state=0).fit(X[:3000], y[:3000])}
RELEASE = {"champion": 1, "candidate": 2, "mode": "shadow", "canary_share": 0.10}
THRESHOLD, LOG = 0.3, []

def bucket(card_id):                                   # stable: the same card always lands in the same bucket
    return int(hashlib.sha256(f"fraud-scorer:{card_id}".encode()).hexdigest(), 16) % 100

class Tx(BaseModel):
    card_id: int
    features: list[float] = Field(min_length=8, max_length=8)

app = FastAPI()

@app.post("/score")
async def score(tx: Tx):
    x = np.array([tx.features])
    canary = RELEASE["mode"] == "canary" and bucket(tx.card_id) < 100 * RELEASE["canary_share"]
    served = RELEASE["candidate"] if canary else RELEASE["champion"]
    p = {v: float(MODELS[v].predict_proba(x)[0, 1]) for v in (RELEASE["champion"], RELEASE["candidate"])}
    LOG.append({"mode": RELEASE["mode"], "served": served, "p": p, "row": len(LOG)})     # both scores, always
    return {"alert": p[served] >= THRESHOLD, "model_version": served}

async def main():
    async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client:
        for i in range(3000, 4000):
            if i == 3500:
                RELEASE["mode"] = "canary"                # after the shadow review, start the canary
            await client.post("/score", json={"card_id": i % 400, "features": [round(v, 4) for v in X[i]]})

asyncio.run(main())
lab = y[3000:]                                          # outcomes, known weeks later; joined by row
for mode in ["shadow", "canary"]:
    rows = [r for r in LOG if r["mode"] == mode]
    a1 = np.array([r["p"][1] >= THRESHOLD for r in rows]); a2 = np.array([r["p"][2] >= THRESHOLD for r in rows])
    yy = lab[[r["row"] for r in rows]]
    served2 = np.array([r["served"] == 2 for r in rows])
    print(f"{mode}: {len(rows)} requests, served by v2 {served2.mean():.3f} | alerts v1 {a1.sum()} v2 {a2.sum()}"
          f" | decisions differ {np.mean(a1 != a2):.3f} | frauds {yy.sum()}: caught by v1 {np.sum(a1 & (yy == 1))}, v2 {np.sum(a2 & (yy == 1))}")
    if mode == "canary":
        print(f"   canary group: {served2.sum()} requests, {yy[served2].sum()} frauds; alert rate v2-served {a2[served2].mean():.3f}"
              f" vs v1-served {a1[~served2].mean():.3f}")
shadow: 500 requests, served by v2 0.000 | alerts v1 11 v2 12 | decisions differ 0.002 | frauds 16: caught by v1 10, v2 11
canary: 500 requests, served by v2 0.096 | alerts v1 5 v2 10 | decisions differ 0.010 | frauds 13: caught by v1 4, v2 5
   canary group: 48 requests, 2 frauds; alert rate v2-served 0.021 vs v1-served 0.009
  • Shadow (500 requests): the two models disagree on 1 decision in 500 (0.002); v1 raises 11 alerts, v2 12, and of the 16 frauds that turned out to be in this traffic v1 caught 10 and v2 11. That is the evidence that justifies a canary: same alert volume (the fraud team's analysts have a fixed capacity), slightly more frauds caught, no surprise.
  • Canary (500 requests): v2 served 9.6 % of requests, close to the 10 % of buckets because cards, not requests, are bucketed. The canary group holds 48 requests and 2 frauds: far too few to judge quality. A canary checks operational health (errors, latency, alert rate, here 0.021 against 0.009, i.e. 1 alert against about 4 in the other group); quality evidence comes from the shadow phase and from the weeks of labels after it.
  • Rollback is moving champion back to v1 in the registry; because both scores are logged in every mode, the team can also replay what v1 would have done.

Step 5: monitoring a fleet, not a model

The third incident was alert fatigue. A single drift monitor looks well behaved in the lab: one feature, a gradual shift of half a standard deviation ramping from day 21 to day 40, and the two-sample KS statistic D=max⁡x∣Fref(x)−Flive(x)∣D = \max_x \lvert F_{\text{ref}}(x) - F_{\text{live}}(x) \rvert with a threshold of 0.11, just above its 5 % critical value 1.358(n+m)/(nm)=0.1051.358 \sqrt{(n + m)/(nm)} = 0.105 for n=200n = 200 live and m=1000m = 1000 reference values, which the status box shows (data drift):

0.00.40.8−4−2024densityFeature x, day 60max gapreferenceliveDay 60: KS D = 0.291threshold 0.11: ALARMlive mean 0.54 (true 0.50)model error today 0.115drift starts on day 21KS 5 % critical D (n=200): 0.1050.00.10.20.30102030405060dayKS D per daydrift startsstatisticthresholdonsetfalse alarmalarm

At the end of the 60 days the readouts say: first alarm on day 12, a false alarm (D = 0.114, nine days before the drift starts); detection delay 0, because day 21 happens to read 0.116 while the mean has barely moved (0.025), a lucky hit, not a detection; then an alarm on day 24 and every day from day 27 on, 37 days in alarm in total. Raise the threshold to 0.12 and the readouts change to: first alarm day 27, delay 6, no false alarms. Now the same monitor with no drift at all:

0.00.40.8−4−2024densityFeature x, day 60max gapreferenceliveDay 60: KS D = 0.104threshold 0.11: no alarmlive mean 0.04 (true 0.00)model error today 0.150no drift: every alarm is falseKS 5 % critical D (n=200): 0.1050.000.050.100.150102030405060dayKS D per daystatisticthresholdonsetfalse alarmalarm

One false alarm day out of 60 (day 12 again: the same random windows). Move the threshold down to 0.10 or change the random run to see how the count moves; at the critical value itself about 5 % of days should alarm. One monitor at a few percent is tolerable. TAD Retail has 30 monitored features across three models (12 for fraud, 10 for the forecast, 8 for spam), and every one of them is a coin with a 5 % chance of a false alarm every day. The simulation below runs 30 such monitors for 60 days, with the same KS statistic and one real drift (fraud feature 0, the lab's gradual ramp), and compares alert policies: page at once, page after kk days in a row, and a Bonferroni-corrected threshold, the critical value at α/30\alpha / 30, from the asymptotic formula c(α)=−ln⁡(α/2)/2c(\alpha) = \sqrt{-\ln(\alpha / 2) / 2} times (n+m)/(nm)\sqrt{(n + m)/(nm)}.

python · try it yourself
import numpy as np

rng = np.random.default_rng(0)
DAYS, N, M = 60, 200, 1000                       # days, live window per day, reference size
MONITORS = [(m, f) for m, k in [("fraud-scorer", 12), ("sales-forecast", 10), ("spam-filter", 8)] for f in range(k)]
ref = {mf: np.sort(rng.normal(size=M)) for mf in MONITORS}
def ks(a, b):                                    # two-sample Kolmogorov-Smirnov D for sorted arrays
    grid = np.concatenate([a, b])
    return float(np.max(np.abs(np.searchsorted(a, grid, side="right") / len(a) - np.searchsorted(b, grid, side="right") / len(b))))
crit = lambda alpha: np.sqrt(-np.log(alpha / 2) / 2) * np.sqrt((N + M) / (N * M))     # asymptotic KS critical value

D = np.zeros((DAYS, len(MONITORS)))
for d in range(DAYS):
    for j, mf in enumerate(MONITORS):
        mu = 0.5 * min(1, max(0, (d + 1 - 20) / 20)) if mf == ("fraud-scorer", 0) else 0.0   # one real drift
        D[d, j] = ks(ref[mf], np.sort(mu + rng.normal(size=N)))
onset, true_j = 21, 0

def policy(thr, consecutive):
    above = D > thr
    run = np.zeros_like(above, dtype=int)
    for d in range(DAYS):
        run[d] = (run[d - 1] + 1) * above[d] if d else above[d]
    fire = run >= consecutive                    # page when a monitor has been above for k days in a row
    false_pages = int(np.sum(fire[:, 1:])) + int(np.sum(fire[:onset - 1, 0]))
    first = next((d + 1 for d in range(onset - 1, DAYS) if fire[d, 0]), None)
    return false_pages, first

print(f"{len(MONITORS)} monitors over {DAYS} days; one real drift (fraud-scorer feature 0, ramp from day {onset})")
for name, thr, k in [("KS 5% per monitor, page at once", crit(0.05), 1),
                     ("KS 5%, 3 days in a row", crit(0.05), 3),
                     ("KS 5%/30 (Bonferroni), page at once", crit(0.05 / len(MONITORS)), 1),
                     ("KS 5%/30, 2 days in a row", crit(0.05 / len(MONITORS)), 2)]:
    fp, first = policy(thr, k)
    print(f"{name:38} threshold D > {thr:.3f}: false pages {fp:3} ({fp / DAYS:.2f} per day) | real drift paged on day {first}")
30 monitors over 60 days; one real drift (fraud-scorer feature 0, ramp from day 21)
KS 5% per monitor, page at once        threshold D > 0.105: false pages  81 (1.35 per day) | real drift paged on day 21
KS 5%, 3 days in a row                 threshold D > 0.105: false pages   1 (0.02 per day) | real drift paged on day 25
KS 5%/30 (Bonferroni), page at once    threshold D > 0.146: false pages   7 (0.12 per day) | real drift paged on day 28
KS 5%/30, 2 days in a row              threshold D > 0.146: false pages   0 (0.00 per day) | real drift paged on day 33

Paging on every monitor at its 5 % critical value produces 81 false alarm-days in 60 days, 1.35 per day: exactly the channel nobody reads. Requiring 3 days in a row cuts that to 1 false alarm-day and still pages the real drift on day 25, 4 days after onset. The Bonferroni threshold (D > 0.146) alone leaves 7 false alarm-days and pages on day 28; combined with 2 days in a row it has none and pages on day 33. Against the criteria (under 0.1 false pages per day, real drift within 14 days), "5 %, 3 days in a row" and "Bonferroni, 2 days in a row" both pass; the first is faster, the second quieter. The platform picks the first and reviews it monthly, because these are the generator's numbers: real features are not independent normal variables, so a policy is set on the fleet's own history of alarms (monitoring ML systems).

Input drift is only half of it. It is a label-free early warning; the judge is the model's error once outcomes arrive, watched with an error-based detector such as Page-Hinkley (concept drift detection). Fraud labels arrive after chargebacks (weeks), sales the next day, spam labels when users report it, so each model's monitor runs on its own clock.

Step 6: the retraining policy and the runbook

What happens after a page is policy, written down before it is needed (retraining strategies, rollback and incidents):

Signal fraud-scorer sales-forecast spam-filter
Scheduled retraining monthly, on a 12-month window weekly, expanding window monthly
Input drift page (step 5 policy) investigate; retrain if labels confirm investigate (promotions and holidays are expected) investigate
Error-based alarm retrain at once, gate, shadow retrain, gate retrain, gate
Gate failure of a retrained model keep champion, open an incident keep champion keep champion
Severe incident (errors, latency, broken feature) roll back alias, fall back to rules fall back to seasonal naive fall back to "deliver all"

The runbook is short and concrete, one entry per alert type. The drift entry, as the on-call engineer reads it:

text
ALERT  drift: <model> feature <f>, KS above threshold 3 days in a row
1. Open the fleet dashboard. Is it one feature or many? Many features of one model at once:
   suspect the feature pipeline first (a broken join or unit change), not the world.
2. Check the parity test and the feature set version of the last deploy (step 1).
3. Compare with the calendar: promotion, holiday, new market, a release of the upstream app.
4. Look at the model's error on the newest labelled days. Error up: follow the retraining policy.
   Error flat: annotate the alert, adjust the reference window if the change is permanent.
5. Never retrain on data you have not explained. Record the decision in the incident log.
Rollback:  move <model>@champion to the previous version; the router picks it up on reload.
Owner:     the model's team (registry tag "team"); platform on-call for pipeline failures.

Extensions

  1. Concept drift. Add Page-Hinkley on each model's daily error to the fleet simulation and measure its delay (concept drift detection).
  2. A champion check in CI: fail the pipeline if any champion alias points at a version whose gate tag is not passed, or whose feature set differs from serving's.
  3. Canary statistics. Use the two-proportion test of deployment strategies on the alert rate, and compute how many canary days you need to see a 1-point change.
  4. Data validation at the gate: run the schema and range checks of data validation on every training set before training starts.
  5. Cost. Add latency and memory budgets to each team's gate and measure them in CI (latency and batching).
  6. Reproducibility. Rebuild fraud v2 from its registry record alone (data hash, commit, feature set) and check the artifact hash matches (reproducibility).

Write-up template

text
Fleet:            models, owners, feature sets, label delays
Criteria:         (copy the table) and the result for each: met / missed
Features:         parity test result, how windows are cut, where the feature set version is recorded
Registry + gate:  each team's gate, this release's checks and outcome, exit code
Release:          shadow numbers (disagreement, alerts, outcomes), canary share and health checks
Monitoring:       monitors, statistic, alert policy, false alarm-days per day, delay on the real drift
Retraining:       schedule and triggers per model
Runbook:          alert types covered; last drill (date, time to roll back)
Risks:            what the simulation does not capture (correlated features, label delay, seasonality)

Practice

  1. Step 1's buggy batch job scored well offline. Why would its model do worse in production, and why would no offline metric reveal it?
  2. The forecast v2 had the better MASE but was rejected. A team lead asks for an exception "since it is clearly better". What do you answer?
  3. The canary group had 48 requests and 2 frauds. What can it prove about v2, and what not?
  4. With 30 independent monitors each at a 5 % daily false-alarm rate, how many false alarms per day do you expect, and what is the chance that a given day has none?
Answer
  1. It was trained on features that include future transactions, which the online service can never see; at serving time the inputs follow a different distribution than in training. Offline evaluation uses the same leaky features on the holdout, so it looks good; only the parity test against the online implementation, or production performance, shows the gap.
  2. It is better on features that serving does not compute: in production it would receive store_daily:v1 inputs and its score would not apply. Release store_daily:v2 to serving (with its own parity test), then re-run the gate; the exception would be the second incident again.
  3. It can show that v2 runs: no errors, acceptable latency, an alert rate in the expected range. It cannot show that v2 catches more fraud: 2 frauds give no statistical power. Quality evidence comes from shadow scoring with joined labels.
  4. 30⋅0.05=1.530 \cdot 0.05 = 1.5 per day (the simulation measured 1.35), and P(no false alarm)=0.9530≈0.21P(\text{no false alarm}) = 0.95^{30} \approx 0.21, so about four days in five have at least one.

Test yourself

What does the parity test of step 1 compare?

  1. Two models on the same features
  2. The batch implementation of each feature with the online service, on sampled events
  3. Training and test accuracy
  4. Two versions of the registry

Why was forecast v2 rejected although its MASE (0.824) beat the champion's (1.047)?

  1. MASE below 1 is invalid
  2. It was trained on feature set store_daily:v2, which serving does not provide yet
  3. Its artifact was too large
  4. The margin was too small

Why is the canary bucket a hash of the card id instead of a random draw per request?

  1. Hashing is faster
  2. So that each card always gets the same model: no flipping between models for one customer, and per-customer outcomes can be compared
  3. Random numbers are not allowed in FastAPI
  4. To make the canary exactly 10 % of requests

In the fleet simulation, which change brought false alarm-days from 81 to 1 while still paging the real drift within 4 days?

  1. A Bonferroni threshold alone
  2. Requiring 3 days in a row above the 5 % critical value
  3. Fewer monitors
  4. A larger window

In the drift-monitor lab with KS at threshold 0.11, the detection delay read 0 days. Why is that misleading?

  1. The lab has a bug
  2. Day 21 crossed the threshold by noise while the mean had barely moved; the steady alarms only start on day 27
  3. KS cannot detect gradual drift
  4. The threshold was too high