Deploying & Serving ML Models
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
A model that scores well in a notebook has delivered nothing until other software can call it reliably. Deployment is the work of turning a trained artifact into a service or a scheduled job with defined inputs, outputs, latency, versions and monitoring. The model is usually a small fraction of the code in such a system; the rest is data handling, packaging, serving, release and observation, which the Google paper "Hidden Technical Debt in Machine Learning Systems" (Sculley et al., 2015) described as the main source of maintenance cost.
The facts below were checked on 2026-10-30 against Python 3.13, PyTorch 2.15, TensorFlow 2.21 with Keras 3.15 and scikit-learn 1.9. The Python examples were run on Python 3.13 with scikit-learn 1.9, PyTorch 2.15 (CPU), Keras 3.15 on TensorFlow 2.21, ONNX Runtime 1.31 and FastAPI on 2026-11-01. The sibling pages are ONNX & Model Interoperability for portable formats, Experiment Tracking & MLOps for Training for registries and pipelines, and Model Compression for making a model fit a latency or memory budget. Large language models have their own serving concerns, covered in Serving at Scale and Deployment and Release Patterns.
Decide the serving mode first
| Mode | What it is | Typical fit |
|---|---|---|
Batch (offline) |
A scheduled job reads many rows, scores them and writes the results to a table or file. |
Nightly recommendations, risk scores, churn lists. Latency is minutes to hours; throughput and cost matter. |
Online (real-time) |
A service answers one request, or a small group of requests, within milliseconds to seconds. |
Fraud checks at payment time, search ranking, image classification behind an API. |
Streaming |
A consumer scores events from a queue as they arrive, often with stateful features. |
Sensor data, clickstreams, anomaly detection. |
Embedded (on-device) |
The model runs inside a phone, browser or microcontroller application. |
Offline use, privacy, very low latency. See ONNX & Model Interoperability for ExecuTorch and LiteRT. |
Batch is the simplest and cheapest option, and many "real-time" requirements disappear when the answer can be computed the night before and looked up. Choose online serving only when the prediction depends on information that exists at request time.
Saving and loading models safely
The file format decides what an attacker or an upgrade can break. The central rule: a pickle-based file can execute code when loaded, so load only files you produced or can verify.
scikit-learn
Scikit-learn estimators are saved with joblib.dump and joblib.load (pickle underneath), which is efficient for NumPy arrays. Two limitations apply: the file is only guaranteed to load with the same scikit-learn, NumPy and Python versions that wrote it (there is no supported way to load a model trained with another scikit-learn version), and loading executes arbitrary code. The skops library offers a safer persistence format with an explicit list of trusted types. The full discussion is in Model Persistence.
import joblib
from sklearn.datasets import load_iris
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_iris(return_X_y=True)
pipe = make_pipeline(StandardScaler(), HistGradientBoostingClassifier(random_state=0)).fit(X, y)
joblib.dump(pipe, "model.joblib", compress=3)
# in the serving process (same pinned environment):
loaded = joblib.load("model.joblib")
print(loaded.predict(X[:3]))
Save the whole pipeline, never only the final estimator: the preprocessing is part of the model. Record the library versions beside the file (the registry in Experiment Tracking & MLOps for Training does this for you).
PyTorch
Save the state_dict (weights) and rebuild the architecture in code. torch.load uses weights_only=True by default since PyTorch 2.6, which restricts unpickling to tensors, primitive types and registered classes. Old code that pickled an entire model with torch.save(model, path) and read it with torch.load(path) now fails. Custom classes must be allowed explicitly with torch.serialization.add_safe_globals or the safe_globals context manager; the environment variable TORCH_FORCE_NO_WEIGHTS_ONLY_LOAD=1 turns the protection off and belongs only in the loading of files you fully trust. Nested tensors left the default allowlist in PyTorch 2.15.
import torch
from torch import nn
model = nn.Sequential(nn.Linear(16, 32), nn.ReLU(), nn.Linear(32, 3))
# save: weights only, plus the metadata needed to rebuild
torch.save({"state_dict": model.state_dict(), "config": {"in": 16, "hidden": 32, "out": 3}}, "model.pt")
# load: map to CPU in the serving process, weights_only is already the default
checkpoint = torch.load("model.pt", map_location="cpu", weights_only=True)
restored = nn.Sequential(nn.Linear(16, 32), nn.ReLU(), nn.Linear(32, 3))
restored.load_state_dict(checkpoint["state_dict"])
restored.eval()
The safetensors format stores only tensors and cannot contain code, which is why the Hugging Face Hub prefers it; PyTorch 2.13 added native loading of safetensors. See Model Formats for the comparison. Whole training checkpoints (optimizer, scheduler, random state) belong to training and are described in Training Deep Networks.
TorchScript (torch.jit.script, torch.jit.trace and torch.jit.save) is deprecated since PyTorch 2.10. For production use torch.export together with ONNX or ExecuTorch (see ONNX & Model Interoperability), or serve the eager nn.Module with torch.compile. TorchServe, the PyTorch project’s model server, was archived on 2025-08-07 and receives no security patches, so do not start a new deployment on it; guides that begin with torch-model-archiver describe a retired path. Maintained alternatives are a plain FastAPI or Ray Serve service, Triton Inference Server, KServe, BentoML, and engine-specific servers such as vLLM for language models.
Keras 3 and TensorFlow
Keras 3 separates saving for Keras from exporting for inference.
-
model.save("m.keras")writes the.kerasarchive andkeras.saving.load_model("m.keras")restores the architecture, weights, optimizer and compile state. Custom layers need@keras.saving.register_keras_serializable()and aget_config. Loading runs in safe mode by default, which refuses to deserialise arbitrary lambda code. -
model.save_weights("m.weights.h5")requires the.weights.h5suffix, and the legacy.h5full-model format still loads but is not recommended. -
model.export("saved_model_dir")writes a TensorFlow SavedModel for inference and serving. A SavedModel cannot be read back withkeras.saving.load_model; usekeras.layers.TFSMLayer(inference only) ortf.saved_model.load.
import keras
import numpy as np
model = keras.Sequential(
[keras.Input(shape=(16,)), keras.layers.Dense(32, activation="relu"), keras.layers.Dense(3)]
)
model.compile(optimizer="adam", loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True))
model.fit(np.random.rand(128, 16).astype("float32"), np.random.randint(0, 3, 128), epochs=1, verbose=0)
model.save("classifier.keras") # for later Keras use
model.export("serving/classifier/1") # SavedModel: <name>/<version>/ for TensorFlow Serving
reloaded = keras.layers.TFSMLayer("serving/classifier/1", call_endpoint="serve")
print(reloaded(np.random.rand(2, 16).astype("float32")))
A FastAPI service with ONNX Runtime
For a single model behind an HTTP API, a small FastAPI application is often enough. The rules that matter are shown below: load the model once at start-up, not per request; keep the endpoint’s contract in Pydantic models; and run CPU-bound inference outside the event loop. The server-side mechanics (lifespan, thread pools, worker processes, testing without a model) are described in Serving Data Science & AI with FastAPI, with background in Settings, Lifespan & Background Tasks, Async & Concurrency and Deployment.
from contextlib import asynccontextmanager
import numpy as np
import onnxruntime as ort
from fastapi import FastAPI
from fastapi.concurrency import run_in_threadpool
from pydantic import BaseModel, Field
state: dict[str, ort.InferenceSession] = {}
@asynccontextmanager
async def lifespan(app: FastAPI):
state["session"] = ort.InferenceSession("classifier.onnx", providers=["CPUExecutionProvider"])
yield
state.clear()
app = FastAPI(lifespan=lifespan)
class Features(BaseModel):
values: list[float] = Field(min_length=16, max_length=16)
class Prediction(BaseModel):
label: int
scores: list[float]
def run_model(values: list[float]) -> Prediction:
x = np.asarray([values], dtype=np.float32)
(logits,) = state["session"].run(["logits"], {"features": x})
return Prediction(label=int(logits.argmax(axis=1)[0]), scores=logits[0].tolist())
@app.post("/predict", response_model=Prediction)
async def predict(body: Features) -> Prediction:
return await run_in_threadpool(run_model, body.values)
@app.get("/healthz")
async def healthz() -> dict[str, str]:
return {"status": "ok" if "session" in state else "loading"}
The service expects a classifier.onnx file whose input is named features (shape [batch, 16]) and whose output is named logits; ONNX & Model Interoperability shows how to export one with those names.
Run it with fastapi run or uvicorn app:app (see the deployment page above). ONNX Runtime releases the Python global interpreter lock while it runs, so a thread pool gives real concurrency on one worker. To scale CPU-bound inference further, add worker processes or replicas rather than larger thread pools, and set the intra-op thread count (SessionOptions.intra_op_num_threads) so that all workers together do not over-subscribe the cores.
Dynamic batching
Accelerators are efficient on batches. An online service sees single requests, so servers batch dynamically: they hold requests for a few milliseconds, concatenate the inputs, run one forward pass and split the outputs. Triton Inference Server and TensorFlow Serving implement this natively with a maximum batch size and a maximum queue delay; a hand-written FastAPI service can do it with an asyncio.Queue and a background task. The trade-off is explicit: the queue delay is added to every request’s latency in exchange for higher throughput. Measure p50, p95 and p99 latency under realistic concurrent load, never only the average of a single request.
TensorFlow Serving
TensorFlow Serving loads SavedModels from a directory whose subdirectories are integer versions and always serves the highest version, hot-swapping new ones without a restart. Export a Keras model into serving/classifier/1 as shown earlier, then run the official Docker image.
docker run --rm -p 8501:8501 -p 8500:8500 \
--mount type=bind,source="$(pwd)/serving/classifier",target=/models/classifier \
-e MODEL_NAME=classifier \
tensorflow/serving:2.21.0
curl -s -X POST http://localhost:8501/v1/models/classifier:predict \
-H "Content-Type: application/json" \
-d '{"instances": [[0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6]]}'
Source: TensorFlow Serving with Docker
These commands need a running Docker engine and were not executed for this page. Port 8501 serves the REST API and port 8500 gRPC, which is faster for large payloads. Pin the image tag to the version you tested, and compare with saved_model_cli show --dir serving/classifier/1 --all to see the exact signatures the server exposes. TensorFlow Serving is part of the TFX ecosystem, which TensorFlow continues to maintain (see the 2026 TensorFlow maintenance policy in the TensorFlow sub-section).
Packaging into a container
The artifact, the code and the pinned dependencies travel together as an image. The general container material is in Docker Getting Started and, for a FastAPI service, in FastAPI with Docker and Kubernetes.
FROM python:3.13-slim
WORKDIR /app
COPY requirements.lock .
RUN pip install --no-cache-dir -r requirements.lock
COPY app.py classifier.onnx ./
USER 10001
EXPOSE 8000
HEALTHCHECK CMD ["python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8000/healthz')"]
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000"]
Source: Dockerfile reference
Practical rules: bake in the model for small files and pull large weights from an artifact store at start-up (fetch with checksum verification); keep GPU images on the CUDA base images that match the framework build; give the container CPU and memory limits and make the thread counts of NumPy, ONNX Runtime and PyTorch follow them; and prefer a lock file over pip install torch so that rebuilds stay identical.
Release patterns and rollback
A new model version is a code change with unpredictable behaviour, so release it the same careful way:
-
Shadow deployment: the new model receives a copy of live traffic and its predictions are logged but not returned. This checks latency, errors and agreement with the incumbent at no user risk.
-
Canary release: send a small percentage of traffic to the new version, watch error rates, latency and business metrics, then widen.
-
A/B test: split users randomly and compare outcome metrics with proper statistics. Needed when "better offline" does not prove "better for users".
-
Blue-green: run both versions, switch the router, keep the old one for instant rollback.
-
Rollback: version every artifact and keep the previous one ready. Registry aliases such as
championmake a rollback a single pointer change.
These patterns, including the LLM-specific ones, are developed in Deployment and Release Patterns; KServe and Kubernetes details for the serving tier are in Serving at Scale.
Training-serving skew
The most frequent production bug is a model that behaves differently from its evaluation because the features differ. Typical causes:
-
Preprocessing written twice, once in the training notebook and once in the service, with a subtle difference (rounding, category order, time zone, missing-value handling).
-
Features computed from the whole table in training (an average over all rows) but from a stream in production.
-
Time leakage: a training feature that was not yet available at prediction time (see Model Evaluation & Validation).
-
Different library versions between training and serving.
Defences: ship preprocessing inside the artifact (a scikit-learn Pipeline, an ONNX graph that includes it, Keras preprocessing layers, or a PyTorch module that takes raw tensors); compute features with the same code path in both places, ideally through a feature store; log the exact features the model received so predictions can be replayed; and test the served endpoint against a fixed set of golden inputs and expected outputs in CI.
Operating a model
A deployed model degrades silently. Plan for:
-
Service health: request rate, error rate, latency percentiles, saturation of CPU, memory and GPU, queue length. The metrics and alerting practices in Metrics, Dashboards & Alerting and Observability with OpenTelemetry apply to any service, and Performance & Observability shows the FastAPI side.
-
Data drift: the distribution of inputs moves away from the training data. Compare live feature statistics with a reference (population stability index, Kolmogorov-Smirnov test, or a drift detector).
-
Concept drift and label delay: the relationship between inputs and outcomes changes. True labels often arrive days or weeks late, so track proxies and compute the real metric as labels arrive. See Drift and Regression Monitoring.
-
Retraining triggers: scheduled, drift-triggered or performance-triggered, always through the same tested pipeline that produced the first model (see Experiment Tracking & MLOps for Training).
-
Governance: a model card or equivalent record of intended use, data, metrics and limitations; see Fairness & Responsible ML and Operational Governance.
Google’s "Production ML systems" course material and "Rules of Machine Learning" recommend starting with a simple model and a solid pipeline, and treating the infrastructure (data collection, serving, monitoring) as the product.
Pitfalls
-
Loading an untrusted pickle,
joblibortorch.loadfile. It can run code. Useweights_only=True, safetensors, ONNX, orskopswith a trusted-type list. -
Rebuilding the model per request. Load once at start-up; check it in the health endpoint.
-
Blocking the event loop. CPU-bound inference in an
async defhandler freezes every request; use a thread pool, a worker process or a separate inference server. -
Unpinned environments. A scikit-learn or framework upgrade can break loading or change predictions. Pin and test.
-
Starting on a retired stack. TorchServe is archived; TorchScript is deprecated; Keras 2 SavedModel snippets (
model.save("dir")) no longer apply to Keras 3. -
No rollback path. Keep the previous version deployed and addressable.
-
Optimising the model before measuring the service. Often the bottleneck is serialisation, preprocessing or network hops.
-
Averages instead of percentiles. Users experience the tail.