Sub topic 12
Versioning models and the API
A deployed model changes in two ways. You retrain it, which changes its behavior. You also revise the request and response format, which changes what clients must send and parse. These changes happen on different schedules, so this chapter treats them as two separate version numbers.
This chapter assumes you have the FastAPI service from earlier chapters: a model loaded at startup, typed Pydantic schemas, and a /predict endpoint. You should also be comfortable with joblib and with running uvicorn and pytest.
Two things that change
The model version identifies one trained artifact: the weights, the preprocessing, and the library versions they need. The API version identifies the contract: URL paths, field names, field types, and response shape.
Neither version implies the other. You can retrain on new data and keep the same contract. You can also rename a response field without touching the model.
| Change | Model version | API version |
|---|---|---|
| Retrain on newer data, same features | New | Same |
| Add an optional response field | Same | Same (non-breaking) |
| Rename or remove a field | Same | New (breaking) |
| Add a required input feature | New | New (breaking) |
| Change the meaning of an output value | New | New (breaking) |
A change is breaking if an existing client that did nothing wrong would start failing or would misread results. Adding an optional field is safe. Clients that ignore unknown fields keep working. Renaming class_index to label breaks every client that reads it.
Versioning the model artifact
The service from earlier chapters loads a single model.joblib. If you overwrite that file on each retrain, you cannot roll back and you cannot tell which model produced a given prediction. Instead, store each artifact in its own directory with a metadata file.
artifacts/
iris/
2025-01-15/
model.joblib
metadata.json
2025-02-03/
model.joblib
metadata.jsonDates, integers, or a short hash of the training data and code all work as version labels. Pick one scheme and keep it. Dates sort naturally, and they tell you how old a model is without a lookup.
This function saves an artifact together with the metadata you will want later. It refuses to overwrite an existing version.
import json
from pathlib import Path
import joblib
import sklearn
def save_artifact(model, version: str, metrics: dict, root: str = "artifacts/iris"):
target = Path(root) / version
target.mkdir(parents=True, exist_ok=False)
joblib.dump(model, target / "model.joblib")
metadata = {
"version": version,
"sklearn_version": sklearn.__version__,
"feature_order": [
"sepal_length",
"sepal_width",
"petal_length",
"petal_width",
],
**metrics,
}
(target / "metadata.json").write_text(json.dumps(metadata, indent=2))
return targetCall it at the end of your training script, for example save_artifact(model, "2025-01-15", {"accuracy": 0.97}). Two fields in the metadata prevent common failures:
sklearn_versionmatters because a pickled scikit-learn model is only guaranteed to load under the same library version that saved it. A mismatch can raise warnings, wrong results, or errors. Pin the version inrequirements.txtand record it here.feature_ordermatters because the model sees a bare list of numbers. If a retrain changes the column order and the service still builds rows in the old order, predictions are silently wrong. Nothing raises an error.
Choosing which model the service loads
Make the version a setting, not a hard-coded path. The service reads an environment variable at startup and loads that artifact. Rolling back then means restarting with the previous value. It does not require a rebuild.
import os
from contextlib import asynccontextmanager
from pathlib import Path
import joblib
from fastapi import APIRouter, FastAPI, Response
from pydantic import BaseModel, Field
ARTIFACT_ROOT = Path(os.environ.get("ARTIFACT_ROOT", "artifacts/iris"))
MODEL_VERSION = os.environ.get("MODEL_VERSION", "2025-01-15")
CLASS_NAMES = ["setosa", "versicolor", "virginica"]
models = {}
@asynccontextmanager
async def lifespan(app: FastAPI):
path = ARTIFACT_ROOT / MODEL_VERSION / "model.joblib"
models["iris"] = joblib.load(path)
yield
models.clear()
app = FastAPI(lifespan=lifespan)
class IrisFeatures(BaseModel):
sepal_length: float = Field(gt=0)
sepal_width: float = Field(gt=0)
petal_length: float = Field(gt=0)
petal_width: float = Field(gt=0)
def to_row(f: IrisFeatures) -> list[float]:
return [f.sepal_length, f.sepal_width, f.petal_length, f.petal_width]
class PredictionV1(BaseModel):
class_index: int
class PredictionV2(BaseModel):
class_index: int
class_name: str
model_version: str
v1 = APIRouter(prefix="/v1")
v2 = APIRouter(prefix="/v2")
@v1.post("/predict", response_model=PredictionV1)
def predict_v1(features: IrisFeatures, response: Response):
response.headers["X-Model-Version"] = MODEL_VERSION
index = int(models["iris"].predict([to_row(features)])[0])
return PredictionV1(class_index=index)
@v2.post("/predict", response_model=PredictionV2)
def predict_v2(features: IrisFeatures, response: Response):
response.headers["X-Model-Version"] = MODEL_VERSION
index = int(models["iris"].predict([to_row(features)])[0])
return PredictionV2(
class_index=index,
class_name=CLASS_NAMES[index],
model_version=MODEL_VERSION,
)
app.include_router(v1)
app.include_router(v2)
@app.get("/health")
def health():
return {"status": "ok", "model_loaded": "iris" in models, "model_version": MODEL_VERSION}Run it with a chosen model like this:
MODEL_VERSION=2025-02-03 uvicorn main:app --port 8000Versioning the API
The service above puts the API version in the URL path, so /v1/predict and /v2/predict are separate endpoints. Both run in one process and share one loaded model. The version label stays visible in logs, curl commands, and browser tests.
Other places to carry the version are a request header or a media type. Those keep URLs stable, but they are harder to see and harder to route at a gateway. For a small service, path versioning is the simplest choice.
The diagram shows how requests flow.
Follow these rules when you change the contract:
- Make additive changes inside the current version whenever you can.
- Put breaking changes in a new version, and keep the old one running.
- Announce a retirement date for the old version before you remove it.
- Remove the old version only after your logs show no remaining traffic.
Separate response models for each version matter here. PredictionV1 is frozen, so a later edit to PredictionV2 cannot change what v1 clients receive.
Reporting the model version
Every response should say which model produced it. The v2 body includes model_version, and both versions set an X-Model-Version header. The v1 body stays unchanged so that old clients are not affected.
When a user reports a bad prediction, you can find the model that made it. The same value should appear in your logs, which the observability chapter covers.
Testing both versions
Test each version separately, so that a v2 change cannot silently break v1. This test assumes the artifact for the default MODEL_VERSION exists on disk.
from fastapi.testclient import TestClient
from main import app
PAYLOAD = {
"sepal_length": 5.1,
"sepal_width": 3.5,
"petal_length": 1.4,
"petal_width": 0.2,
}
def test_v1_shape_is_unchanged():
with TestClient(app) as client:
response = client.post("/v1/predict", json=PAYLOAD)
assert response.status_code == 200
assert set(response.json()) == {"class_index"}
def test_v2_reports_model_version():
with TestClient(app) as client:
response = client.post("/v2/predict", json=PAYLOAD)
body = response.json()
assert response.status_code == 200
assert body["model_version"] == response.headers["X-Model-Version"]
assert body["class_name"] in {"setosa", "versicolor", "virginica"}The first test checks that the set of v1 fields is exactly {"class_index"}. If someone adds a field to PredictionV1, it fails and flags the change.
Rolling out a new model safely
Retraining can degrade results even when the code is correct. Move to a new model in stages.
- Offline check. Score the new artifact on a held-out set and compare it with the current one before deploying.
- Shadow mode. Run the new model on live requests, log its output, and return the old model's answer. You see real inputs without any user impact.
- Canary. Send a small share of traffic, such as 5 percent, to replicas running the new version. Watch error rates and prediction distributions, then widen the share.
- Rollback. Keep the previous artifact directory and restart with the earlier
MODEL_VERSION.
Because the version is an environment variable, a canary is a second deployment with a different value. This needs a load balancer in front, which the scaling chapter covers.
Common errors
- Overwriting
model.joblibin place. You lose rollback and cannot tell what was serving at a given time. - Library drift. The image builds with a newer scikit-learn than the one used for training, and the model loads with warnings or behaves differently.
- Changing feature order silently. Predictions stay plausible but wrong. Store the order in metadata and test it.
- Breaking v1 "just slightly". A renamed field is a breaking change, even if the rename feels minor.
- Mixed versions during a rolling restart. For a short time, some replicas serve the old model and some the new one. If clients compare results across requests, this can look inconsistent.
Exercise
You retrain the iris model on more data. The features and output format do not change, and you also want clients to see which model answered. Which versions change, and what is the safest way to add the model name to the response?
Show answer
Only the model version changes. The API version stays the same because the contract is unchanged. Adding model_version as a new optional field is a non-breaking, additive change, and an X-Model-Version header is also safe. Keep the v1 response model frozen and add the field to v2, so existing v1 clients see no change. Roll the new model out by shadowing or a canary, and keep the old artifact directory for rollback.
Exercise
A new training run reorders the input columns to petal_width, petal_length, sepal_width, sepal_length. The service still builds each row in the old order. What happens, and how do you prevent it?
Show answer
The service does not raise an error, because it still sends four positive numbers. The model reads them in the wrong positions and returns wrong but plausible predictions. To prevent this, save feature_order in metadata.json, build rows from that list, and add a test that fails if the service order and the metadata order differ.