AILearn AI
LearnGlossarySources
ID/EN
Learn AI — open material for learning AIEvery lesson cites its original sources.
⚙ML Development & MLOps
  1. The ML development stack
  2. The ML lifecycle & MLOps maturity
  3. Experiment tracking with MLflow
  4. Model Registry, data versioning & lineage
  5. Deployment & model serving
  6. Monitoring, data drift & concept drift
  7. CI/CD, continuous training & feature stores
Modules
  1. ◎ AI Foundations
  2. ∿ Classical Machine Learning
  3. ⌬ Neural Networks
  4. ↘ Training Results & Evaluation
  5. ▦ Deep Learning Architectures
  6. ✎ Large Language Models
  7. ◐ Image Generation
  8. ♪ Audio & Speech AI
  9. ◈ Multimodal, Video & 3D
  10. ↻ Reinforcement Learning
  11. ⚙ ML Development & MLOps
  12. ★ Advanced & Frontier Topics
Learn/ML Development & MLOps

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.

Advanced~25 min·6 references
Key terms
Model servingBatch inferenceLatencyThroughputDockerONNXInferenceKV cache

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).

≈
Catering vs. à la carte
Batch inference is catering: you cook 10,000 meals overnight and deliver them in the morning — efficient, but nobody can order something new at noon. Online serving is an à-la-carte restaurant: each order is cooked on demand and must arrive within minutes. Dynamic batching is a waiter who waits a few seconds to bring several orders to the kitchen at once — the kitchen is more efficient, but each guest waits a little longer.

Serving patterns

PatternHow it worksGood forWatch out
BatchScheduled job scores a whole table and writes results to a DBChurn scores, nightly recommendations, reportsStale for new users/events; wasted work on unused rows
Online (request/response)REST/gRPC endpoint answers each request in real timeFraud checks at payment, search ranking, chatbotsStrict latency budget; must scale with traffic
StreamingConsumes events from Kafka/Kinesis, emits predictions continuouslyReal-time features, anomaly detection on sensor dataOperational complexity, ordering, state
On-device / edgeModel runs on phone, browser or embedded devicePrivacy, offline use, zero network latencyTight 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 = λ · W (in-flight requests = throughput × average latency)
Little's law: how throughput and latency decide the concurrency you must provision.
In words: “the number of requests inside the system at any moment = how many arrive per second × how long each one stays”. It holds for any stable system, whatever the request mix. So if latency doubles at the same traffic, you need twice the concurrent capacity — slow requests eat capacity.
Symbols(hover a symbol in the formula)
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
λ = 200 req/s, W = 0.05 s (50 ms) L = 200 × 0.05 = 10 requests in flight on average Each replica handles 4 at once → 10 / 4 = 2.5 → run 3 replicas (+ headroom) Latency rises to 0.1 s at the same traffic → L = 200 × 0.1 = 20 → twice the capacity

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

python
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/docs
app/main.py — load the model once at startup, validate input with pydantic, expose /predict and /health.

FastAPI 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

dockerfile
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"]
bash
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-mlflow

A 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].

python
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 verify

4. Dedicated inference servers

ServerStrengthsTypical use
NVIDIA Triton Inference ServerMany backends (TensorRT, ONNX Runtime, PyTorch, Python, vLLM); dynamic batching; concurrent model instances; model ensembles; metricsHigh-throughput GPU serving of many models
vLLMLLM-specific: PagedAttention for KV-cache memory, continuous batching, OpenAI-compatible server (vllm serve <model>)Serving open-weight LLMs
TorchServePyTorch's model server (handlers, model archives); its repository has announced limited maintenance, so check status before adoptingExisting PyTorch deployments
FastAPI / BentoML / KServe / MLflow serveSimple, flexible Python services; KServe adds Kubernetes autoscalingCPU 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.

Loading interactive…
Where the pieces of this lesson sit in a real deployment. Walk through one request from client to GPU and back, then tap Dynamic batching and Autoscaler (HPA). Notice that latency is the sum of every hop (gateway, feature lookup, queue, inference), and that the “× N” pod badge is how you buy throughput.
text
name: "churn"
backend: "onnxruntime"
max_batch_size: 64
dynamic_batching {
  max_queue_delay_microseconds: 2000
}
instance_group [ { count: 2, kind: KIND_GPU } ]
Triton config.pbtxt — enabling dynamic batching for an ONNX model
knobmax batch size (serving)
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.
knobmax queue delay (batch timeout)
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.
knobworkers / replicas
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.
knobrequest timeout
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).
!
Serving pitfalls
• Loading the model inside the request handler → every request pays seconds of load time. • Training-serving skew: preprocessing reimplemented differently in the API than in training — ship the same pipeline object. • Reporting only average latency. • No input validation → garbage in, confident garbage out. • Forgetting 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

1.
Your API's average latency is 40 ms but users complain about slowness. What should you look at first?
2.
You raise Triton's max_queue_delay_microseconds from 500 to 20,000 at moderate traffic. What happens?
3.
By Little's law, a service with 500 req/s and 80 ms average latency has about how many requests in flight?
4.
Why does vLLM's PagedAttention increase LLM serving throughput?
5.
Nightly churn scores for all 2 million customers are needed by the CRM each morning. Which pattern fits best?
Score: 0/5

References

  1. [1]
    FastAPI documentation
    DocsSebastián Ramírezfastapi.tiangolo.com
  2. [2]
    Docker documentation — Get started
    DocsDockerdocs.docker.com
  3. [3]
    ONNX Runtime documentation
    DocsMicrosoft / ONNX Runtimeonnxruntime.ai
  4. [4]
    NVIDIA Triton Inference Server — User Guide
    DocsNVIDIAdocs.nvidia.com
  5. [5]
    Efficient Memory Management for Large Language Model Serving with PagedAttention
    PaperKwon et al.2023arxiv.org
  6. [6]
    torch.onnx — PyTorch documentation
    DocsPyTorchdocs.pytorch.org
← Previous
Model Registry, data versioning & lineage
Next →
Monitoring, data drift & concept drift