Model Registry: Versioning and Lifecycle States
Difficulty: Senior Level | Companies: Google, Meta, Netflix, Uber, Stripe
Prerequisites
- !Experiment tracking with MLflow or a similar tool
- !Serializing and loading a trained model
- !How a serving process resolves the artifact it loads
What You'll Learn
- 1Separate registry responsibilities from artifact storage
- 2Design lifecycle states that match real release decisions
- 3Register, promote, and compare versions through the MLflow API
- 4Implement a rollback path that does not require retraining
Why a folder of pickles is not a registry
The moment more than one service consumes a model, models/latest.pkl stops being cute and starts being an incident. Nobody can say which training run produced the file, overwriting destroys the previous version with no undo, and two teams can silently disagree about what "production" means. A registry exists to answer three questions instantly: what is serving right now, what was serving before it, and what would I have to do to put the old one back. If those answers require shell access and a shared filesystem, you have a storage directory with a marketing name.
The deeper problem is that a model is not a single object. It is an artifact plus the metadata that makes the artifact interpretable: the metrics it was judged by, the data snapshot behind those metrics, the serving signature, the approval state, and the person accountable for it. Registry design is therefore mostly metadata design. Teams that get this right find that deployment code shrinks â the deployer reads a pointer, never a path â and that audits become a query rather than an archaeology project.
Lifecycle states worth having
Every state transition should answer a question someone actually asks. Two states are too few, because "approved" conflates a model that passed automated gates with one that a human signed off on. Six is too many, because then engineers invent a private numbering scheme in a README. Four covers nearly every release process, and each one should have entry criteria that a machine can verify rather than a meeting that someone must attend.
| State | Entry criteria | Who can set it | Serving traffic |
|---|---|---|---|
| None | Training finished, artifact uploaded | Pipeline automatically | No |
| Staging | Evaluation thresholds passed in CI | CI job on merge | Shadow or canary only |
| Production | Smoke test plus sign-off recorded | Release job or named owner | Yes, as the live alias |
| Archived | Superseded, or a rollback moved past it | Automatic on promotion | No |
Two supporting rules make those states trustworthy. First, promotion should be monotonic and logged: a version moves forward or is archived, never silently backwards. Second, exactly one version holds the production alias at any time, and the alias â not a hard-coded version number â is what serving reads. Pinning a version is correct for reproducibility; reading the alias is correct for operations. Mature systems do both, pinning inside a deployment manifest while the manifest itself is updated by the promotion job.
Registering and promoting through MLflow
The MLflow registry API maps cleanly onto those states. Registering creates an immutable version tied to a run; transitioning changes only metadata, never bytes. That immutability is the whole point: if promoting to production could alter the artifact, you could no longer trust that yesterday's audit result applies to today's deployment.
# registry_promotion.py
from typing import Dict, List, Optional
from mlflow.tracking import MlflowClient
class Stages:
NONE = "None"
STAGING = "Staging"
PRODUCTION = "Production"
ARCHIVED = "Archived"
class ModelPromoter:
def __init__(self, tracking_uri: str = "http://localhost:5000"):
self.client = MlflowClient(tracking_uri=tracking_uri)
def register(self, run_id: str, name: str, description: str) -> str:
uri = f"runs:/{run_id}/model"
mv = self.client.register_model(uri, name)
self.client.update_model_version(
name=name, version=mv.version, description=description
)
return mv.version
def set_tags(self, name: str, version: str, tags: Dict[str, str]) -> None:
for key, value in tags.items():
self.client.set_model_version_tag(name=name, version=version, key=key, value=value)
def promote(self, name: str, version: str, stage: str) -> None:
if stage not in (Stages.STAGING, Stages.PRODUCTION, Stages.ARCHIVED):
raise ValueError(f"unknown stage {stage}")
self.client.transition_model_version_stage(
name=name,
version=version,
stage=stage,
archive_existing_versions=(stage == Stages.PRODUCTION),
)
def current(self, name: str, stage: str = Stages.PRODUCTION) -> Optional[str]:
versions = self.client.get_latest_versions(name, stages=[stage])
return versions[0].version if versions else None
def history(self, name: str) -> List[Dict[str, str]]:
out = []
for mv in self.client.search_model_versions(f"name='{name}'"):
run = self.client.get_run(mv.run_id)
out.append({
"version": mv.version,
"stage": mv.current_stage,
"accuracy": run.data.metrics.get("accuracy", float("nan")),
"data_version": run.data.params.get("data_version", "unknown"),
"updated": mv.last_updated_timestamp or 0,
})
return sorted(out, key=lambda r: int(r["version"]))
promoter = ModelPromoter()
version = promoter.register(
run_id="b7f1c2d94a1e4f0c9a2d5e6f7a8b9c0d",
name="churn-predictor",
description="Gradient boosted model, data snapshot 2026-02-11",
)
promoter.set_tags("churn-predictor", version, {
"team": "growth-ml",
"dataset_version": "2026-02-11",
"owner": "ml-platform",
})
promoter.promote("churn-predictor", version, Stages.STAGING)
print("live version:", promoter.current("churn-predictor"))
Call archive_existing_versions=True deliberately rather than by habit: archiving the previous production model is what makes "which version is live" answerable without a query over every version ever registered.
A minimal registry you can build yourself
For teams not ready to operate a registry server, a file-backed implementation with an index is a legitimate stepping stone â provided it preserves the two invariants: versions are immutable once written, and one version holds the production pointer. The implementation below adds a content hash on purpose. If the same bytes appear under two versions, that is a signal that a retraining job ran without changing anything, which is worth knowing before you pay for a deployment.
# local_registry.py
import hashlib
import json
from dataclasses import asdict, dataclass, field
from datetime import datetime, timezone
from pathlib import Path
from typing import Dict, List, Optional
@dataclass
class VersionRecord:
version: int
model_name: str
stage: str
artifact_path: str
metrics: Dict[str, float]
params: Dict[str, str]
digest: str
created_at: str = field(
default_factory=lambda: datetime.now(timezone.utc).isoformat()
)
class LocalRegistry:
def __init__(self, root: str):
self.root = Path(root)
self.root.mkdir(parents=True, exist_ok=True)
self.index_path = self.root / "index.json"
self.index: Dict[str, Dict] = self._load()
def _load(self) -> Dict:
if self.index_path.exists():
return json.loads(self.index_path.read_text())
return {}
def _save(self) -> None:
self.index_path.write_text(json.dumps(self.index, indent=2))
@staticmethod
def _digest(path: Path) -> str:
h = hashlib.sha256()
with open(path, "rb") as fh:
for chunk in iter(lambda: fh.read(8192), b""):
h.update(chunk)
return h.hexdigest()[:16]
def register(self, name: str, artifact: Path, metrics: Dict[str, float],
params: Dict[str, str]) -> VersionRecord:
versions = self.index.get(name, {}).get("versions", [])
version = (max((v["version"] for v in versions), default=0) + 1)
target = self.root / name / f"v{version}"
target.mkdir(parents=True, exist_ok=True)
stored = target / artifact.name
stored.write_bytes(artifact.read_bytes())
record = VersionRecord(
version=version, model_name=name, stage="None",
artifact_path=str(stored), metrics=metrics, params=params,
digest=self._digest(stored),
)
self.index.setdefault(name, {"versions": [], "production": None})
self.index[name]["versions"].append(asdict(record))
self._save()
return record
def promote_to_production(self, name: str, version: int) -> None:
entry = self.index[name]
target = next(v for v in entry["versions"] if v["version"] == version)
if target["digest"] == entry.get("production_digest"):
raise ValueError("identical artifact already in production")
for v in entry["versions"]:
if v["stage"] == "Production":
v["stage"] = "Archived"
target["stage"] = "Production"
entry["production"] = version
entry["production_digest"] = target["digest"]
self._save()
def rollback(self, name: str) -> int:
entry = self.index[name]
history = [v for v in entry["versions"] if v["stage"] == "Archived"]
if not history:
raise ValueError("no archived version to roll back to")
previous = max(history, key=lambda v: v["version"])
return self.promote_to_production(name, previous["version"]) or previous["version"]
def serving_version(self, name: str) -> Optional[int]:
return self.index.get(name, {}).get("production")
Choosing what serving actually loads
Serving layers resolve a model in one of three ways, and each has a failure mode worth naming. Reading an explicit version gives perfect reproducibility and zero automatic recovery: if that artifact disappears, the service fails. Reading a stage alias gives automatic recovery at the cost of surprise â a promotion can change production behaviour without a deploy of your own. Reading a mutable "latest" tag gives you the downsides of both, and it is the option to reject outright.
The pattern that survives contact with incidents is a two-layer pointer. The deployment manifest pins an exact version and digest, so any running pod can be explained and rebuilt byte for byte. The registry keeps the stage alias, so the promotion job has exactly one place to write when it moves traffic. Reconciliation between the two runs on a schedule; if the manifest and the registry disagree, the reconciler alerts rather than silently rewriting production. That alert is how you find out a colleague promoted a model at midnight without announcing it.
Choosing which version a given environment reads is then a policy question with a mechanical answer. Development reads the newest successful run, staging reads anything that passed CI gates, production reads only what a promotion job wrote. Nothing else may write the production pointer â not a notebook, not a one-off script, not a hotfix. Enforce it with credentials: the registry token used by training jobs cannot transition into production.
Lineage: what to record for every version
Lineage is the chain from a business question to a served prediction, and a registry is where that chain becomes queryable. At minimum, record the training run identifier, the data snapshot, the evaluation metrics with their thresholds, the serving signature (input names, types, order), and the approval event with its actor. Anything less forces the next engineer to reconstruct intent from commit messages.
Version the signature as loudly as the weights. A model that expects twelve columns but receives eleven is a runtime error at best and a silent garbage-in prediction at worst, and the signature changes far more often than teams expect â a renamed feature, a reordered input, a categorical encoding switch. Pin the signature alongside the artifact so the serving layer can validate requests against exactly what this version was trained to consume.
Rollback without retraining
Rollback plans fail for predictable reasons: the previous artifact was garbage-collected, the database migration only rolls forward, or the person who knows the procedure is on vacation. Fix all three in advance. Keep at least the last three production artifacts under retention policy, make the promotion job write a reversible pointer update rather than a rebuild, and rehearse the rollback until it is a single command with a known duration.
The test is concrete: pick a random Friday, announce a simulated bad release, and measure how long until the previous model answers production traffic again. Under a minute means your pointer indirection works. Ten minutes means you will discover, during a real incident, which of the three failure modes above you actually have. Rehearsal is the only reliable evidence, because a document that describes a rollback is a hypothesis, not a capability.
â ī¸Never mutate a registered artifact
Common Mistakes
Letting services read model files by hard-coded path
Fix: Have services resolve a stage alias or pointer that only the promotion job writes.
Skipping the archived state so old models stay marked production
Fix: Archive the previous production version automatically whenever a new one is promoted.
Recording metrics without the data version they were computed on
Fix: Store the snapshot identifier as a parameter on the run that produced the artifact.
Treating rollback as an emergency-only procedure
Fix: Schedule a rehearsal and keep a documented artifact retention window so rollback stays possible.
Best Practices
- Keep one production alias per model and never pin versions in application code
- Attach the serving signature to every registered version
- Tag each version with team, owner, and dataset for audit queries
- Archive rather than delete; let a retention policy clean up on a schedule
- Make promotion a job that emits a changelog entry with metrics delta
Interview Questions
Q1: Difference between model versioning and model registry?
Versioning assigns immutable identifiers to artifacts; a registry adds lifecycle state, ownership metadata, queries, and controlled transitions on top of those versions.
Q2: How do you roll back a bad model release?
Flip the production pointer to the previously archived version, verify latency and metrics, and open a postmortem â no retraining involved, because artifacts are retained.
Q3: What metadata does a regulated deployment require?
Training data provenance, code version, evaluation report, approver identity, and a timestamped audit trail of every state transition.
Q4: How would you A/B test two registered versions?
Both stay in production states simultaneously behind an experiment router, with traffic split recorded and metrics attributed back to version identifiers.
Key Takeaways
- A registry is metadata design; storage is the easy half
- Four lifecycle states with machine-checkable entry criteria cover most teams
- Serving should read an alias; the manifest pins the exact version for reproducibility
- Immutability plus a content hash makes every promotion explainable
- Rollback is a capability only after you have timed it once