Most machine learning projects stall in the same place: the model works in a notebook, and then nothing happens. The model is rarely the problem. What’s missing is a repeatable process that turns a trained model into something another person or system can call, trust, and roll back.
In this tutorial, you’ll take a small churn prediction model from a training script to a tested, benchmarked, containerized API. Along the way, you’ll build a release checklist you can reuse on your own projects. To follow along, you should be comfortable with Python, scikit-learn basics, and running commands in a terminal. You don’t need prior experience with Docker or FastAPI.
Each section follows the same rhythm. You write a small piece of the system, run it to see real output, then step back and understand why it exists. That rhythm matters more than the specific tools, because the same reasoning applies if you later swap FastAPI for another framework or scikit-learn for a different library. The goal is to leave you with a process you can carry into your own projects, not a recipe tied to one stack.
By the end of this tutorial, you’ll understand that:
A notebook and a service solve different problems. A notebook helps you explore. A service has to behave predictably when someone else sends it data you never saw.
The gap exists because a notebook hides its assumptions. The columns are already in the right order, the scaler was fitted three cells ago, and the library versions are whatever happened to be installed that day. None of this is a mistake while you explore, but each hidden assumption becomes a possible production failure the moment another person or system depends on the model.
The running example is a customer churn predictor with four features: tenure_months, monthly_charges, support_tickets, and late_payments. The training data is generated synthetically with a fixed seed so you can reproduce every number in this tutorial. Because the data is synthetic, the metrics describe the pipeline, not a real business.
The results shown here come from Python 3.12.3, scikit-learn 1.5.2, and FastAPI 0.165.0 on Linux. Your latency numbers will differ on other hardware.
Think of a production-ready model as three things shipped together: the model itself, the data contract it expects, and the environment it runs in. If any one of them changes without the others, predictions can degrade without a single error message. The rest of this tutorial turns each of those three into something explicit that you can check, test, and version.
Training-serving skew is the first failure to expect. In the notebook you scale the features before fitting, and in the service you forget to repeat the same scaling. Nothing crashes, the endpoint returns a number between 0 and 1, and the number is simply wrong. Because there is no error, the problem can run for weeks before someone questions the results.
The second failure is a silent dependency change. A library update can alter a default value, rename a parameter, or change how a saved object is read back. The code you wrote didn’t change, but the behavior did, and the only evidence is a number that looks slightly different from last month.
The third failure comes from the data. A client might send tenure in days instead of months, or send a monthly charge in a different currency. The model accepts any number it is given, so it returns a confident prediction for a customer who doesn’t exist. Each of these failures produces a plausible output instead of an error, which is why the rest of this process focuses on making problems loud and early.
With that picture in mind, you can set up the project.
Create a project folder with this layout:
ml-service/├── .github/│ └── workflows/│ └── ci.yml├── artifacts/│ ├── metadata.json│ └── model.joblib├── app.py├── artifact.py├── benchmark.py├── Dockerfile├── drift.py├── requirements.txt├── sim_traffic.py├── test_app.py├── test_artifact.py└── train.py
You won’t create every file at once. The files artifact.py, drift.py, sim_traffic.py, test_artifact.py, and the CI workflow are added in later sections, as the process grows from a working service into a trustworthy one.
The structure enforces one rule: training code produces artifacts, and serving code only loads them. train.py never runs inside the API, and app.py never trains anything. That separation keeps the service small and makes each half testable on its own.
Mixing training and serving code is tempting because it feels faster, but it creates a quiet coupling. A change to the training logic can then alter the live service without anyone deciding to release it, and a bug in the service can only be reproduced by retraining. Keeping the two apart gives each half a clear owner and a clear output. It also helps you avoid training-serving skew, where the transformations used at training time don’t match the ones used at prediction time.
Save these pinned dependencies as requirements.txt. They are the exact versions used to produce the results in this tutorial:
scikit-learn==1.5.2joblib==1.6.0numpy==2.5.5pandas==3.1.1fastapi==0.165.0uvicorn==0.55.0pydantic==2.14.4pytest==9.2.0httpx==0.29.0
Exact pins can look rigid, but they are what makes a result reproducible. Without them, pip install resolves to whatever is newest on the day you run it, and a minor release of a library can change behavior, add a warning, or break a saved model. Pinning means the environment you tested is the environment you ship. You can still upgrade deliberately, one dependency at a time, with the tests and the benchmark as your safety net.
Then create and activate a virtual environment and install them:
python -m venv .venvsource .venv/bin/activatepip install -r requirements.txt
Next, you’ll write the training script that creates the artifact.
Save the following as train.py:
import hashlibimport jsonfrom pathlib import Path
python
import joblibimport numpy as npimport pandas as pdimport sklearnfrom sklearn.linear_model import LogisticRegressionfrom sklearn.metrics import roc_auc_scorefrom sklearn.model_selection import train_test_splitfrom sklearn.pipeline import Pipelinefrom sklearn.preprocessing import StandardScalerSEED = 42FEATURES = ["tenure_months", "monthly_charges", "support_tickets", "late_payments"]ARTIFACT_DIR = Path("artifacts")def make_data(n=5_000): rng = np.random.default_rng(SEED) df = pd.DataFrame( { "tenure_months": rng.integers(1, 72, n), "monthly_charges": rng.normal(70, 20, n).clip(15, 150), "support_tickets": rng.poisson(1.5, n), "late_payments": rng.poisson(0.5, n), } ) logit = ( -1.0 - 0.04 * df["tenure_months"] + 0.02 * df["monthly_charges"] + 0.35 * df["support_tickets"] + 0.6 * df["late_payments"] ) prob = 1 / (1 + np.exp(-logit)) df["churned"] = rng.binomial(1, prob) return dfdef main(): df = make_data() X, y = df[FEATURES], df["churned"] X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=SEED, stratify=y ) model = Pipeline( [ ("scale", StandardScaler()), ("clf", LogisticRegression(max_iter=1000)), ] ) model.fit(X_train, y_train) auc = roc_auc_score(y_test, model.predict_proba(X_test)[:, 1]) ARTIFACT_DIR.mkdir(exist_ok=True) model_path = ARTIFACT_DIR / "model.joblib" joblib.dump(model, model_path) metadata = { "features": FEATURES, "sklearn_version": sklearn.__version__, "test_auc": round(float(auc), 4), "model_sha256": hashlib.sha256(model_path.read_bytes()).hexdigest(), } (ARTIFACT_DIR / "metadata.json").write_text(json.dumps(metadata, indent=2)) print(json.dumps(metadata, indent=2))if __name__ == "__main__": main()
Four decisions in this script matter more than the model itself:
A fixed seed and a stratified split make the run reproducible, so a metric change always has a cause you can find.
A Pipeline bundles the scaler with the classifier. A classic bug is scaling features in the notebook and forgetting to do it in the service. When the scaler travels inside the artifact, that bug can't happen.
Feature order is saved in the metadata. A model expects columns in the order it was trained on, so the API will reorder incoming data using this list.
The scikit-learn version and a SHA-256 hash are recorded. joblib uses pickle under the hood, and a model under a different scikit-learn version can raise a warning or fail. The hash lets you confirm that the file you deploy is the file you trained.
Taken together, these choices mean the artifact can answer three questions on its own: what was this model trained to expect, which environment can load it safely, and has the file changed since training. A model without that information is a black box that only its author understands, and even the author forgets the details within a few weeks. Writing the metadata costs a few lines of code and saves hours of guessing during an incident.
Note: Only load joblib or pickle files that you created yourself or fully trust. Unpickling a malicious file can execute arbitrary code.
Run the script:
python train.py
{ "features": [ "tenure_months", "monthly_charges", "support_tickets", "late_payments" ], "sklearn_version": "1.5.2", "test_auc": 0.7835, "model_sha256": "19c297770a5cbd75eb491dd04bc11ac929060a50219446999f2fc3f7ebbf6b3e"}
The test AUC is 0.7835, and model.joblib is only 1,758 bytes because logistic regression stores very little. Real models are usually much larger, which affects image size and startup time later.
Treat the AUC as a baseline for comparison, not as a promise about production. It is measured on synthetic data with a hold-out split, so here it only shows that the pipeline runs end to end. In a real project you would record the same number for every retrain, because a release decision is easier to defend when it compares two numbers instead of relying on a feeling.
With an artifact on disk, you can build the service that loads it.
Save the following as app.py:
import jsonfrom contextlib import asynccontextmanagerfrom pathlib import Path
python
import joblibimport pandas as pdfrom fastapi import FastAPI, HTTPExceptionfrom pydantic import BaseModel, FieldARTIFACT_DIR = Path("artifacts")state = {}@asynccontextmanagerasync def lifespan(app: FastAPI): state["model"] = joblib.load(ARTIFACT_DIR / "model.joblib") state["meta"] = json.loads((ARTIFACT_DIR / "metadata.json").read_text()) yield state.clear()app = FastAPI(title="Churn Service", lifespan=lifespan)class Customer(BaseModel): tenure_months: int = Field(ge=0, le=120) monthly_charges: float = Field(ge=0, le=500) support_tickets: int = Field(ge=0, le=100) late_payments: int = Field(ge=0, le=100)class Prediction(BaseModel): churn_probability: float model_auc: float@app.get("/health")def health(): if "model" not in state: raise HTTPException(status_code=503, detail="Model not loaded") return {"status": "ok", "sklearn_version": state["meta"]["sklearn_version"]}@app.post("/predict", response_model=Prediction)def predict(customer: Customer): row = pd.DataFrame([customer.model_dump()])[state["meta"]["features"]] proba = float(state["model"].predict_proba(row)[0, 1]) return Prediction( churn_probability=round(proba, 4), model_auc=state["meta"]["test_auc"] )
This file makes three choices worth naming:
Validation at the boundary matters because most production incidents begin with data, not with code. Clients send nulls, negative numbers, strings where numbers belong, and values in different units than the training data used. The bounds in the Customer model are business assumptions written down in one place. When a request breaks them, the client receives a clear 422 response instead of the service returning a confident prediction built on nonsense.
Start the server:
uvicorn app:app --port 8000
In another terminal, check the health endpoint and send a prediction request:
curl -s localhost:8000/healthcurl -s -X POST localhost:8000/predict \ -H "Content-Type: application/json" \ -d '{"tenure_months":12,"monthly_charges":80.0,"support_tickets":3,"late_payments":1}'
{"status":"ok","sklearn_version":"1.5.2"}{"churn_probability":0.8508,"model_auc":0.7835}
Now send an invalid request with "tenure_months": -5. The API rejects it with a 422 status and an explanation instead of returning a meaningless prediction:
{"detail":[{"type":"greater_than_equal","loc":["body","tenure_months"],"msg":"Input should be greater than or equal to 0","input":-5,"ctx":{"ge":0}}]}
One detail about the endpoint code is worth knowing. The predict function is defined with def rather than async def, so FastAPI runs it in a worker thread pool. That keeps the blocking scikit-learn call from stalling the event loop that handles other requests. If you rewrote it as async def while still calling the model synchronously, a slow prediction would block every other request until it finished.
The service works by hand. Next, you’ll make sure it keeps working when someone changes the code.
Save the following as test_app.py:
import pytestfrom fastapi.testclient import TestClient
python
from app import app@pytest.fixture(scope="module")def client(): with TestClient(app) as c: yield cGOOD = { "tenure_months": 12, "monthly_charges": 80.0, "support_tickets": 3, "late_payments": 1,}def test_health(client): assert client.get("/health").json()["status"] == "ok"def test_predict_returns_probability(client): body = client.post("/predict", json=GOOD).json() assert 0.0 <= body["churn_probability"] <= 1.0def test_risky_customer_scores_higher_than_loyal_one(client): risky = {**GOOD, "tenure_months": 1, "late_payments": 5} loyal = {** GOOD, "tenure_months": 70, "late_payments": 0, "support_tickets": 0} p_risky = client.post("/predict", json=risky).json()["churn_probability"] p_loyal = client.post("/predict", json=loyal).json()["churn_probability"] assert p_risky > p_loyaldef test_rejects_negative_values(client): resp = client.post("/predict", json={**GOOD, "tenure_months": -5}) assert resp.status_code == 422def test_rejects_missing_field(client): bad = {k: v for k, v in GOOD.items() if k != "late_payments"} assert client.post("/predict", json=bad).status_code == 422
Run the tests:
pytest -q
All five pass:
5 passed
The tests fall into three groups, and each one protects against a different failure:
The behavior test deserves a closer look because it encodes domain knowledge instead of exact numbers. Exact probabilities change every time you retrain, so a test that expects 0.8508 would eventually fail for the wrong reason. A test that asserts a high-risk customer scores above a loyal one keeps passing through harmless retrains and fails when something fundamental breaks. Tests like these also work as documentation, since a new teammate can read them and learn what the model is supposed to do.
Notice that the fixture uses TestClient as a context manager. That is what triggers the startup logic that loads the model. Without the with block, /health would return 503 in your tests.
These tests cover the service, not the model’s quality. They can’t tell you whether the model is accurate on real customers, or whether the training data still resembles what clients send. That work belongs to evaluation and monitoring, which have their own tools. Keeping the two concerns separate stops you from treating a green test run as proof that the model is good, when it only proves that the service behaves as designed.
Once the behavior is locked in, there is one more failure the tests can’t see: a perfectly valid request served by the wrong model.
Passing tests don’t guarantee that the service loads the right model in the right environment. Two things can go wrong without breaking a single test: the artifact file can differ from the one you trained, or the libraries installed at serving time can differ from the ones used during training. This section adds a startup check that turns both problems into loud, immediate failures.
To see the second problem for yourself, create a separate virtual environment with an older scikit-learn release such as 1.4.2, then load the artifact from the project folder. On the test machine, this environment used scikit-learn 1.4.2 together with a NumPy release below 2.0.
python -W always -c "import joblib; joblib.load('artifacts/model.joblib')"
The model loads, but scikit-learn warns that it was saved by a different version:
InconsistentVersionWarning: Trying to unpickle estimator Pipeline from version 1.5.2 when using version 1.4.2. This might lead to breaking code or invalid results. Use at your own risk.
That warning is easy to miss in a busy log, and the model still loaded without raising an error. A deployment pipeline that only checks whether the process is running would report success. You want a stricter rule: if the environment doesn’t match the one recorded in the metadata, refuse to start.
Save the following as artifact.py:
import hashlibimport jsonfrom pathlib import Path
python
import joblibimport sklearn
class ArtifactError(RuntimeError): pass
python
def load_verified(artifact_dir: Path): model_path = artifact_dir / "model.joblib" meta = json.loads((artifact_dir / "metadata.json").read_text())
actual_hash = hashlib.sha256(model_path.read_bytes()).hexdigest() if actual_hash != meta["model_sha256"]: raise ArtifactError("model.joblib does not match the hash in metadata.json")
if sklearn.__version__ != meta["sklearn_version"]: raise ArtifactError( f"Model was trained with scikit-learn {meta['sklearn_version']}, " f"but {sklearn.__version__} is installed" )
return joblib.load(model_path), meta
The function runs two checks before it loads anything. The first compares the SHA-256 hash of model.joblib with the hash that train.py recorded, which catches a file that was replaced, corrupted, or copied from the wrong release. The second compares the installed scikit-learn version with the one in the metadata. Checking the hash before calling joblib.load also matters for safety, because unpickling a file you haven't verified is the risky step.
Now update app.py so the service uses this function. Replace the imports of json and joblib that were only used for , and change the top of the file and the lifespan function like this:
import osfrom contextlib import asynccontextmanagerfrom pathlib import Path
python
from artifact import load_verified
ARTIFACT_DIR = Path(os.getenv("ARTIFACT_DIR", "artifacts"))state = {}
python
@asynccontextmanagerasync def lifespan(app: FastAPI): state["model"], state["meta"] = load_verified(ARTIFACT_DIR) yield state.clear()
The artifact folder now comes from an environment variable with a sensible default. That small change lets the same code read artifacts from a different location in a container or a test without editing the source. If you start the service in the older environment, it now stops immediately with a clear message instead of serving requests:
artifact.ArtifactError: Model was trained with scikit-learn 1.5.2, but 1.4.2 is installed
Failing at startup is the point. A container platform that sees the process exit will not route traffic to it, so a mismatched environment never reaches a user.
A safety check that you never exercise is only a hope. Save the following as test_artifact.py:
import jsonimport shutilfrom pathlib import Path
python
import pytestfrom artifact import ArtifactError, load_verifiedSOURCE = Path("artifacts")def test_valid_artifact_loads(tmp_path): shutil.copytree(SOURCE, tmp_path / "artifacts") model, meta = load_verified(tmp_path / "artifacts") assert meta["features"]def test_tampered_model_is_rejected(tmp_path): shutil.copytree(SOURCE, tmp_path / "artifacts") model_file = tmp_path / "artifacts" / "model.joblib" model_file.write_bytes(model_file.read_bytes() + b"\x00") with pytest.raises(ArtifactError, match="hash"): load_verified(tmp_path / "artifacts")def test_version_mismatch_is_rejected(tmp_path): shutil.copytree(SOURCE, tmp_path / "artifacts") meta_file = tmp_path / "artifacts" / "metadata.json" meta = json.loads(meta_file.read_text()) meta["sklearn_version"] = "0.0.1" meta_file.write_text(json.dumps(meta)) with pytest.raises(ArtifactError, match="scikit-learn"): load_verified(tmp_path / "artifacts")
Each test copies the real artifact into a temporary folder and then damages the copy in one specific way. The first confirms the happy path still works. The second appends a single byte to the model file, which changes its hash. The third rewrites the recorded scikit-learn version to one that can’t match. Working on a copy matters, because a test should never modify the artifact you plan to ship. Run the whole suite from the project root:
pytest -q
8 passed
The five original tests and the three new ones all pass. With the artifact protected, you can measure how fast the service responds.
Someone will eventually ask how fast the service is. Answer with a measurement instead of a guess. Save this as benchmark.py:
import statisticsimport time
python
import httpxURL = "http://127.0.0.1:8000/predict"PAYLOAD = { "tenure_months": 12, "monthly_charges": 80.0, "support_tickets": 3, "late_payments": 1,}with httpx.Client() as client: for _ in range(50): # warm-up client.post(URL, json=PAYLOAD) timings = [] for _ in range(500): start = time.perf_counter() client.post(URL, json=PAYLOAD) timings.append((time.perf_counter() - start) * 1000)timings.sort()print(f"median: {statistics.median(timings):.2f} ms")print(f"p95: {timings[int(len(timings) * 0.95)]:.2f} ms")print(f"p99: {timings[int(len(timings) * 0.99)]:.2f} ms")
With the server running, execute it:
python benchmark.py
The script sends 50 warm-up requests, then times 500 sequential requests. On the test machine, the results were:
Median: 3.40 ms
p95: 4.79 ms
p99: 5.70 ms
Two details make this benchmark more honest than a single timing:
This is not a load test. It used one client, one machine, and the local loopback interface, so it excludes network time and concurrent traffic. Treat it as a baseline you can compare against after every change, and set a latency budget for your own project, for example, “p95 under 50 ms”.
A latency budget turns the benchmark into a decision tool. Once you agree on a number, any change that pushes the p95 beyond it, such as a larger model, heavier preprocessing, or an extra feature lookup, becomes visible before release instead of after a user complains. Run the same script before and after each change and keep the results in the pull request, so the history of the service’s speed is written down.
It is also worth being realistic about what these numbers describe. With a model this small, the prediction itself is unlikely to be the slowest part of a request. Parsing JSON, validating fields, and building a DataFrame probably account for much of the time. Profile before you optimize, because the slow part is often not where you expect it, and a heavier model will shift the balance.
Run the benchmark more than once before you trust it. On the test machine, the first run reported the median of 3.40 ms shown above, while later runs with the final version of the service reported medians between 2.39 and 2.60 ms. The first run after a fresh start is often the slowest, and background activity on the machine adds noise. The practical rule is to compare numbers produced by the same procedure on the same machine, and to repeat each measurement a few times so one unlucky run doesn’t mislead you.
A service that is tested and measured still needs to run the same way everywhere. That is what a container is for.
Save the following as Dockerfile:
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .RUN pip install --no-cache-dir -r requirements.txt
COPY app.py .COPY artifacts/ artifacts/
EXPOSE 8000CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000"]
Build and run it, tagging the image with a version that matches your release:
docker build -t churn-service:1.0.0 .docker run --rm -p 8000:8000 churn-service:1.0.0
Then confirm the container responds:
curl -s localhost:8000/health
The Dockerfile follows a few habits worth keeping:
The point of the container is repeatability. Because the image includes the code, the pinned dependencies, and the artifact, the same image behaves the same way on your laptop, in staging, and in production. Tagging every image with a version number also means you can always say exactly what is running, which is the first question anyone asks during an incident.
In a larger project, move pytest and httpx into a separate requirements-dev.txt so the production image stays lean.
Before sending an image to production, consider three small upgrades. Run the process as a non-root user so a compromise inside the container has fewer privileges. Add a .dockerignore file so local virtual environments and caches never enter the build context. Add a container health check that calls /health, so the platform can restart an instance that failed to load its model. None of these change the model, but each removes a common source of avoidable incidents.
The pieces are now in place. What turns them into a process is deciding in advance what must be true before you release.
A checklist is the difference between “I deployed it once” and “anyone on the team can deploy it safely”. Use this one as a starting point and adjust the thresholds to your project.
Before release
During release
After release
The checklist also acts as documentation. A new teammate can read it and understand what “ready to ship” means in your team without asking anyone.
A checklist only works if someone owns it. Assign each release to one person, let that person tick the boxes, and treat any unticked item as a reason to . As your process matures, you can automate the mechanical items, such as running the tests and the benchmark, while keeping the judgment items, such as whether a metric change is acceptable, with a human.
A checklist depends on people remembering to follow it, and people forget under deadline pressure. The mechanical items on your list, such as training from a clean environment and running the tests, are good candidates for automation. A continuous integration (CI) pipeline runs them for you on every change and reports the result next to the code.
If your project is hosted on GitHub, you can describe the pipeline in a workflow file. Save the following as .github/workflows/ci.yml:
name: ci
on: push: pull_request:
jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-python@v5 with: python-version: "3.12" cache: pip - run: pip install -r requirements.txt - run: python train.py - run: pytest -q
The workflow checks out your code, installs Python 3.12, and installs the pinned requirements. It then runs train.py before the tests, which creates a fresh artifact in a clean environment. That order matters for two reasons. It proves the training script still works without leftover files on your laptop, and it gives the artifact tests a real model to verify. The Python version matches the base image in the Dockerfile, so the pipeline tests the same interpreter you ship.
The next question is which results should stop a change from reaching production. Failing tests should always block it, because they describe behavior you decided to protect. You can enforce that by marking the pipeline as a required check on your main branch, so nobody can merge while it is red.
A metric floor is a useful second gate. You could add a test that reads metadata.json and fails if test_auc drops below a value your team agreed on. That turns the checklist item about not shipping a worse model into something that can't be skipped by accident.
Other items are better left out of the pipeline. Shared CI machines have unpredictable load, so a latency benchmark run there produces noisy numbers that would cause false failures. Run the benchmark on a stable machine and record the result in the release notes instead. The judgment calls, such as whether a small metric drop is acceptable for a faster model, should stay with a person. Automation is there to remove forgetting from the process, not to remove thinking.
Shipping the service is not the end of the work. This section covers what to do when a release goes wrong and how to notice problems before your users do. You’ll start with a rollback plan, then decide what to monitor, and finally build a simple check that detects when live data stops resembling the training data.
Releases fail. The question is how long a failure lasts. Because the artifact is baked into the image, rollback is a single step: redeploy the previous image tag. There is no separate model file to track down and match with code.
A safer pattern than switching everything at once is to run the new version beside the old one and move traffic gradually. If you send a small share of requests to the new image first, you can compare error rates and latency against the old one while most users are still protected. Whether you do this with a load balancer, a platform feature, or a simple manual switch depends on your setup, but the principle is the same: limit how many users a bad release can reach.
Once the service is live, monitor four things:
You can’t compute AUC in production until the true outcomes arrive. For churn, that could be weeks. Plan how those labels will flow back so you can evaluate the model on real results.
Input drift can’t be measured without a record of what the service received. The simplest option is to write one JSON line per request. Add import json, from datetime import datetime, timezone, and a LOG_PATH setting next to ARTIFACT_DIR in app.py, then add this function:
LOG_PATH = Path(os.getenv("PREDICTION_LOG", "predictions.jsonl"))
php
def log_prediction(features: dict, probability: float) -> None: record = { "ts": datetime.now(timezone.utc).isoformat(), "features": features, "churn_probability": probability, } with LOG_PATH.open("a") as f: f.write(json.dumps(record) + "\n")
Then update the predict function so it logs every prediction before returning:
@app.post("/predict", response_model=Prediction)def predict(customer: Customer): features = customer.model_dump() row = pd.DataFrame([features])[state["meta"]["features"]] proba = round(float(state["model"].predict_proba(row)[0, 1]), 4) log_prediction(features, proba) return Prediction(churn_probability=proba, model_auc=state["meta"]["test_auc"])
Each request now adds one line like this to predictions.jsonl:
{"ts": "2026-11-28T16:09:29.089278+00:00", "features": {"tenure_months": 11, "monthly_charges": 75.9749107501694, "support_tickets": 1, "late_payments": 0}, "churn_probability": 0.6263}
Three practical points apply here. First, the log contains the data your clients send, so decide who can read it and how long you keep it before you log anything personal. The features in this example are numeric and anonymous, but real projects often aren’t. Second, a file append is fine for a single process, but several worker processes writing to one file can interleave lines. In a container, it is more common to write each record to standard output and let the platform collect it. Third, add predictions.jsonl to your .gitignore, because the test suite writes to it too.
Logging adds work to every request, so it is worth measuring. The benchmark was run three times with the log pointed at /dev/null, which discards writes, and three times with a real file. The medians were 2.42, 2.57, and 2.46 ms without a real write, and 2.60, 2.39, and 2.46 ms with one. At this traffic level the difference disappears into run-to-run noise.
With the log in place, you can ask a simple question: do the requests arriving now look like the data the model was trained on? Save the following as drift.py. It reuses make_data from train.py to rebuild the training features, so the baseline needs no extra file:
import jsonimport mathimport sysfrom pathlib import Path
python
import pandas as pdfrom train import FEATURES, make_datadef load_live(path): lines = Path(path).read_text().splitlines() rows = [json.loads(line)["features"] for line in lines] return pd.DataFrame(rows)[FEATURES]def main(path="predictions.jsonl", threshold=3.0): baseline = make_data()[FEATURES] live = load_live(path) n = len(live) print(f"Comparing {n} logged requests against the training data\n") for feature in FEATURES: train_mean = baseline[feature].mean() live_mean = live[feature].mean() std_error = baseline[feature].std() / math.sqrt(n) z = (live_mean - train_mean) / std_error status = "DRIFT" if abs(z) > threshold else "ok" print( f"{feature:16} train={train_mean:7.2f} " f"live={live_mean:7.2f} z={z:+6.1f} {status}" )if __name__ == "__main__": main(*sys.argv[1:2])
For each feature, the script measures how far the live average has moved from the training average, expressed in standard errors. That value is the z column. A value near zero means the live data looks like the training data, and a large positive or negative value means the average has moved further than random sampling would explain. The threshold of 3 is a common convention, not a law, so adjust it to how many false alarms your team can tolerate.
To see it work, you need traffic. Save this small script as sim_traffic.py. It sends 300 requests, and the shifted option mimics a sudden wave of new customers by limiting tenure to under a year:
import sys
python
import httpximport numpy as npURL = "http://127.0.0.1:8000/predict"N = 300def customers(shifted, seed): rng = np.random.default_rng(seed) low, high = (1, 12) if shifted else (1, 72) for _ in range(N): yield { "tenure_months": int(rng.integers(low, high)), "monthly_charges": float(np.clip(rng.normal(70, 20), 15, 150)), "support_tickets": int(rng.poisson(1.5)), "late_payments": int(rng.poisson(0.5)), }if __name__ == "__main__": shifted = len(sys.argv) > 1 and sys.argv[1] == "shifted" with httpx.Client() as client: for payload in customers(shifted, seed=7): client.post(URL, json=payload) print(f"sent {N} {'shifted' if shifted else 'normal'} requests")
Start the service with an empty log, send normal traffic, and run the check:
python sim_traffic.py normalpython drift.py
Comparing 300 logged requests against the training data
tenure_months train= 35.91 live= 37.72 z= +1.5 okmonthly_charges train= 70.31 live= 68.13 z= -1.9 oksupport_tickets train= 1.52 live= 1.49 z= -0.4 oklate_payments train= 0.50 live= 0.49 z= -0.2 ok
Now delete predictions.jsonl, restart the service, and repeat the experiment with shifted traffic:
python sim_traffic.py shiftedpython drift.py
Comparing 300 logged requests against the training data
tenure_months train= 35.91 live= 6.24 z= -25.0 DRIFTmonthly_charges train= 70.31 live= 68.13 z= -1.9 oksupport_tickets train= 1.52 live= 1.49 z= -0.4 oklate_payments train= 0.50 live= 0.49 z= -0.2 ok
The second run is the important one. Every request in it was valid, every prediction succeeded, and no error appeared anywhere, yet the check flags tenure_months immediately. This is the kind of problem that tests and health checks can't catch, because the service is working exactly as designed on data it was never prepared for.
This check is a screen, not a full monitoring system, and its limits are worth stating. It compares averages only, so it can miss a change in the shape of a distribution when the mean stays put. It assumes you have enough requests for the average to be stable, and with very large samples it will flag tiny shifts that don’t matter in practice. When you outgrow it, look at distribution-level methods such as the Kolmogorov-Smirnov test or the population stability index. The habit it teaches is the part to keep: write down what the model expects, record what it receives, and compare the two on a schedule.
Monitoring is where the process loops back to the start. Drift in the input features and a shift in the prediction distribution are early warnings that the world has changed since training, and they are the usual trigger for the next retrain. When that happens, you don’t improvise. You go back to the training script, produce a new versioned artifact, and walk through the same checklist again.
This process is a solid foundation, but it has limits you should know about:
Shipping an ML service is mostly a process problem, not a modeling problem. A model that can’t be reproduced, tested, measured, and rolled back is a risk, no matter how good its metrics are.
The common thread is that every step turns something implicit into something explicit. The input format becomes a schema, the environment becomes a pinned file, the quality bar becomes a test, the speed becomes a number, and the release becomes a checklist. That explicitness is what lets a team trust a model, and it also makes the work easy to explain to someone who wasn’t there when it was built.
In this tutorial, you’ve learned how to:
From here, you could automate the checklist with a CI pipeline, add authentication, or compare a heavier model against this baseline using the same benchmark.
From Notebook to Production: A Step-by-Step Process for Shipping an ML Service was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.