Level 3 In-Depth AI · ML Engineering and Production
Deploying Models
How a trained model leaves your laptop and starts doing useful work. Saving it, wrapping it in a web API with FastAPI, packaging it in a container, choosing between batch and online inference, measuring latency, and rolling out safely.
- Level
- ●●●●● Easy
- Reading
- 11 min
- To learn it well
- 1 hour to read, an afternoon to practise
- Builds on
- 6 concepts →
- Quiz
- 5 questions ↓
The full path from zero — 6 concepts before this one
- What Is AI?
- Python for AI
- How Machines Learn
- Supervised, Unsupervised and Reinforcement Learning
- Supervised Learning
- The ML Project Lifecycle
- Deploying Models
Read them roughly in this order. See it on the concept map →
Why it matters
A model in a notebook helps nobody. It starts creating value only when other software can ask it questions and act on the answers: a checkout page asking "is this payment fraud?", a nightly job scoring every customer for churn, a phone app recognising a plant. Deployment is the work of getting the model from the training environment into that position, reliably, quickly enough, and in a way you can update and roll back.
Deployment is where many projects stall (The ML Project Lifecycle). The skills involved are closer to software engineering than to statistics: saving files, writing web services, packaging dependencies, measuring speed. They are not hard, and this chapter walks through a complete, working example. The same patterns, scaled up, serve large language models (Serving LLMs at Scale).
The intuition
Think of a professional kitchen. A chef develops a recipe in the test kitchen (training). To sell it, the restaurant needs three things. A written recipe card that any cook can follow (the saved model file). A serving hatch where waiters hand in orders and collect plates (the API). And a standard kitchen layout so the same dish comes out the same in every branch (the container).
Restaurants also serve in different ways. A banquet hall cooks 500 identical meals in advance (batch). An à-la-carte restaurant cooks each order as it arrives, and every minute of waiting matters (online). A food truck takes the kitchen to the customer (edge). ML deployment comes in the same three shapes:
Key idea Use batch inference whenever predictions can be computed in advance: it is simpler, cheaper and easier to monitor. Use an online API only when the input is not known until the moment of the request, and then measure tail latency, not just the average.
How it works
Step 1: save the model
Training produces a model object in memory. Model serialization writes it to a file that another process can load. Common formats:
- pickle / joblib for scikit-learn. One line each way. But unpickling a file can run arbitrary code, so never load a pickle from a source you don't trust. Pickles also tend to break across library versions, so record the versions (Experiment Tracking and Reproducibility).
- PyTorch state dict (
torch.save(model.state_dict(), ...)): just the weights. You need the model's Python class to rebuild it. - safetensors: a simple, safe format for tensors only, with no code execution. It is now the default for weights on the Hugging Face Hub.
- ONNX (Open Neural Network Exchange): stores the computation graph and weights in a framework-neutral format. ONNX Runtime can then run it fast on servers, phones or browsers without PyTorch installed.
Save the preprocessing with the model. In scikit-learn, put the scaler and the model in one Pipeline and save that. If you save only the model, someone will re-implement the preprocessing slightly differently in production. That is training–serving skew.
Step 2: wrap it in an API
An inference endpoint is a URL that accepts input and returns predictions, usually as JSON over HTTP. FastAPI is the most popular Python framework for this. You write ordinary functions, and FastAPI turns them into web endpoints. Combined with Pydantic, it validates every request against a schema: a request with a missing field or a negative petal length gets a clear error (status 422) instead of a nonsense prediction.
Three rules for the service:
- Load the model once at start-up, not per request. Loading can take seconds.
- Accept lists of inputs, so callers can send a batch in one request.
- Expose a health endpoint that reports the model version, so load balancers and humans can check what is running.
Step 3: package it in a container
The service needs the right Python version, the right library versions and the model file. A container bundles all of that into one image that runs the same on a laptop, a server or a cloud platform. Docker is the standard tool. A minimal Dockerfile for the app below:
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY app.py model.joblib ./
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000"]
docker build -t iris-api . builds the image, and docker run -p 8000:8000 iris-api starts it. Cloud platforms run many copies of the container behind a load balancer, and an orchestrator such as Kubernetes adds or removes copies as traffic changes (autoscaling).
Batch, online or edge?
- Batch inference scores many records on a schedule (hourly, nightly) and stores the results. The application just looks up a precomputed answer. It is cheap (it can use big batches and spare machines), simple to retry, and easy to check before anyone sees the output. The cost is freshness: predictions are as old as the last run, and you must score every record even if few are ever looked up.
- Online inference computes a prediction when a request arrives, using information only available then: the contents of a basket, the text just typed. It needs a service that is always up and fast enough.
- Edge deployment runs the model on the user's device. There is no network round trip, it works offline, and private data never leaves the device. The model must be small, which is where Quantization and Knowledge Distillation and Small Models come in.
A related pattern is streaming: predictions computed on events as they flow through a message queue, a middle ground between batch and online.
Latency and throughput
Two numbers describe a service's speed:
- Latency: how long one request takes, from sending to receiving the answer.
- Throughput: how many predictions per second the service handles.
They pull against each other. Grouping requests into batches raises throughput, because the hardware does many predictions at once, but each request may wait for its batch to fill. In the example below, one request for one flower takes about 3 ms, while one request for 1,000 flowers takes about 13 ms: more than 200 times as many flowers per second.
Averages hide the pain. Users notice the slow requests, so services are measured by percentiles: p50 (the median), p95 and p99 (the time within which 95% or 99% of requests finish). The slow end is called tail latency. A page that calls ten services, each with a 1-in-100 chance of being slow, will be slow for about 1 in 10 page loads ().
A typical latency budget for an interactive feature is a few hundred milliseconds end to end, and the model's share is often tens of milliseconds. When that is too tight: use a smaller model, quantize it, run it on a GPU, cache frequent answers, or move work into a batch job.
Rolling out safely
A new model version is a risky change. Standard ways to limit the damage:
- Shadow deployment: the new model receives a copy of real traffic and its predictions are logged, but not used. You compare it with the current model on real inputs with zero risk to users.
- Canary release: send a small share of traffic (say 1–5%) to the new model and watch error rates and business metrics before increasing it.
- A/B test: split users randomly between old and new for long enough to measure a business difference with statistical confidence.
- Rollback: always keep the previous version ready, and make switching back one command. A model registry makes "serve version 6 again" easy.
After launch, Monitoring and Data Drift takes over.
In code
Three small files. First, train and save a model with its preprocessing (train.py):
import joblib
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_iris(return_X_y=True)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)).fit(X, y)
joblib.dump({"model": model, "classes": ["setosa", "versicolor", "virginica"],
"version": "iris-2025-01"}, "model.joblib")
Then the service (app.py, needs pip install fastapi uvicorn). Run it with uvicorn app:app and open http://127.0.0.1:8000/docs for automatic interactive documentation.
import joblib
from fastapi import FastAPI
from pydantic import BaseModel, Field
bundle = joblib.load("model.joblib") # load once, at start-up
app = FastAPI(title="iris classifier")
class Flower(BaseModel): # validates every request
sepal_length: float = Field(gt=0, lt=20)
sepal_width: float = Field(gt=0, lt=20)
petal_length: float = Field(gt=0, lt=20)
petal_width: float = Field(gt=0, lt=20)
@app.get("/health")
def health():
return {"status": "ok", "model_version": bundle["version"]}
@app.post("/predict")
def predict(flowers: list[Flower]):
X = [[f.sepal_length, f.sepal_width, f.petal_length, f.petal_width] for f in flowers]
probs = bundle["model"].predict_proba(X)
return [{"label": bundle["classes"][p.argmax()], "confidence": round(float(p.max()), 3)}
for p in probs]
Finally, a test that calls the service without starting a server, using FastAPI's TestClient (which needs pip install httpx). Put tests like this in your CI so a broken model never ships:
import time
import numpy as np
from fastapi.testclient import TestClient
from app import app
client = TestClient(app)
print(client.get("/health").json())
r = client.post("/predict", json=[{"sepal_length": 5.1, "sepal_width": 3.5,
"petal_length": 1.4, "petal_width": 0.2}])
print(r.status_code, r.json())
bad = client.post("/predict", json=[{"sepal_length": -1, "sepal_width": 3.5,
"petal_length": 1.4, "petal_width": 0.2}])
print(bad.status_code, bad.json()["detail"][0]["msg"])
times = []
for _ in range(500):
t = time.perf_counter()
client.post("/predict", json=[{"sepal_length": 6.0, "sepal_width": 2.9,
"petal_length": 4.5, "petal_width": 1.5}])
times.append((time.perf_counter() - t) * 1000)
print("latency ms p50 %.2f p95 %.2f p99 %.2f" % tuple(np.percentile(times, [50, 95, 99])))
batch = [{"sepal_length": 6.0, "sepal_width": 2.9, "petal_length": 4.5, "petal_width": 1.5}] * 1000
t = time.perf_counter(); client.post("/predict", json=batch)
print("1,000 flowers in one request: %.1f ms" % ((time.perf_counter() - t) * 1000))
# {'status': 'ok', 'model_version': 'iris-2025-01'}
# 200 [{'label': 'setosa', 'confidence': 0.985}]
# 422 Input should be greater than 0
# latency ms p50 2.98 p95 3.75 p99 5.30
# 1,000 flowers in one request: 13.1 ms
The timings are from a laptop and exclude the network, so real numbers will be higher. The ratio between one-at-a-time and batched requests is the point.
Common pitfalls
- Preprocessing drift. Training scaled the inputs, but the service doesn't, or does it with different statistics. Save the whole pipeline as one object.
- Loading the model per request. Latency jumps from milliseconds to seconds. Load at start-up.
- No input validation. A missing field becomes
NaN, and the model returns a confident wrong answer. Validate with a schema and reject bad input with a clear error. - Library version mismatch. A model pickled with one scikit-learn version may fail or silently change behaviour in another. Pin versions in
requirements.txtand build the container from them. - Measuring only the average latency. The p99 is what users complain about. Load-test with realistic traffic before launch.
- No way back. Deploying by overwriting the old model file means a bad release can't be undone quickly. Version models and keep the previous one deployable.
Watch out Never
pickle.loadorjoblib.loada file from an untrusted source: loading it can run any code its author chose. Prefer safetensors or ONNX for models you download, and treat model files like executable programs.
Where it leads
- Monitoring and Data Drift: what to watch once the model is live.
- Serving LLMs at Scale: deploying large language models, where GPU memory, batching and the KV cache dominate.
- Quantization and Knowledge Distillation and Small Models: making models small and fast enough for tight latency budgets and edge devices.
- Running Models Locally: the LLM version of edge deployment.
- Building AI Products: product decisions around a deployed model.
A bit of history
For years, deploying a model often meant rewriting it: data scientists prototyped in R or Python, and engineers re-implemented the model in Java or C++ for production. Better tools gradually removed that step. Google released TensorFlow Serving in 2016 for serving models at scale. Microsoft and Facebook launched ONNX in 2017 to move models between frameworks. Docker (2013) and Kubernetes (2014) made packaging and scaling any service routine, and in 2017 Uber described Michelangelo, an internal platform covering the whole loop from data to deployment, which inspired many similar platforms. FastAPI, released in 2018, made a typed, validated Python API a few lines of code. Today the same ideas run at enormous scale behind every large language model API.
Try it
- Run the three files. Then send a request with a missing field (drop
petal_width). What status code and message do you get?- Add a
/predict_batch_csvendpoint, or a batch script that reads a CSV of flowers and writes a CSV of predictions. Which would you choose for scoring 10 million rows a night?- Measure p50 and p99 for batches of 1, 10, 100 and 1,000 flowers per request. Plot milliseconds per flower against batch size.
Hint for 3: per-request overhead (HTTP parsing, validation, Python function calls) is shared by every item in the batch, so the cost per flower falls quickly and then levels off.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
FastAPI documentation and tutorial
A clear, step-by-step tutorial for the most popular Python web API framework, including request validation, testing and deployment.
Made With ML
How to design, develop, deploy and iterate on ML systems in production.
Designing Machine Learning Systems
The practical guide to data, features, deployment, monitoring and iteration in production ML.
FastAPI in Containers - Docker
How to write a Dockerfile for a FastAPI service, with explanations of each line and of replication in production.
ONNX (Open Neural Network Exchange)
An open format for trained models, so a model exported from PyTorch or scikit-learn can run with ONNX Runtime on servers, phones and browsers.
Saving and Loading Models
The official guide to state dicts, checkpoints and loading models for inference in PyTorch.
Full Stack Deep Learning
Lectures on taking deep learning and LLM projects from idea to production.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/mlops/model-deployment.md