Sub topic 12
Deploying and serving models
This chapter assumes you can train and evaluate a supervised model in Python and know roughly how a web service is deployed. It covers the main ways to put a registered model in front of users, how to roll out a new version safely, and the errors that most often cause trouble.
What deploying a model means
Deploying a model means packaging a specific registered version so that other systems can get predictions from it. Serving is the runtime part: loading the model, receiving inputs, running inference, and returning outputs.
A deployed model is more than a weights file. It also needs:
- The preprocessing and feature logic that was used at training time.
- A pinned runtime environment (library versions, Python version, system packages).
- A defined input and output schema.
- Resource settings such as CPU, memory, and optionally a GPU.
The model comes from the registry, the step before this one. The registry entry says which version to deploy. The deployment step is what turns that version into a running service or a scheduled job.
Choosing a serving pattern
Three patterns cover most cases. The deciding factor is how quickly a prediction must be available after the input arrives.
| Pattern | When predictions are produced | Typical use | Main cost |
|---|---|---|---|
| Batch | On a schedule, for many rows at once | Nightly churn scores, weekly recommendations | Predictions can be hours old |
| Online (real-time) | On request, in milliseconds to seconds | Fraud checks, search ranking | Always-on infrastructure and latency limits |
| Streaming | Continuously, as events arrive | Sensor anomaly detection | A streaming platform and stateful processing |
Batch serving
A batch job reads a table of inputs, scores every row, and writes the results to a table or file. Downstream systems read the stored scores. This is the simplest pattern. It uses cheap compute that you can start and stop, and it is easy to re-run if something fails.
Choose batch when the answer does not change between runs, or when staleness is acceptable. Many teams use online serving where batch would have been enough.
Online serving
An online service wraps the model in an API. A caller sends features and gets a prediction back in the same request. You must manage latency, throughput, autoscaling, timeouts, and availability, as for any web service.
Two requirements are specific to ML:
- Feature availability. Every feature the model needs must be available at request time. If a feature is computed in a nightly job, it cannot be fresh at request time.
- Training-serving consistency. Features must be computed the same way in the service as in training. Otherwise the model receives inputs it was never trained on, and accuracy drops without any error being raised.
Streaming serving
A streaming consumer reads events from a queue, scores them, and publishes results to another stream. It sits between batch and online. Use it when each event needs a fast response but no caller is waiting synchronously.
A minimal online service
The sketch below loads a model once at startup and exposes a prediction endpoint. It uses FastAPI and validates the input shape. The model file name is an example; in practice you would load the version named in the registry.
from contextlib import asynccontextmanager
import joblib
from fastapi import FastAPI
from pydantic import BaseModel, Field
state = {}
@asynccontextmanager
async def lifespan(app: FastAPI):
# Load once at startup, not on every request.
state["model"] = joblib.load("model.joblib")
state["version"] = "iris-logreg-v3"
yield
state.clear()
app = FastAPI(lifespan=lifespan)
class IrisFeatures(BaseModel):
features: list[float] = Field(min_length=4, max_length=4)
@app.post("/predict")
def predict(request: IrisFeatures):
label = int(state["model"].predict([request.features])[0])
return {"prediction": label, "model_version": state["version"]}
@app.get("/health")
def health():
return {"status": "ok", "model_loaded": "model" in state}Three details matter here. The model loads once, because loading on each request would add large latency. The response includes the model version, so a bad prediction can be traced to the version that produced it. The health endpoint lets the platform check that the model actually loaded before it sends traffic.
Rolling out a new version safely
Passing offline evaluation does not guarantee good behaviour on live traffic. Staged rollout limits the damage if a model turns out to be worse than expected.
| Strategy | How it works | What it protects against |
|---|---|---|
| Shadow | The new model receives a copy of live traffic. Its outputs are logged but never returned to users. | Crashes, latency problems, and unexpected output distributions, with zero user impact |
| Canary | A small share of real traffic (for example 5%) goes to the new model. | Quality or error regressions, with limited exposure |
| Blue/green | Two full environments run. Traffic switches from old to new in one step. | Slow or risky cutovers, since rollback is a switch back |
| A/B test | Traffic is split between versions and a business metric is compared statistically. | Choosing a model on real outcomes instead of offline proxies |
Shadow and canary are often combined: shadow first to check for technical faults, then canary to check real outcomes.
Routing traffic in code
The core of a canary is deterministic routing. Hashing a stable identifier keeps each user on the same version across requests, which avoids inconsistent behaviour and keeps comparisons clean.
import hashlib
def choose_version(user_id: str, canary_fraction: float = 0.05) -> str:
"""Send a stable share of users to the canary model."""
digest = hashlib.sha256(user_id.encode("utf-8")).hexdigest()
bucket = int(digest[:8], 16) / 0xFFFFFFFF # value in [0, 1]
return "canary" if bucket < canary_fraction else "stable"
for uid in ["user-1", "user-2", "user-3", "user-4"]:
print(uid, choose_version(uid))In production this logic usually lives in a load balancer, service mesh, or serving platform rather than in application code. The principle is the same.
Performance and cost considerations
Serving has its own engineering concerns:
- Latency. Measure the 95th and 99th percentile, not only the average. Slow tail requests are what users notice.
- Batching requests. Grouping several requests into one model call raises throughput, especially on GPUs, but adds waiting time for each request.
- Model size. Smaller models, quantization, or distillation can cut latency and cost, at some accuracy cost that you should measure.
- Cold starts. Autoscaled instances must load the model before they serve traffic. Large models can take minutes, so warm instances or readiness checks matter.
- Hardware. GPUs help for large neural networks. Many tabular models run faster and cheaper on CPUs.
Common errors and gotchas
- Training-serving skew. The service computes a feature differently from training, for example a different handling of missing values or a different scaling constant. Fix it by sharing one feature code path or by using a feature store.
- Unpinned environments. A library upgrade changes numerical behaviour or breaks loading of a pickled model. Pin versions and build a container image from the same lock file used in training.
- Unsafe model files. Loading pickle-based files runs arbitrary code. Load only artifacts from your own registry, and consider formats that do not execute code.
- No input validation. Malformed or out-of-range inputs produce confident but meaningless predictions. Validate schema and ranges at the boundary.
- No rollback path. If the previous version is deleted or its feature dependencies changed, you cannot go back. Keep the prior version deployable.
- Missing prediction logging. Without logged inputs, outputs, and versions, you cannot monitor drift or compute live accuracy later. Log them, with attention to privacy rules.
- Delayed labels. For many problems, true outcomes arrive days or weeks after the prediction. Live quality is then measured late, so canary windows must be long enough or must rely on proxy metrics.
Decision criteria
Ask these questions in order:
- Does the prediction need to reflect data from the last few seconds? If not, prefer batch.
- Does a person or system wait for the answer? If yes, you need online serving.
- Are events continuous with no waiting caller? Consider streaming.
- How costly is a wrong prediction? The higher the cost, the more you should use shadow and canary stages, and the slower the rollout.
- Can you roll back in minutes? If not, fix that before the first deployment.
Exercise
A retailer scores 2 million customers each night for a marketing email that goes out the next morning. A teammate proposes an always-on online API. Which pattern fits better, and what would you tell them?
Show answer
Batch serving fits better. No caller waits for an individual answer, and scores that are a few hours old are acceptable. A nightly job is cheaper, simpler to operate, and easy to re-run on failure. An online API would add always-on infrastructure, autoscaling, and latency work without any benefit.
Exercise
A new model scores 2 points higher than production in offline evaluation. Name a rollout sequence that limits risk, and say what each stage checks.
Show answer
Run it in shadow mode first to check for crashes, latency, and odd output distributions with no user impact. Then run a canary with a small share of live traffic to check error rates and quality metrics on real outcomes. If both hold, roll out fully and keep the previous version available for rollback.
Exercise
A service returns fast, error-free responses, but conversion has dropped since the last model release. A review finds that the service fills missing values with 0, while training used the column median. What is this problem called, and how do you prevent it?
Show answer
It is training-serving skew. Prevent it by using a single shared feature computation for training and serving, or a feature store, and by testing that the serving path produces the same features as the training path for the same raw input.