Skip to content

Deployment and MLOps basics

A model in production is a program that other programs call. It must load the right model, reject bad input, answer fast, and warn you when the world changes. This page covers the project layout, saving a model with its metadata, loading it safely, serving it with FastAPI and pydantic, testing the service, detecting drift, tracking experiments with MLflow and what to monitor. The same FastAPI, pydantic and testing patterns apply to any web API. The examples use data/customers.csv. The blocks share one session:

import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
CATEGORICAL = ["plan", "contract"]
NUMERIC = ["age", "tenure_months", "monthly_charges", "support_tickets"]
FEATURES = CATEGORICAL + NUMERIC
customers = pd.read_csv("data/customers.csv")
train, test = train_test_split(customers, test_size=0.2,
stratify=customers["churned"], random_state=42)
pipeline = Pipeline([
("prep", ColumnTransformer([
("cat", OneHotEncoder(handle_unknown="ignore"), CATEGORICAL),
("num", StandardScaler(), NUMERIC),
])),
("model", LogisticRegression(max_iter=1000)),
]).fit(train[FEATURES], train["churned"])
auc = roc_auc_score(test["churned"], pipeline.predict_proba(test[FEATURES])[:, 1])
print(f"test ROC-AUC {auc:.3f}")
Output
test ROC-AUC 0.799
I want to… Use… Notes
repeatable training random_state=42 on every random step splits, models, CV
pin the environment uv lock or uv pip freeze > requirements.txt exact versions
record library versions importlib.metadata.version("scikit-learn") into the metadata
fingerprint a file hashlib.sha256(path.read_bytes()).hexdigest() data and model files
a split that stays stable as data grows zlib.crc32(customer_id.encode()) % 100 < 20 not hash()
read a config file with open("config/train.toml", "rb") as f: cfg = tomllib.load(f) binary mode
save a model with metadata joblib.dump({"pipeline": p, "metadata": m}, path) + a JSON sidecar
check a model before loading read the JSON sidecar: versions, features, SHA-256 before joblib.load; a trusted copy of the hash stops tampering
load a saved model joblib.load(path) only files you created
a JSON API app = FastAPI(), @app.post("/predict")
validate a request body a pydantic BaseModel as the parameter type 422 on failure
a number in a range Field(ge=18, le=100) gt, lt for strict bounds
fixed categories only Literal["basic", "standard", "premium"] unknown values → 422
reject unknown fields model_config = ConfigDict(extra="forbid") catches typos
reject inf and NaN ConfigDict(allow_inf_nan=False)
no type conversion ConfigDict(strict=True) "34" is an error
load the model once at start-up FastAPI(lifespan=lifespan)
“not ready” / “failed” answers HTTPException(status_code=503), 500 generic detail
run the API uvicorn app:app --reload development
test the API without a server with TestClient(app) as client: needs httpx2
a request in a test client.post("/predict", json=payload) .status_code, .json()
measure a shift in a feature PSI on reference deciles > 0.25 = major
test a continuous shift scipy.stats.ks_2samp(ref, cur) not for 0/1 or categories
a categorical shift PSI on category shares, or chi2_contingency
a local experiment store mlflow.set_tracking_uri("sqlite:///mlflow.db") not file:./mlruns
log a run with mlflow.start_run(): mlflow.log_params(...); mlflow.log_metrics(...)
compare runs mlflow.search_runs(order_by=["metrics.auc DESC"]) a DataFrame
open the tracking UI mlflow ui --backend-store-uri sqlite:///mlflow.db Terminal
Project layout
churn-service/
├── pyproject.toml # dependencies, pinned by uv.lock
├── uv.lock
├── config/train.toml # seed, paths, hyperparameters
├── data/raw/ # read-only snapshots (not in git when large)
├── models/ # model bundles + JSON sidecars (not in git)
├── notebooks/ # exploration only
├── src/churn/
│ ├── features.py # column lists, build_pipeline()
│ ├── train.py # python -m churn.train: data -> models/
│ ├── bundle.py # save_bundle(), load_bundle()
│ └── api.py # FastAPI app
└── tests/
├── test_bundle.py
└── test_api.py # TestClient
Rule Why
one module defines the features and the pipeline training and serving cannot drift apart
training is a script, not a notebook one command, top to bottom, repeatable
configs in a file, not in code change settings without changing code
models and data snapshots out of git large binary files; store them elsewhere with their hash
tests for the bundle and the API catch broken models before users do
Reproducibility source Fix Record
random steps seed each one seed
library versions lock file sklearn_version, …
data snapshot + SHA-256 data_sha256
test rows hash split by a permanent id the split rule
code and settings git commit + config file git_commit, model_version
import hashlib
import json
from pathlib import Path
import joblib
import sklearn
def file_sha256(path: Path) -> str:
return hashlib.sha256(path.read_bytes()).hexdigest()
def save_bundle(pipeline, metadata: dict, path: Path) -> None:
"""One joblib file (pipeline + metadata) and a JSON sidecar with its hash."""
path.parent.mkdir(parents=True, exist_ok=True)
joblib.dump({"pipeline": pipeline, "metadata": metadata}, path)
sidecar = metadata | {"bundle_sha256": file_sha256(path)}
path.with_suffix(".json").write_text(json.dumps(sidecar, indent=2))
metadata = {
"model_version": "1.0.0",
"trained_at": "2025-01-06", # write the real date in train.py
"sklearn_version": sklearn.__version__,
"features": FEATURES,
"metrics": {"test_roc_auc": round(auc, 4)},
"threshold": 0.5,
}
MODEL_PATH = Path("models/churn.joblib")
save_bundle(pipeline, metadata, MODEL_PATH)
sidecar = json.loads(MODEL_PATH.with_suffix(".json").read_text())
print(sorted(sidecar)[:4], len(sidecar))
Output
['bundle_sha256', 'features', 'metrics', 'model_version'] 7
Metadata field Why
model_version logs, API responses and bug reports refer to it
trained_at the age of the model
data_sha256 which data trained it
sklearn_version (and pandas, NumPy) a pickle needs the same versions
features the exact inputs, in order
metrics the baseline for monitoring
threshold how a probability becomes an action

A joblib or pickle file can run code when it loads. Check what you can before joblib.load, using only the plain JSON sidecar. The hash detects a corrupted, replaced or accidentally changed file. It does not stop an attacker who can also rewrite the sidecar next to it. Against tampering, keep the expected hash where they cannot write (a model registry, the deploy config in git, a signed manifest), or share models as skops or ONNX files.

class ModelLoadError(RuntimeError):
"""The saved bundle cannot be used safely."""
def load_bundle(path: Path) -> dict:
sidecar = path.with_suffix(".json")
if not path.exists() or not sidecar.exists():
raise ModelLoadError(f"{path.name} or its sidecar is missing")
meta = json.loads(sidecar.read_text()) # JSON cannot run code
if meta["sklearn_version"] != sklearn.__version__:
raise ModelLoadError(f"saved with scikit-learn {meta['sklearn_version']}")
if meta["features"] != FEATURES:
raise ModelLoadError("the feature list changed")
if file_sha256(path) != meta["bundle_sha256"]:
raise ModelLoadError(f"{path.name} changed since it was saved")
return joblib.load(path) # only after every check
bundle = load_bundle(MODEL_PATH)
print(bundle["metadata"]["model_version"], type(bundle["pipeline"]).__name__)
Output
1.0.0 Pipeline

A changed file (with an unchanged sidecar) is refused before it is unpickled:

Path("models/copy.joblib").write_bytes(MODEL_PATH.read_bytes() + b"\x00")
Path("models/copy.json").write_text(MODEL_PATH.with_suffix(".json").read_text())
load_bundle(Path("models/copy.joblib"))
Output
ModelLoadError: copy.joblib changed since it was saved
Format Safe to load from others Use
joblib / pickle no: can run code your own models, same versions
skops.io with an explicit list of trusted types sharing scikit-learn models
ONNX yes (data only) fast, cross-language serving
torch.save(state_dict) + torch.load(weights_only=True) mostly: tensors and plain types only PyTorch weights
JSON sidecar yes metadata you check first
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from typing import Literal
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, ConfigDict, Field
models: dict[str, dict] = {}
class Customer(BaseModel):
"""The request body. Every field is checked before the model runs."""
model_config = ConfigDict(extra="forbid", allow_inf_nan=False)
plan: Literal["basic", "standard", "premium"]
contract: Literal["month-to-month", "one-year", "two-year"]
age: int = Field(ge=18, le=100)
tenure_months: int = Field(ge=0, le=600)
monthly_charges: float = Field(gt=0, le=1000)
support_tickets: int = Field(default=0, ge=0, le=100)
class Prediction(BaseModel):
churn_probability: float
will_churn: bool
model_version: str
@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
models["churn"] = load_bundle(MODEL_PATH) # once, at start-up
yield
models.clear()
app = FastAPI(title="Churn API", lifespan=lifespan)
@app.get("/health")
def health() -> dict[str, str]:
if "churn" not in models:
raise HTTPException(status_code=503, detail="model not loaded")
version = models["churn"]["metadata"]["model_version"]
return {"status": "ok", "model_version": version}
@app.post("/predict")
def predict(customer: Customer) -> Prediction:
if "churn" not in models:
raise HTTPException(status_code=503, detail="model not loaded")
bundle = models["churn"]
row = pd.DataFrame([customer.model_dump()], columns=FEATURES) # fixed column order
proba = float(bundle["pipeline"].predict_proba(row)[0, 1])
return Prediction(churn_probability=round(proba, 4),
will_churn=proba >= bundle["metadata"]["threshold"],
model_version=bundle["metadata"]["model_version"])
Terminal
uvicorn app:app --reload # development server on http://127.0.0.1:8000
curl -X POST http://127.0.0.1:8000/predict \
-H "Content-Type: application/json" -d @customer.json # body from a JSON file

Open http://127.0.0.1:8000/docs for the interactive schema that FastAPI builds from the pydantic models.

pydantic tool Meaning
x: int type check with lax conversion: "34" → 34
Field(ge=0, le=120) / Field(gt=0, lt=1) inclusive / exclusive range
Field(min_length=1, max_length=100) length of a string or list
Field(pattern=r"^C\d{5}$") a regex for strings
Literal["a", "b"] exact allowed values
x: float | None = None optional field
ConfigDict(extra="forbid") unknown fields are errors
ConfigDict(strict=True) no conversions
ConfigDict(allow_inf_nan=False) reject inf and NaN
Model.model_validate(d), obj.model_dump() dict → model, model → dict
Status Meaning in an ML API
200 prediction returned
404 unknown resource
422 the body failed validation; detail lists every error
500 the model or the code failed; log the cause, send a generic detail
503 not ready: the model is not loaded

TestClient calls the app in-process, without a server. In the course environment it runs on the httpx2 package; without it, importing TestClient warns.

from fastapi.testclient import TestClient
payload = {"plan": "basic", "contract": "month-to-month", "age": 30,
"tenure_months": 2, "monthly_charges": 70.0, "support_tickets": 3}
loyal = payload | {"contract": "two-year", "tenure_months": 60, "support_tickets": 0}
with TestClient(app) as client: # "with" runs the lifespan: the model loads
print(client.get("/health").json())
risky = client.post("/predict", json=payload)
safe = client.post("/predict", json=loyal)
print(risky.status_code, risky.json())
print(risky.json()["churn_probability"] > safe.json()["churn_probability"])
bad = client.post("/predict", json=payload | {"age": 16, "plan": "gold",
"promo": "X"})
print(bad.status_code, [(e["loc"][-1], e["type"]) for e in bad.json()["detail"]])
saved = models.pop("churn") # simulate a model that failed to load
print(client.post("/predict", json=payload).json())
models["churn"] = saved
Output
{'status': 'ok', 'model_version': '1.0.0'}
200 {'churn_probability': 0.6286, 'will_churn': True, 'model_version': '1.0.0'}
True
422 [('plan', 'literal_error'), ('age', 'greater_than_equal'), ('promo', 'extra_forbidden')]
{'detail': 'model not loaded'}
tests/test_api.py
import pytest
from fastapi.testclient import TestClient
from churn import api
VALID = {"plan": "basic", "contract": "month-to-month", "age": 30,
"tenure_months": 2, "monthly_charges": 70.0, "support_tickets": 3}
RISKY = VALID
LOYAL = VALID | {"contract": "two-year", "tenure_months": 60, "support_tickets": 0}
@pytest.fixture(scope="module")
def client():
with TestClient(api.app) as c: # runs the lifespan once for the module
yield c
def test_health(client):
assert client.get("/health").json()["status"] == "ok"
@pytest.mark.parametrize("field, value", [("age", 16), ("plan", "gold"),
("monthly_charges", -5)])
def test_invalid_input_is_422(client, field, value):
body = VALID | {field: value}
assert client.post("/predict", json=body).status_code == 422
def test_risky_scores_higher_than_loyal(client): # an ordering, not exact numbers
risky = client.post("/predict", json=RISKY).json()["churn_probability"]
loyal = client.post("/predict", json=LOYAL).json()["churn_probability"]
assert risky > loyal
def test_missing_model_is_503(client, monkeypatch):
monkeypatch.delitem(api.models, "churn") # restored after the test
assert client.post("/predict", json=VALID).status_code == 503
Test Asserts
health 200 and the model version
valid input 200, a probability in [0, 1]
invalid input 422 for each bad field
ordering risky profiles score higher than loyal ones
model missing 503, not a crash
bundle checks changed file or other versions → ModelLoadError

Do not assert exact probabilities: they change with every retraining.

PSI=∑i=1B(ci−ri)ln⁡ciriD=max⁡x∣Fref(x)−Fcur(x)∣\mathrm{PSI} = \sum_{i=1}^{B} (c_i - r_i)\ln\frac{c_i}{r_i} \qquad D = \max_x \lvert F_\text{ref}(x) - F_\text{cur}(x) \rvert

rir_i and cic_i are the shares of the reference and the current data in bin ii. The bins are the deciles of the reference data. DD is the Kolmogorov–Smirnov (KS) statistic: the largest gap between the two cumulative distributions.

from scipy.stats import ks_2samp
def psi(reference, current, bins: int = 10) -> float:
"""Population stability index on the deciles of the reference data."""
reference, current = np.asarray(reference), np.asarray(current)
inner = np.unique(np.quantile(reference, np.linspace(0, 1, bins + 1))[1:-1])
r = np.bincount(np.searchsorted(inner, reference, side="right"),
minlength=len(inner) + 1) / len(reference)
c = np.bincount(np.searchsorted(inner, current, side="right"),
minlength=len(inner) + 1) / len(current)
r, c = np.clip(r, 1e-4, None), np.clip(c, 1e-4, None) # avoid log(0)
return float(np.sum((c - r) * np.log(c / r)))
signup = pd.to_datetime(customers["signup_date"])
reference = customers[signup < "2023-01-01"] # older customers
current = customers[signup >= "2024-01-01"] # this year's sign-ups
for col in ["age", "monthly_charges", "tenure_months"]:
ks = ks_2samp(reference[col], current[col])
print(f"{col:<16} PSI {psi(reference[col], current[col]):6.3f} "
f"KS D {ks.statistic:.3f} p {ks.pvalue:.2g}")
Output
age PSI 0.015 KS D 0.021 p 0.77
monthly_charges PSI 0.035 KS D 0.038 p 0.12
tenure_months PSI 8.663 KS D 1.000 p 0

Age and charges are stable. Tenure shows a huge shift, but by construction: this year’s sign-ups cannot have long tenure. A feature tied to time drifts on purpose; compare like with like, or monitor it against the same cohort last year.

PSI Reading Action
below 0.1 stable none
0.1–0.25 moderate check the feature and its source
above 0.25 major investigate; consider retraining
Drift kind What changes Needs labels Check
data drift (covariate shift) input distributions no PSI, KS per feature
prediction drift score distribution, flag rate no PSI on the scores
prior (label) shift class shares yes the positive rate
concept drift the input–target relation yes the metric on new labels
track.py (MLflow 3.18)
import logging
import os
import mlflow
import mlflow.sklearn
from mlflow.models import infer_signature
logging.getLogger("mlflow").setLevel(logging.WARNING) # hide INFO lines
os.environ["MLFLOW_ENABLE_ARTIFACTS_PROGRESS_BAR"] = "false" # no tqdm on stderr
mlflow.set_tracking_uri("sqlite:///mlflow.db") # file:./mlruns raises in 3.18
mlflow.set_experiment("churn-baseline")
for C in [0.1, 1.0]:
with mlflow.start_run(run_name=f"logreg-C{C}"): # one run per setting
model = build_pipeline(C=C).fit(X_train, y_train)
mlflow.log_params({"C": C, "seed": 42})
mlflow.log_metrics({"cv_auc_mean": cv_auc(model)})
mlflow.set_tag("data_sha256", data_hash)
signature = infer_signature(X_train, model.predict_proba(X_train))
mlflow.sklearn.log_model(
model, name="model", signature=signature,
pyfunc_predict_fn="predict_proba", # generic loader returns probabilities
skops_trusted_types=["numpy.dtype"], # MLflow 3 saves with skops
pip_requirements=[f"scikit-learn=={sklearn.__version__}"],
)
runs = mlflow.search_runs(experiment_names=["churn-baseline"],
order_by=["metrics.cv_auc_mean DESC"])
best = mlflow.sklearn.load_model(f"runs:/{runs.iloc[0]['run_id']}/model")
Call Does
mlflow.set_tracking_uri("sqlite:///mlflow.db") a local database file in the current folder
mlflow.set_experiment(name) create or select an experiment
with mlflow.start_run(run_name=...) one run; closes itself
log_params, log_metrics, set_tag settings (stored as text), results, labels
log_artifact(path) any file: a chart, a report
mlflow.sklearn.log_model(...) the model with signature and requirements
mlflow.search_runs(...) runs as a DataFrame: params.*, metrics.*, tags.*
mlflow.sklearn.load_model("runs:/<id>/model") the original pipeline
mlflow.pyfunc.load_model(uri) a generic predict() that checks the signature
mlflow ui --backend-store-uri sqlite:///mlflow.db the web UI (Terminal)

Log cross-validation scores for model selection. Touch the test set once, for the final model.

  1. Service: request count, error rate (5xx), latency (p50, p95). Alert: p95 above your budget.
  2. Input quality: 422 rate, missing values, unknown categories, values at the edge of the allowed ranges. Alert: more than 2% rejected.
  3. Data drift: PSI per feature against the training data, every day or week. Alert: any PSI above 0.25.
  4. Prediction drift: PSI of the scores, the share of positive decisions. Alert: the flag rate moves by a third.
  5. Performance: the training metric (ROC-AUC, recall) on new labels when they arrive. Alert: a drop larger than the CV spread.
  6. Traceability: log the model version, the input and the output of every prediction (without personal data you do not need).
  7. Retraining: a written rule (schedule or alert), the same training script, a comparison with the current model before the switch.
  8. Rollback: keep the previous bundle and switch back with one change.
Trap Symptom Fix
hash("C00001") for a split a different split in every process zlib.crc32 or hashlib
random split with a seed the test set changes when rows are added hash split by a permanent id
joblib.load on files from others arbitrary code runs load only your files; check the hash first
other scikit-learn version only an InconsistentVersionWarning; predictions may change or fail check the version in the sidecar and refuse
checks after joblib.load too late for a malicious file check the hash against a trusted record before loading
expected hash stored next to the model an attacker who replaces the model rewrites the sidecar too keep the hash in a registry, the deploy config or a signed manifest
no Literal on categories an unknown category becomes an all-zero one-hot row Literal[...] → 422
no extra="forbid" a misspelled optional field is ignored silently ConfigDict(extra="forbid")
lax mode "34" → 34, "yes" → True strict=True where that matters
float fields by default NaN, Infinity, 1e308 accepted allow_inf_nan=False and an upper bound
TestClient(app) without with the lifespan never runs: 503 with TestClient(app) as client:
TestClient without httpx2 a warning on import install the pinned requirements
relative paths in uvicorn app:app the model file is not found build paths from Path(__file__).parent
leaking stack traces internal details in 500 responses log the error; send a generic detail
KS test on 0/1 or few values misleading p-values PSI on the values, or a chi-square test
KS on large samples tiny, harmless shifts are “significant” decide on the PSI or the size of D
PSI bins from the current data drift hidden bins from the reference data
file:./mlruns in MLflow 3.18 MlflowException sqlite:///mlflow.db
MLflow logs and progress bars INFO lines and tqdm bars on stderr mlflow logger to WARNING, MLFLOW_ENABLE_ARTIFACTS_PROGRESS_BAR=false
params.* from search_runs strings, not numbers runs["params.C"].astype(float)
choosing runs by the test score an optimistic final score select on CV; test once