Sub topic 2
Tracking versions in a model registry
This chapter assumes you know how a trained model is packaged for serving and can run Python and shell commands. It also assumes you know the previous chapter's point: a rollback needs an immutable, versioned artifact to return to. Here you will learn what a model registry records, how to register versions so they are useful during an incident, and which metadata lets you pick a safe rollback target in minutes.
What a registry is for
A model registry is a service that stores a catalog of model versions and the metadata about each one. It does not usually store the model bytes itself. It holds a reference (a URI) to an artifact in object storage, plus a name, a version number, and descriptive fields.
During a rollback the registry answers three questions:
- Which versions of this model exist?
- Which version is serving production right now?
- Which earlier version was known to be good, and what does it need in order to run?
If you can only answer these by searching Slack or reading old pipeline logs, the rollback will be slow and error-prone. The registry makes the answers a lookup.
The structure of a registry
Most registries, including MLflow, use two levels. A registered model is a named entity such as fraud-detector. It owns many model versions, numbered 1, 2, 3 and so on. Each version points at one artifact and carries tags and aliases.
Two rules matter for rollback:
- Version numbers are assigned by the registry and only go up. Version 4 is never replaced by a different "version 4".
- An alias is a mutable name that points to exactly one version of a model. A version can have several aliases, but an alias name can point to only one version. Moving an alias is the operation that changes what production serves. The next chapter covers it in detail.
Older registry designs used stages such as Staging and Production. MLflow deprecated stages in favor of aliases and tags, so use aliases in new work. Other registries (SageMaker Model Registry, Vertex AI Model Registry, Azure ML) use different names for the same ideas: model package or model version, plus a label, approval status, or tag.
Registering a version
The following script trains a small model, logs it, and registers it as a new version of fraud-detector. It uses a SQLite backend because the MLflow model registry needs a database-backed store, not plain files. Install mlflow and scikit-learn first.
import mlflow
import mlflow.sklearn
from mlflow import MlflowClient
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import train_test_split
mlflow.set_tracking_uri("sqlite:///mlflow.db")
mlflow.set_experiment("fraud-detector")
NAME = "fraud-detector"
X, y = make_classification(n_samples=2000, n_features=10, random_state=0)
X_train, X_val, y_train, y_val = train_test_split(X, y, random_state=0)
with mlflow.start_run() as run:
model = LogisticRegression(max_iter=500).fit(X_train, y_train)
auc = roc_auc_score(y_val, model.predict_proba(X_val)[:, 1])
mlflow.log_metric("val_auc", auc)
info = mlflow.sklearn.log_model(
model, "model", registered_model_name=NAME
)
client = MlflowClient()
version = str(info.registered_model_version)
# Record what a future responder needs to know.
client.set_model_version_tag(NAME, version, "git_sha", "abc1234")
client.set_model_version_tag(NAME, version, "feature_set", "txn_features_v2")
client.set_model_version_tag(NAME, version, "val_auc", f"{auc:.4f}")
print("Registered", NAME, "version", version, "from run", run.info.run_id)Run it several times and you get versions 1, 2, 3. Each call to log_model with registered_model_name creates a new version. It never overwrites an old one. The git_sha value in the example is a placeholder. In a real pipeline your CI job supplies it.
> Note that tag values are strings. MLflow stores everything you put in a tag as text, so format numbers yourself and parse them when you read them back.
Metadata that makes rollback fast
The registry gives you a version number and a source URI for free. Everything else you must record deliberately. For rollback, record the metadata in this table at registration time, not during the incident.
| Metadata | Why a rollback needs it |
|---|---|
| Artifact URI and checksum | Confirms the bytes you load are the bytes that were approved. |
| Training run ID | Links to parameters, metrics, and the training data snapshot. |
| Git commit of training and serving code | Lets you rebuild the exact environment if needed. |
| Feature set name and version | Shows whether the old model expects the features the system still produces. |
| Preprocessing artifact version | Prevents pairing an old model with a new scaler or encoder. |
| Dependency versions (framework, Python) | Shows whether the serving image can load the old artifact. |
| Offline evaluation metrics | Helps you rank candidates when several earlier versions exist. |
| Deployment history (when it served, with what result) | Distinguishes "known good in production" from "passed offline tests only". |
The last row is the most often missing. A version that scored well offline but never served traffic is a weaker rollback target than one that ran in production for three weeks without incident. Record that fact with a tag when a version finishes a healthy production period.
from mlflow import MlflowClient
client = MlflowClient(tracking_uri="sqlite:///mlflow.db")
NAME = "fraud-detector"
# Mark a version after it has served production without incident.
client.set_model_version_tag(NAME, "2", "prod_verdict", "healthy")
client.set_model_version_tag(NAME, "2", "prod_window", "2026-10-01/2026-10-28")
# Mark a version that must never be a rollback target.
client.set_model_version_tag(NAME, "3", "prod_verdict", "rolled_back")
client.set_model_version_tag(
NAME, "3", "rollback_reason", "p95 latency above limit after release"
)This example assumes versions 2 and 3 exist from the earlier script runs. If you only registered one version, adjust the version numbers.
Listing and auditing versions
Before you ever need a rollback, write a small audit that prints the registry's state. You can run it during an incident to see candidates at a glance.
from mlflow import MlflowClient
client = MlflowClient(tracking_uri="sqlite:///mlflow.db")
NAME = "fraud-detector"
versions = client.search_model_versions(f"name = '{NAME}'")
print(f"{'ver':>3} {'status':<7} {'aliases':<14} {'verdict':<12} source")
for mv in sorted(versions, key=lambda v: int(v.version)):
verdict = mv.tags.get("prod_verdict", "unknown")
aliases = ",".join(mv.aliases) or "-"
print(f"{mv.version:>3} {mv.status:<7} {aliases:<14} {verdict:<12} {mv.source}")Notes on this code:
mv.versionis a string, so sort onint(mv.version). Sorting the raw strings puts "10" before "2".mv.statusisREADYonce the registry has finished copying the artifact. OnlyREADYversions should be loaded.mv.aliaseslists the alias names currently pointing at that version.- The filter string is interpolated here because
NAMEis a constant in your own code. If a model name ever comes from user input, validate it before building the filter.
Choosing a known good version
The simplest rule is "roll back to the version that served production immediately before the current one". That is usually right, but verify it with the metadata:
- The version has
prod_verdict = healthy, or a recorded production window with no incidents. - Its artifact is still present and
statusisREADY. - Its feature set and preprocessing version match what the system produces today. If the feature pipeline changed since that version served, it may not be safe to restore, as the compatibility chapter explains.
- Its dependencies load in the current serving image.
You can encode the rule as a function, so the choice is repeatable and does not depend on who is on call.
from mlflow import MlflowClient
def last_known_good(client, name, current_version):
"""Return the highest healthy, ready version below current_version."""
candidates = []
for mv in client.search_model_versions(f"name = '{name}'"):
if int(mv.version) >= int(current_version):
continue
if mv.status != "READY":
continue
if mv.tags.get("prod_verdict") != "healthy":
continue
candidates.append(mv)
if not candidates:
return None
return max(candidates, key=lambda v: int(v.version))
client = MlflowClient(tracking_uri="sqlite:///mlflow.db")
good = last_known_good(client, "fraud-detector", current_version="3")
print("Rollback candidate:", good.version if good else "none found")If the function returns None, you have no tagged safe target. That is a finding in itself: you must pick manually and accept more risk, or consider rolling forward.
Common errors
- Overwriting an artifact in place. If a training job writes to a fixed path such as
s3://models/fraud/latest/, version 3 might point at bytes that changed after registration. Write each artifact to a unique path (for example, one that includes the run ID) and enable object versioning or write-once policies on the bucket. - Deleting old versions to save space. Retention rules that remove versions after 30 days can delete your rollback target. Keep at least the last few versions that served production, whatever their age.
- Registering before the artifact is complete. A version whose status is not
READY, or whose upload failed halfway, can break loading. Register only after the artifact is fully written, and check status before use. - Version numbers in code. Hard-coding
models:/fraud-detector/3in application code makes every release a code change. Load by alias (models:/fraud-detector@production) so the registry controls what is served. - Missing preprocessing. A model registered without its encoder or scaler is not independently restorable. Package preprocessing inside the model artifact (for example, a scikit-learn
Pipeline) or register it as a paired, tagged artifact. - Several registries, no source of truth. If staging and production use separate registries or workspaces, the version numbers differ between them. Record the promoted source version in a tag so you can trace a production version back.
Quick check of your setup
A registry is ready for rollback when you can do all of the following without asking anyone:
- List every version of the model with its status, aliases, and production verdict.
- Name the version that served before the current one.
- Say which feature set, preprocessing, and dependencies each version needs.
- Load any listed version in a scratch environment and get a prediction.
The next chapter shows how an alias turns this catalog into a switch for production traffic.
Exercise
Your registry has versions 1 to 4 of a model. Version 4 is serving production and is failing. Version 3 is tagged prod_verdict=healthy. Version 2 was never deployed, but has the best offline AUC. Version 3's artifact has status READY, but it was trained against feature set txn_features_v1, and production now produces only txn_features_v2. Which version should you restore, and what should you do before choosing?
Show answer
Do not restore version 3 yet, and do not choose version 2 just because its offline AUC is best, since it never served production. Version 3 is the normal candidate because it has a healthy production record, but its feature set txn_features_v1 no longer matches what production produces. First check whether version 3 can still run against txn_features_v2, for example by loading it in a scratch environment and scoring recent data, or whether the old features are still available. If it is incompatible, rolling back will trade one failure for another. In that case consider a fix that rolls forward, or restoring the old feature pipeline together with the model. Record the outcome as tags on the versions for the next responder.
Exercise
Why does the audit script sort with int(mv.version) instead of sorting the version strings directly?
Show answer
The registry returns version numbers as strings. Sorting strings compares them character by character, so "10" sorts before "2". Converting to int gives numeric order, so the highest version is correctly identified as the latest.