Lab: Containerize, Load-Test and Optimize
Package the prediction API from the previous lab as a container image with pinned dependencies and a non-root user, load-test it with concurrent requests to read p50, p95 and p99 latency and throughput, switch the model to ONNX Runtime after checking that predictions match, measure again, and turn the throughput into a cost per 1,000 predictions.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: Write the image definition
- Step 2: Add a second backend, then build and start the service
- Step 3: Load-test the baseline
- Step 4: Apply one optimisation and measure again
- Step 5: Turn throughput into cost
- Check your understanding
- Apply it
- Review prompt
Lessons of Model Packaging & Serving
- What Exactly Are You Shipping? Model Artifacts and Formats Concept · 20 min
- Batch, Online or Streaming: Picking the Inference Pattern Concept · 15 min
- Lab: A Validated Prediction API with Shared Batch Scoring Lab · 30 min
- Lab: Containerize, Load-Test and Optimize Lab · 30 min
- Safe Rollouts: Shadow, Canary, A/B Tests and Rollback Concept · 15 min
- Check: Serving Design Review Knowledge check · 8 questions
What you will learn
- Containerize the service, load-test it for p50/p95 latency and throughput, and apply one optimization (request batching, quantization, ONNX Runtime, or a dedicated LLM server such as vLLM) with measured impact on latency and cost.
Prerequisites: Containerization
01. Goal and setup
The service from the API lab works on your laptop. To run it anywhere else you package it as a container image: a file system with Python, the pinned libraries, your code and the model, plus the command that starts the service. Then you measure it the way users will experience it, under concurrent load, and you make it faster with one change whose effect you measure before and after.
Work in the serving-lab folder of the API lab, with its virtual environment active. You need its model.skops, metadata.json, predict.py and data.py. Building and running the image needs Docker; every other step runs without it, and step 2 shows how to run the same service command directly if Docker is not available. Latency and throughput depend on your machine, so those outputs are illustrative: the numbers in this lesson come from an older 4-core desktop and only their ratios matter.
cd serving-lab
python -m pip install "skl2onnx==1.20.*" "onnxruntime==1.32.*"02. Step 1: Write the image definition
First pin every runtime dependency to an exact version. The training environment produced the artifact with these versions, and the metadata records them; an image built next month must not pick up a newer scikit-learn by accident. The serving image does not need skl2onnx or training tools, only what the service imports.
fastapi==0.163.1
uvicorn==0.54.0
pydantic==2.14.3
scikit-learn==1.9.1
numpy==2.5.5
pandas==3.1.1
skops==0.16.0
onnxruntime==1.32.0A Dockerfile lists the steps that build the image. Each instruction creates a layer, and Docker reuses a layer from its cache when nothing it depends on has changed. That is why the order matters: the dependencies, which change rarely, are installed before the code and the model are copied, so changing app.py does not reinstall every library. The service runs as an ordinary user, not root, which limits the damage if the process is ever compromised. HEALTHCHECK asks the readiness endpoint, using Python because the slim base image has no curl. The base image is pinned to a Python patch release, like the libraries; for fully repeatable builds, pin it by digest as well (python:3.12.13-slim@sha256:…), because a tag can be rebuilt with newer system packages. The .dockerignore file keeps the local virtual environment and data files out of the image.
FROM python:3.12.13-slim
# Install the pinned dependencies first: this layer is reused until they change.
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Then the code and the artifact, which change more often.
COPY predict.py onnx_model.py app.py metadata.json model.skops model.onnx ./
# Do not run the service as root inside the container.
RUN useradd --create-home --uid 10001 appuser
USER appuser
EXPOSE 8000
HEALTHCHECK --interval=10s --timeout=3s --start-period=20s CMD \
python -c "import urllib.request as u; u.urlopen('http://localhost:8000/health/ready')"
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "1"].venv/
__pycache__/
*.csv03. Step 2: Add a second backend, then build and start the service
The Dockerfile already copies onnx_model.py and model.onnx, the optimisation you will measure in step 4. onnx_model.py offers the same predict interface as predict.Model, backed by ONNX Runtime: it feeds each column as a typed array and uses one thread per request, because a single row is too small to split. export_onnx.py converts the pipeline and compares both backends on 1,000 new customers before anything is served. The new app.py replaces the old one: it reads MODEL_BACKEND from the environment and reports the backend in /version.
"""The same predict interface as predict.Model, backed by ONNX Runtime."""
import json
import numpy as np
import onnxruntime as ort
from predict import Customer, Prediction
INT_COLUMNS = ["tenure_months", "support_calls"]
TEXT_COLUMNS = ["plan", "channel"]
class OnnxModel:
def __init__(self, path="model.onnx", metadata_path="metadata.json"):
self.metadata = json.load(open(metadata_path))
options = ort.SessionOptions()
options.intra_op_num_threads = 1 # a request is tiny: skip thread overhead
self.session = ort.InferenceSession(path, options,
providers=["CPUExecutionProvider"])
def predict(self, customers: list[Customer]) -> list[Prediction]:
def column(name, dtype):
return np.array([[getattr(c, name)] for c in customers], dtype=dtype)
feeds = {name: column(name, np.int64) for name in INT_COLUMNS}
feeds["monthly_fee"] = column("monthly_fee", np.float32)
feeds.update({name: column(name, object) for name in TEXT_COLUMNS})
_, proba = self.session.run(None, feeds)
version, threshold = self.metadata["model_version"], self.metadata["threshold"]
return [Prediction(churn_probability=round(float(p), 6),
will_churn=bool(p >= threshold), model_version=version)
for p in proba[:, 1]]"""Export the served pipeline to ONNX and compare both backends on 1,000 customers."""
import pandas as pd
import skops.io as sio
from skl2onnx import to_onnx
from skl2onnx.common.data_types import (FloatTensorType, Int64TensorType,
StringTensorType)
from data import CATEGORICAL, NUMERIC, make
from onnx_model import OnnxModel
from predict import Customer, Model
types = [("tenure_months", Int64TensorType([None, 1])),
("monthly_fee", FloatTensorType([None, 1])),
("support_calls", Int64TensorType([None, 1])),
("plan", StringTensorType([None, 1])),
("channel", StringTensorType([None, 1]))]
onx = to_onnx(sio.load("model.skops"), initial_types=types, options={"zipmap": False},
target_opset=18)
open("model.onnx", "wb").write(onx.SerializeToString())
rows = make(n=1000, seed=3)[NUMERIC + CATEGORICAL]
customers = [Customer(**row) for row in rows.to_dict(orient="records")]
sk = pd.Series([p.churn_probability for p in Model().predict(customers)])
ox = pd.Series([p.churn_probability for p in OnnxModel().predict(customers)])
print(f"customers compared: {len(customers)}")
print(f"largest difference after rounding to 6 decimals: {(sk - ox).abs().max():.6f}")
print("same decisions:", (sk >= 0.5).equals(ox >= 0.5))"""Online inference: a FastAPI service around the shared predict module."""
import os
from contextlib import asynccontextmanager
from fastapi import FastAPI, Response
from onnx_model import OnnxModel
from predict import Customer, Model, Prediction
BACKENDS = {"sklearn": Model, "onnx": OnnxModel}
state = {"model": None}
@asynccontextmanager
async def lifespan(app: FastAPI):
backend = os.environ.get("MODEL_BACKEND", "sklearn")
state["model"] = BACKENDS[backend]() # load once, at startup
yield
state["model"] = None
app = FastAPI(title="churn-api", lifespan=lifespan)
@app.get("/health/live")
def live():
return {"status": "alive"} # the process answers: do not restart it
@app.get("/health/ready")
def ready(response: Response):
if state["model"] is None: # not loaded: send no traffic here yet
response.status_code = 503
return {"status": "loading"}
return {"status": "ready"}
@app.get("/version")
def version():
meta = state["model"].metadata
return {"model_version": meta["model_version"], "sha256": meta["sha256"][:12],
"backend": type(state["model"]).__name__}
@app.post("/predict")
def predict(customers: list[Customer]) -> list[Prediction]:
return state["model"].predict(customers)python export_onnx.pycustomers compared: 1000
largest difference after rounding to 6 decimals: 0.000001
same decisions: TrueThe largest difference is one unit in the sixth decimal, a rounding effect of 32-bit arithmetic, and every decision is the same, so the two backends are interchangeable. Now build the image and start a container. --cpus 2 and --memory 1g give it the same limits it would have in production, which matters because a load test on an unlimited laptop says little about a 2-CPU container.
docker build -t churn-api:1 .
docker run --rm --name churn-api --cpus 2 --memory 1g -p 8742:8000 churn-api:1After the first build, docker images churn-api lists the image, and the running container answers on port 8742 of your machine. docker ps shows its health as starting and then healthy once the readiness endpoint answers. Without Docker, start the same command the image runs, in a second terminal, and leave it running:
uvicorn app:app --host 127.0.0.1 --port 8742 --workers 104. Step 3: Load-test the baseline
A load test sends many requests and records how long each takes from the client's point of view, which includes queueing, network and serialisation, not just the model. loadtest.py keeps 8 requests in flight at once and sends 400 after 20 warm-up requests. Warm-up matters because the first calls pay one-off costs, such as opening connections and filling caches, that would distort the tail.
Read the results as percentiles. p50, the median, is the latency that half of the requests beat. p95 is the latency that 95% beat, so 1 request in 20 is slower; p99 covers all but 1 in 100. Users notice the tail, so latency targets are usually written for p95 or p99. Throughput is completed requests per second. Percentiles cannot be averaged with each other or across runs; compare them run against run under the same load.
"""Send concurrent requests to the API and report latency percentiles and throughput."""
import asyncio
import statistics
import sys
import time
import httpx2
URL = sys.argv[1]
CONCURRENCY, TOTAL, WARM_UP = 8, 400, 20
BODY = [{"tenure_months": 3, "monthly_fee": 70.0, "support_calls": 4,
"plan": "basic", "channel": "online"}]
async def worker(client, jobs, latencies):
while jobs:
jobs.pop()
start = time.perf_counter()
response = await client.post(URL, json=BODY)
response.raise_for_status()
latencies.append(time.perf_counter() - start)
async def main():
async with httpx2.AsyncClient(timeout=10) as client:
for _ in range(WARM_UP): # first calls pay one-off costs
(await client.post(URL, json=BODY)).raise_for_status()
jobs, latencies = list(range(TOTAL)), []
start = time.perf_counter()
workers = [worker(client, jobs, latencies) for _ in range(CONCURRENCY)]
await asyncio.gather(*workers)
elapsed = time.perf_counter() - start
q = statistics.quantiles(latencies, n=100) # q[49] = p50, q[94] = p95
print(f"{TOTAL} requests, {CONCURRENCY} at once: {TOTAL / elapsed:.0f} per second")
print(f"latency p50 {q[49] * 1000:.1f} ms p95 {q[94] * 1000:.1f} ms "
f"p99 {q[98] * 1000:.1f} ms")
asyncio.run(main())python loadtest.py http://127.0.0.1:8742/predict400 requests, 8 at once: 144 per second
latency p50 55.0 ms p95 72.6 ms p99 80.2 msOn our machine the service handled about 144 requests per second. With 8 requests in flight, each one waits for the others: the p50 of about 55 ms is mostly time spent in the queue behind other requests, since one prediction costs a few milliseconds of real work. That real work is mostly per-call overhead of the scikit-learn pipeline (building a data frame, checking columns, running each transformer), the overhead that the inference-patterns lesson measured at several milliseconds per single-row call on the same machine.
05. Step 4: Apply one optimisation and measure again
Change one thing at a time, so that you know what caused the difference. Start a second server with the ONNX backend on another port, check which backend it reports, and run exactly the same load test. In the container you would set -e MODEL_BACKEND=onnx on docker run instead.
MODEL_BACKEND=onnx uvicorn app:app --host 127.0.0.1 --port 8743 --workers 1curl -s http://127.0.0.1:8743/version \
| python -c "import json, sys; print(json.load(sys.stdin)['backend'])"OnnxModelpython loadtest.py http://127.0.0.1:8743/predict400 requests, 8 at once: 772 per second
latency p50 10.1 ms p95 15.5 ms p99 16.8 msOn our machine throughput rose about five times and p95 fell from about 73 ms to about 16 ms. The gain comes from skipping per-call Python overhead, so it is large for small tabular models and small requests; for a large neural network, where the matrix arithmetic dominates, the gain from ONNX Runtime is usually smaller and needs its own measurement.
Other optimisations target other bottlenecks, and each must be measured in the same way. Dynamic batching makes the server wait a few milliseconds to group concurrent requests into one model call; it pays off when one call on a batch costs little more than one call on a single row, as on GPUs. Quantisation stores weights in 8-bit integers instead of 32-bit floats to save memory and compute; it changes predictions slightly, so you must also report accuracy on the same evaluation data. For large language models, dedicated servers such as vLLM batch requests continuously at the token level and manage the attention cache, which a plain web framework cannot do. For phones and edge devices, runtimes such as ONNX Runtime Mobile, ExecuTorch and LiteRT run exported models on the device itself.
06. Step 5: Turn throughput into cost
Speed only matters to the business when you turn it into money. If one machine at an assumed $0.10 per hour can serve N requests per second, the cost of 1,000 predictions is its hourly price divided by the predictions it serves in an hour, times 1,000. Plan for less than the measured maximum: running at about 60% leaves room for traffic peaks without the queue, and with it p95, exploding. Pass your own two throughput numbers.
"""Cost per 1,000 predictions from measured throughput. Prices are assumptions."""
import sys
PRICE_PER_HOUR = 0.10 # one machine with 2 vCPUs, $ per hour (use your own price)
UTILISATION = 0.6 # plan for 60% of the measured maximum, to keep headroom
for name, measured in zip(["scikit-learn", "ONNX Runtime"], sys.argv[1:3]):
per_hour = float(measured) * 3600 * UTILISATION
print(f"{name:13} {float(measured):5.0f} req/s measured, "
f"${PRICE_PER_HOUR / per_hour * 1000:.6f} per 1,000 predictions")python cost.py 144 772scikit-learn 144 req/s measured, $0.000322 per 1,000 predictions
ONNX Runtime 772 req/s measured, $0.000060 per 1,000 predictionsThe cost per prediction falls by the same factor as throughput rises, because the same machine-hour now serves five times as many predictions. Equally, you could keep the cost and serve five times the traffic on one machine, or move to a smaller one. Report the change as a before-and-after table: p50, p95, throughput, cost per 1,000 predictions, and the parity result that shows predictions did not change. Stop both servers with Ctrl+C when you are done.
07. Check your understanding
08. Apply it
For your project, containerise the service of the previous lab with pinned requirements and a non-root user, run it with the CPU and memory limits you expect in production, and load-test it at two or three concurrency levels. Choose one optimisation that fits your bottleneck (ONNX Runtime, request batching or quantisation), check that predictions still match, and report p50, p95, throughput and cost per 1,000 predictions before and after.
09. Review prompt
Without looking back, answer in your own words:
- What goes into a serving image, and why are the dependencies installed before the code is copied?
- What do p50, p95 and p99 mean, and why do latency targets focus on the tail?
- Why must an optimisation be checked for prediction parity as well as speed?
- How do you turn throughput into a cost per 1,000 predictions, and why plan below the measured maximum?
- When do dynamic batching, quantisation or a dedicated LLM server help?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.