Sub topic 12
Versioning models and the API
This chapter assumes you have the FastAPI service from earlier chapters: a /predict endpoint, Pydantic request and response models, and a model loaded at startup.
Two things that change
A model service has two versions, and they change for different reasons.
- The model version identifies the trained artifact. It changes when you retrain or tune. Clients usually don't care, but you need it to debug and compare results.
- The API version identifies the contract: URLs, field names, and types. It changes when the request or response shape changes. Clients depend on it.
Retraining on new data can leave the contract untouched. Renaming class_index to label breaks every client, even if the model is identical. Keep the two versions separate.
Which changes break clients
| Change | Breaking? |
|---|---|
| Add an optional request field with a default | No |
| Add a new field to the response | Usually no |
| Rename or remove a field | Yes |
| Change a field's type or meaning | Yes |
| Swap in a retrained model with the same output meaning | No |
| Change what a class index means | Yes |
The last row is easy to miss. If a new model reorders its classes, the JSON looks the same but the meaning has changed.
Version the API in the URL
A path prefix is the simplest scheme. Each version is a router, and several can run side by side. This example reads the model version from an environment variable and returns it with every prediction.
import os
from contextlib import asynccontextmanager
import joblib
from fastapi import APIRouter, FastAPI
from pydantic import BaseModel, Field
MODEL_VERSION = os.environ.get("MODEL_VERSION", "1.0.0")
MODEL_PATH = f"model-{MODEL_VERSION}.joblib"
models = {}
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)
class PredictionV1(BaseModel):
class_index: int
model_version: str
@asynccontextmanager
async def lifespan(app: FastAPI):
models["iris"] = joblib.load(MODEL_PATH)
yield
models.clear()
app = FastAPI(lifespan=lifespan)
v1 = APIRouter(prefix="/v1")
@v1.post("/predict", response_model=PredictionV1)
def predict(features: IrisFeatures):
row = [[
features.sepal_length,
features.sepal_width,
features.petal_length,
features.petal_width,
]]
prediction = models["iris"].predict(row)[0]
return PredictionV1(class_index=int(prediction), model_version=MODEL_VERSION)
app.include_router(v1)
@app.get("/health")
def health():
return {
"status": "ok",
"model_loaded": "iris" in models,
"model_version": MODEL_VERSION,
}Save the artifact as model-1.0.0.joblib and start the service with MODEL_VERSION=1.0.0 uvicorn main:app. The file name carries the version, so you can keep old artifacts and roll back by changing one variable.
Running two API versions
When you must make a breaking change, add a v2 router with its own response model and keep v1 running. Both routers can share the same loaded model.
Retire v1 only after you have confirmed, from logs, that no clients still call it.
Practical rules
- Return
model_versionin responses and log it with each request, so you can trace a bad prediction to an artifact. - Never overwrite an artifact under the same version. Write a new file and change the version.
- Treat a change in output meaning as a breaking change, even when the schema is unchanged.
- Keep a record of which training data and code produced each artifact.
Exercise
You retrain the iris model and the new artifact predicts the same three classes, but in a different order, so class index 0 now means a different species. The JSON fields are unchanged. Is this a breaking change, and what should you do?
Show answer
Yes. Clients that interpret class_index would silently get wrong meanings. Either keep the old class order when training, or release a new API version (for example /v2/predict) that returns a stable label, and keep /v1 running until clients migrate.