Deployment & model serving
Batch vs online vs streaming inference, latency percentiles and throughput, a FastAPI + Docker service, ONNX export, and when to use Triton, vLLM and friends.
A model creates value only when its predictions reach a user or a system. [[model-serving]] is everything between “I have a model file” and “an application gets a prediction”: choosing the serving pattern, wrapping the model in an API, packaging it in a container, making it fast enough, and rolling it out safely. The two numbers you will live by are [[latency]] (how long one request takes) and [[throughput]] (how many requests or tokens per second you can handle).
Serving patterns
| Pattern | How it works | Good for | Watch out |
|---|---|---|---|
| Batch | Scheduled job scores a whole table and writes results to a DB | Churn scores, nightly recommendations, reports | Stale for new users/events; wasted work on unused rows |
| Online (request/response) | REST/gRPC endpoint answers each request in real time | Fraud checks at payment, search ranking, chatbots | Strict latency budget; must scale with traffic |
| Streaming | Consumes events from Kafka/Kinesis, emits predictions continuously | Real-time features, anomaly detection on sensor data | Operational complexity, ordering, state |
| On-device / edge | Model runs on phone, browser or embedded device | Privacy, offline use, zero network latency | Tight memory/compute; needs Quantization or Knowledge distillation |
Latency, throughput and tail latency
Averages hide pain. Report latency as percentiles: p50 (median — the typical request), p95 and p99 (the slowest 5% / 1%). If a page calls 10 services, the chance that at least one hits its p99 is ≈ 1 − 0.99¹⁰ ≈ 10%, so tail latency dominates user experience. Throughput is requests/s (or tokens/s for LLMs). The two are linked by Little's law:
- L
- average number of requests in flight (being queued or processed) at the same time
- λ
- lambda — arrival rate = throughput, in requests per second
- W
- average time a request spends in the system (latency), in seconds
- ·
- multiplication
▸Worked example
Batching is the main trade-off lever: GPUs are far more efficient on a batch of 32 inputs than on 32 separate inputs, so grouping requests raises throughput — but each request may wait in a queue for the batch to fill, raising latency. Servers like Triton implement dynamic batching with a maximum batch size and a maximum queue delay[4].
1. An online API with FastAPI
import os
from contextlib import asynccontextmanager
import mlflow
import pandas as pd
from fastapi import FastAPI
from pydantic import BaseModel, Field
MODEL_URI = os.getenv("MODEL_URI", "models:/churn-clf@champion")
state = {}
@asynccontextmanager
async def lifespan(app: FastAPI):
state["model"] = mlflow.sklearn.load_model(MODEL_URI) # once, not per request
yield
app = FastAPI(title="churn-api", lifespan=lifespan)
class Customer(BaseModel):
tenure_months: int = Field(ge=0)
monthly_charges: float = Field(gt=0)
contract: str # "monthly" | "yearly"
class Prediction(BaseModel):
churn_probability: float
model_uri: str
@app.get("/health")
def health():
return {"status": "ok"}
@app.post("/predict", response_model=Prediction)
def predict(c: Customer):
X = pd.DataFrame([c.model_dump()])
p = float(state["model"].predict_proba(X)[0, 1])
return Prediction(churn_probability=p, model_uri=MODEL_URI)
# run locally: uvicorn app.main:app --reload → docs at http://127.0.0.1:8000/docsFastAPI generates interactive OpenAPI docs at /docs and rejects malformed requests with a 422 error thanks to the pydantic schema[1]. Defining the endpoint with plain def makes FastAPI run it in a thread pool, which is appropriate for blocking CPU-bound model calls.
2. Package it with Docker
FROM python:3.12-slim
WORKDIR /app
# install dependencies first so this layer is cached between code changes
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY app/ ./app
ENV MODEL_URI=models:/churn-clf@champion
EXPOSE 8000
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "2"]docker build -t churn-api:1.0 .
docker run -p 8000:8000 -e MLFLOW_TRACKING_URI=http://mlflow:5000 churn-api:1.0
curl -X POST localhost:8000/predict -H "Content-Type: application/json" \
-d '{"tenure_months": 3, "monthly_charges": 79.5, "contract": "monthly"}'
# MLflow can also build or serve a container straight from a registered model:
mlflow models serve -m "models:/churn-clf@champion" -p 5001
mlflow models build-docker -m "models:/churn-clf@champion" -n churn-mlflowA Docker image freezes the OS libraries, Python version and dependencies, so “works on my machine” becomes “works everywhere the image runs” — a laptop, CI, Kubernetes or a cloud service[2]. Copy requirements.txt before the code so dependency layers are cached, keep images slim, and never bake secrets into the image.
3. ONNX: a portable, faster model format
[[onnx]] (Open Neural Network Exchange) is an open format for computation graphs. Export once from PyTorch with torch.onnx.export[6] (or scikit-learn via skl2onnx), then run with ONNX Runtime on CPU, CUDA, TensorRT, DirectML, mobile or the browser — often faster than eager PyTorch thanks to graph optimisations, and without needing PyTorch installed in the serving image[3].
import numpy as np
import torch
import onnxruntime as ort
model.eval()
dummy = torch.randn(1, 20)
torch.onnx.export(
model, (dummy,), "churn.onnx",
input_names=["features"], output_names=["logits"],
dynamic_axes={"features": {0: "batch"}, "logits": {0: "batch"}}, # variable batch size
)
sess = ort.InferenceSession("churn.onnx", providers=["CPUExecutionProvider"])
x = np.random.randn(8, 20).astype(np.float32)
(logits,) = sess.run(None, {"features": x})
print(logits.shape) # (8, 2) — compare with model(torch.from_numpy(x)) to verify4. Dedicated inference servers
| Server | Strengths | Typical use |
|---|---|---|
| NVIDIA Triton Inference Server | Many backends (TensorRT, ONNX Runtime, PyTorch, Python, vLLM); dynamic batching; concurrent model instances; model ensembles; metrics | High-throughput GPU serving of many models |
| vLLM | LLM-specific: PagedAttention for KV-cache memory, continuous batching, OpenAI-compatible server (vllm serve <model>) | Serving open-weight LLMs |
| TorchServe | PyTorch's model server (handlers, model archives); its repository has announced limited maintenance, so check status before adopting | Existing PyTorch deployments |
| FastAPI / BentoML / KServe / MLflow serve | Simple, flexible Python services; KServe adds Kubernetes autoscaling | CPU models, business logic around the model |
LLM serving is special: output is generated token by token and each sequence keeps a growing KV cache. Kwon et al. showed that naive KV-cache allocation wastes much of GPU memory through fragmentation; PagedAttention stores the cache in fixed-size blocks (like virtual-memory pages), so far more sequences fit in a batch, and vLLM reported 2–4× higher throughput than prior systems at similar latency[5]. Continuous batching adds new requests into the running batch at every decoding step instead of waiting for the whole batch to finish.
name: "churn"
backend: "onnxruntime"
max_batch_size: 64
dynamic_batching {
max_queue_delay_microseconds: 2000
}
instance_group [ { count: 2, kind: KIND_GPU } ]- What it is
- The largest number of requests the server merges into one forward pass.
- ↑ If you increase it
- Higher throughput and GPU utilisation; more memory per batch and higher latency for requests waiting to fill it.
- ↓ If you decrease it
- Lowest per-request latency but the GPU is underused, so cost per prediction rises.
- Typical values
- 1–8 for latency-critical CPU APIs; 16–128 on GPUs; for LLMs limited by KV-cache memory.
- What it is
- How long the server may hold a request while waiting for more requests to form a batch.
- ↑ If you increase it
- Fuller batches → better throughput under moderate traffic, but adds up to that delay to every request's latency.
- ↓ If you decrease it
- Requests go out almost immediately (low latency) but batches are small at low traffic.
- Typical values
- 0.5–10 ms for online APIs.
- What it is
- Number of server processes (e.g. uvicorn
--workers) or container replicas handling traffic in parallel. - ↑ If you increase it
- More parallel capacity and resilience to one replica failing; each worker loads its own copy of the model (memory × N).
- ↓ If you decrease it
- Cheaper, but queues build up at peak traffic and p99 latency explodes.
- Typical values
- Size with Little's law + 30–50% headroom; autoscale on CPU/GPU utilisation or queue length.
- What it is
- Maximum time a client or gateway waits for a prediction before giving up (and maybe using a fallback).
- ↑ If you increase it
- Fewer failed requests during slow moments, but slow requests tie up resources and users wait.
- ↓ If you decrease it
- Snappier failure and quick fallback to a default/heuristic; more errors if set below your p99.
- Typical values
- A bit above the target p99 (e.g. 2× p99).
model.eval()/torch.no_grad() in PyTorch services. • Not verifying ONNX outputs numerically against the original model. • Releasing to 100% at once instead of shadow → canary → full.▸Go deeper: rollout strategies
- Shadow deployment — the new model receives a copy of live traffic but its predictions are only logged, never used. Zero user risk; validates latency and output distribution.
- Canary — a small share of users gets the new model; expand if metrics hold.
- Blue/green — two full environments; switch traffic at once and switch back instantly on trouble.
- [[a-b-testing|A/B test]] — randomised split to measure the causal effect on business metrics.
Quiz
max_queue_delay_microseconds from 500 to 20,000 at moderate traffic. What happens?References
- [1]FastAPI documentationDocsSebastián Ramírezfastapi.tiangolo.com
- [2]Docker documentation — Get startedDocsDockerdocs.docker.com
- [3]ONNX Runtime documentationDocsMicrosoft / ONNX Runtimeonnxruntime.ai
- [4]NVIDIA Triton Inference Server — User GuideDocsNVIDIAdocs.nvidia.com
- [5]Efficient Memory Management for Large Language Model Serving with PagedAttentionPaperKwon et al.2023arxiv.org
- [6]torch.onnx — PyTorch documentationDocsPyTorchdocs.pytorch.org