Platform Engineering · Lesson 332

Model Registry and Promotion: Tracking, Validation Gates, and Rollback

A trained model is an artifact, like a container image: it should be built reproducibly, recorded with everything that made it, tested before it ships, promoted through environments by a gate rather than by hand, and easy to roll back. Experiment tracking records each training run (code commit, data version, parameters, metrics); the model registry holds the versions worth keeping, with their lineage and an alias such as champion that serving follows. This lesson follows one model version from a training run to production, and shows the two failures that registries exist to prevent: a model nobody can reproduce, and a promotion that skipped the gate.

Difficulty: Advanced · Know this first: Lesson 330, Lesson 324

What you will learn

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.

Run it as:

When it breaks, I check

One thing to remember

Where the time goes

This bar adds up minutes from a finished training run to the champion alias. It is a worked example, not a measurement. The tracked-record and gate hops are where promotion goes wrong.

Try it: should this version become champion?

Pick how the candidate compares with the champion, and how promotion works. The gate passes only if no important slice is worse than its threshold.

passgate
v19champion

Promoted

Check yourself

Three questions. No score is saved anywhere — this is just you against the material.

Basic to master

Model promotion grows in four levels: reading the registry, tracking every run, gating promotion, and running it as a governed release process.

Basic — Read the registry

At the basic level you can say which version is serving, where it came from, and what the previous one was.

  • Registered model, versions, aliases (champion, challenger).
  • From a version to its run: commit, data version, parameters, metrics.
  • The version label on served predictions.

Where it breaks: a champion with no run behind it.

Try it: Basic

Which version is in production, and what is the rollback target?

Now do it: Find your champion and its run in the registry.

Intermediate — Track every run

At the intermediate level no model reaches the registry without a tracked, reproducible run.

  • Training in a pipeline from a commit, pinned data, a lock file or image, and a seed.
  • Autologging plus explicit logs of the dataset version and the feature list.
  • The model signature saved with it, so serving rejects wrong inputs.

Try it: Intermediate

A colleague uploads a model trained in a notebook. What do you ask for?

Now do it: Move one notebook model into a tracked pipeline run.

Advanced — Gate the promotion

At the advanced level promotion is a pipeline with a gate, not a click.

  • Holdout and slice metrics against the champion, fairness and calibration, latency on serving hardware.
  • A staging soak with replayed traffic; agreement between offline and served predictions.
  • Alias moves only from the pipeline; rollback rehearsed.

Try it: Advanced

Where should the thresholds for the gate come from?

Now do it: Write the gate thresholds for one model.

Master — Govern model releases

At the master level model releases are as governed as software releases.

  • Model cards and approvals recorded with each version for consequential models.
  • Promotion through environments (dev, staging, production registries or workspaces) with the same artifact.
  • Metrics: lead time from run to champion, rollback rate, regressions caught by the gate against found in production.

Trade-off: gates and approvals slow urgent fixes; a fast, rehearsed rollback lets you keep the gate and still move quickly.

Try it: Master

An urgent fix must ship today. What keeps it safe without skipping the gate?

Now do it: Time your gate end to end.

Go deeper

Tracking, registering, and promoting with MLflow's client (2.x and later use aliases; the older fixed stages are deprecated). Check the current MLflow documentation for exact signatures.

import mlflow
from mlflow import MlflowClient

mlflow.set_experiment("fraud-scorer")
with mlflow.start_run() as run:
    mlflow.log_params({"max_depth": 6, "lr": 0.05, "seed": 7})
    mlflow.log_param("dataset_version", "v412")
    mlflow.set_tag("git_sha", GIT_SHA)
    model = train(...)
    mlflow.log_metric("auc", 0.861)
    mlflow.sklearn.log_model(model, name="model", signature=signature,   # MLflow 3; artifact_path= in 2.x
                             registered_model_name="fraud-scorer")   # creates version 19

client = MlflowClient()
# the gate writes its verdict on the version; promotion checks it
client.set_model_version_tag("fraud-scorer", "19", "gate", "passed")
client.set_registered_model_alias("fraud-scorer", "champion", "19")   # promote
# rollback: client.set_registered_model_alias("fraud-scorer", "champion", "18")
model = mlflow.pyfunc.load_model("models:/fraud-scorer@champion")     # serving

What a validation gate checks, at minimum:

The same pattern exists in every platform: SageMaker Model Registry (model package groups, approval status), Vertex AI Model Registry (versions and aliases), Azure Machine Learning (registered models with versions and tags), and Databricks with Unity Catalog (MLflow aliases).

One time it broke

This is a composite of a failure pattern that keeps repeating; the details are illustrative. The average went up; one group paid for it.

Timeline

  • 09:00A retrained fraud model, version 19, scores +0.012 AUC overall. A fraud ring is active, so the release is marked urgent.
  • 09:20The champion alias is moved to version 19 by hand. The gate, which checks slices, is skipped "to save an hour".
  • 09:20–23:10Version 19 was trained on data that under-sampled new customers; on that slice it is 18 points worse. Fraud from new accounts rises.
  • 23:10A finance dashboard flags the loss. The alias is moved back to version 18; serving follows in three minutes.

What changed after

Only the promotion pipeline can move the champion alias (registry permissions), the gate runs in under 15 minutes so there is no reason to skip it, the new-customer slice has its own threshold, and every promotion is canaried before full traffic.

Try it yourself, from scratch

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: A virtual environment for Python packages: python3 -m venv ~/mlops && . ~/mlops/bin/activate. Then pip install mlflow scikit-learn.

1. Linux commands

Type each one, read what it prints, and compare it with the note above it.

  1. Start a local tracking server with a SQLite backend (the registry needs a database).

    Reversible

    mkdir -p ~/labs/registry && cd ~/labs/registry
    mlflow server --backend-store-uri sqlite:///mlflow.db --port 5000 >server.log 2>&1 &
    sleep 8; curl -s -o /dev/null -w "%{http_code}\n" localhost:5000

    Options: --backend-store-uri is where runs and the registry live; & runs it in the background.

    Expect: 200 once the server is up.

    Clean up: kill %1 stops it; rm -rf ~/labs/registry removes everything.

  2. Train, log, and register two versions of a small model.

    Reversible

    cat > train.py <<'EOF'
    import sys, mlflow
    from sklearn.datasets import load_breast_cancer
    from sklearn.linear_model import LogisticRegression
    from sklearn.metrics import roc_auc_score
    mlflow.set_tracking_uri("http://localhost:5000"); mlflow.set_experiment("demo")
    X, y = load_breast_cancer(return_X_y=True)
    C = float(sys.argv[1])
    with mlflow.start_run():
        m = LogisticRegression(C=C, max_iter=5000).fit(X[:400], y[:400])
        mlflow.log_param("C", C); mlflow.log_metric("auc", roc_auc_score(y[400:], m.predict_proba(X[400:])[:, 1]))
        mlflow.sklearn.log_model(m, name="model", registered_model_name="demo-scorer")
    EOF
    python3 train.py 0.1 && python3 train.py 1.0

    Options: Each run logs a parameter, a metric, and the model, and registers it as the next version of demo-scorer.

    Expect: Two lines saying versions 1 and 2 of demo-scorer were created.

  3. Promote version 2 by moving the champion alias, then load the model by alias.

    Read-only

    python3 -c "from mlflow import MlflowClient; import mlflow; mlflow.set_tracking_uri('http://localhost:5000'); c=MlflowClient(); c.set_registered_model_alias('demo-scorer','champion','2'); print(c.get_model_version_by_alias('demo-scorer','champion').version)"

    Expect: 2.

    Clean up: Aliases are only pointers; deleting one never deletes a version.

  4. Roll back: move the alias to version 1, and check it.

    Reversible

    python3 -c "from mlflow import MlflowClient; import mlflow; mlflow.set_tracking_uri('http://localhost:5000'); c=MlflowClient(); c.set_registered_model_alias('demo-scorer','champion','1'); print(c.get_model_version_by_alias('demo-scorer','champion').version)"
    kill %1

    Expect: 1, then the server stops.

2. Python: registry.py

This program is a tiny model registry: runs record their lineage, registered versions are immutable, a gate compares a candidate with the champion overall and per slice, and promotion and rollback move an alias. It promotes one good candidate, refuses one that is better on average and much worse for new customers, and rolls back. Save it as registry.py, then run it.

# registry.py
RUNS = {
    8790: {"commit": "a91f0d", "data": "v398", "seed": 7, "auc": 0.849, "slices": {"returning": 0.861, "new": 0.802}},
    8812: {"commit": "4be21c", "data": "v412", "seed": 7, "auc": 0.861, "slices": {"returning": 0.872, "new": 0.799}},
    8840: {"commit": "c03e77", "data": "v415", "seed": 7, "auc": 0.866, "slices": {"returning": 0.889, "new": 0.621}},
}
GATE = {"min_overall_gain": 0.0, "max_slice_drop": 0.01}

versions, aliases, log = {}, {}, []

def register(run_id):
    v = len(versions) + 1
    versions[v] = {"run": run_id, **RUNS[run_id]}     # immutable from now on
    return v

def gate(candidate, champion):
    c, b = versions[candidate], versions[champion]
    reasons = []
    if c["auc"] - b["auc"] < GATE["min_overall_gain"]:
        reasons.append(f"overall {c['auc'] - b['auc']:+.3f}")
    for name, score in c["slices"].items():
        drop = b["slices"][name] - score
        if drop > GATE["max_slice_drop"]:
            reasons.append(f"slice '{name}' {-drop:+.3f}")
    return reasons

def promote(candidate):
    champion = aliases.get("champion")
    reasons = gate(candidate, champion) if champion else []
    if reasons:
        log.append(f"v{candidate} REFUSED: " + "; ".join(reasons) + f"  (champion stays v{champion})")
        return
    aliases["champion"] = candidate
    if champion:
        aliases["previous"] = champion
    r = versions[candidate]
    log.append(f"v{candidate} is champion  (run {r['run']}, commit {r['commit']}, data {r['data']}, seed {r['seed']})")

def rollback():
    aliases["champion"], aliases["previous"] = aliases["previous"], aliases["champion"]
    log.append(f"rollback: champion is v{aliases['champion']} again")

v1, v2, v3 = register(8790), register(8812), register(8840)
promote(v1)
promote(v2)
promote(v3)
rollback()
print("\n".join(log))
print("aliases:", aliases)
print("versions are unchanged:", {v: versions[v]["run"] for v in versions})

Run it, and you should see this output:

$ python3 registry.py
v1 is champion  (run 8790, commit a91f0d, data v398, seed 7)
v2 is champion  (run 8812, commit 4be21c, data v412, seed 7)
v3 REFUSED: slice 'new' -0.178  (champion stays v2)
rollback: champion is v1 again
aliases: {'champion': 1, 'previous': 2}
versions are unchanged: {1: 8790, 2: 8812, 3: 8840}

3. What to notice

4. Advanced: every step as one Bash script

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/model-registry-and-promotion && cd ~/labs/model-registry-and-promotion) and save this as lab.sh.

#!/usr/bin/env bash
# The Linux steps of "Model Registry and Promotion: Tracking, Validation Gates, and Rollback", 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=(
  'Start a local tracking server with a SQLite backend (the registry needs a database).'
  'Train, log, and register two versions of a small model.'
  'Promote version 2 by moving the champion alias, then load the model by alias.'
  'Roll back: move the alias to version 1, and check it.'
)

step_1() {
mkdir -p ~/labs/registry && cd ~/labs/registry
mlflow server --backend-store-uri sqlite:///mlflow.db --port 5000 >server.log 2>&1 &
sleep 8; curl -s -o /dev/null -w "%{http_code}\n" localhost:5000
}

step_2() {
cat > train.py <<'EOF'
import sys, mlflow
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
mlflow.set_tracking_uri("http://localhost:5000"); mlflow.set_experiment("demo")
X, y = load_breast_cancer(return_X_y=True)
C = float(sys.argv[1])
with mlflow.start_run():
    m = LogisticRegression(C=C, max_iter=5000).fit(X[:400], y[:400])
    mlflow.log_param("C", C); mlflow.log_metric("auc", roc_auc_score(y[400:], m.predict_proba(X[400:])[:, 1]))
    mlflow.sklearn.log_model(m, name="model", registered_model_name="demo-scorer")
EOF
python3 train.py 0.1 && python3 train.py 1.0
}

step_3() {
python3 -c "from mlflow import MlflowClient; import mlflow; mlflow.set_tracking_uri('http://localhost:5000'); c=MlflowClient(); c.set_registered_model_alias('demo-scorer','champion','2'); print(c.get_model_version_by_alias('demo-scorer','champion').version)"
}

step_4() {
python3 -c "from mlflow import MlflowClient; import mlflow; mlflow.set_tracking_uri('http://localhost:5000'); c=MlflowClient(); c.set_registered_model_alias('demo-scorer','champion','1'); print(c.get_model_version_by_alias('demo-scorer','champion').version)"
kill %1
}

# 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

5. Learn the basics behind it

New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.

If you remember nothing else

Design exercise

Your company has 25 models in production, half trained in notebooks and deployed by copying files. Design the tracking, registry, and promotion process.

Clarifying questions to ask

What must every run record? Which models are registered, and how do versions link to data and code? What does the gate check, and who sets thresholds? How does serving load models, and how is rollback done? Who may promote, and what is recorded?

Rough sizing

Say 25 models, 4 retrains a week each, 3 environments, and 2 regressions reached production last quarter.

Shape of the answer

A tracker and registry (MLflow or the cloud equivalent) shared by all teams; training only in pipelines from a commit and a dataset version; registration from the pipeline with the signature and lineage; a gate job with per-model thresholds in Git (holdout, slices, fairness, latency); staging soak with replayed traffic; aliases champion and challenger, moved only by the pipeline; approvals and model cards for consequential models; serving by alias with canary rollout; rollback rehearsed monthly.

Trade-offs to name

A gate and approvals add an hour to an urgent release and catch the regressions that averages hide; moving every team onto pipelines costs a quarter of migration and removes "nobody can rebuild it"; strict registry permissions annoy people until the first audit.

Failure modes and how to troubleshoot them

Each row is one way this system went wrong in the diagram's scenarios. The hop number is where to look first.

ScenarioWhereEffectWhat goes wrong
A model nobody can rebuildHop 2: Tracked recordBreaksThe champion has a model file and an accuracy number in a slide. No commit, no data version, no parameters. When a bug in a feature needs a retrain, nobody can reproduce the champion to compare against.
The gate was skippedHop 4: Validation gateBreaksThe release is urgent, so the gate is skipped and v19 is promoted directly. Overall AUC is better, but v19 was trained on a dataset where new customers were under-sampled, and on that slice it is 18 points worse.

How to troubleshoot

  1. Write down the symptom and when it started: what users see, which number moved, and what changed just before (a deploy, a config change, traffic).
  2. Walk the path in order, from the first hop to the last: Training run → Tracked record → Registered version → Validation gate → Staging deploy → Approval → Champion alias → Serving → Rollback. The first hop whose evidence is wrong is where to dig.
  3. At that hop, run the read-only check from the diagram or the lab first; change nothing until the evidence points at a cause.
  4. Fix the smallest thing that restores service, or roll back the last change, and confirm the symptom is gone with the same check.
  5. Write down what you found and the check that would have caught it sooner, so the next person starts there.

References and review

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.

Saved on this device, in this browser.
Next in this series · Lesson 333
Model Canary and Shadow Deployment: A/B Tests and Champion/Challenger

Passing an offline gate says a model is good on yesterday's data. Only live traffic says it is good today. There are four ways to let a new model meet real traffic safely.

Go to Lesson 333 →

Or browse the full course from the Lessons index.