Serve a Model in Production: Docker, Latency and Scaling
Who it is for
What you will achieve
Prerequisites
Curriculum
- Step 1: Online, Batch or Streaming? Picking the Serving Pattern for an ML Model
Before writing any API code, decide how a model's answers should reach people. Two questions, who is waiting and when is the input known, pick between an online API, batch scoring and streaming.
- Step 2: A Production FastAPI for an ML Model: Input Limits, /health, /ready and a Model Version
Grow a simple model API into one you can run: Field limits that refuse a humidity of 140, a clean 422, a /v1 route with a response model, a startup load with /health and /ready, and a model version in every log line.
- Step 3: Batch Scoring a Million Rows: Chunks, a Run ID and a Safe Rerun
Score one million rows with a saved model: all at once, then in chunks that use about half the memory with identical answers. Then make the job safe to kill and rerun with a run id, one part file per chunk, and a tmp-then-rename write.
- Step 4: Docker Essentials for ML: Images, Containers and Volumes with a Model API
Pack the rain-prediction API into a Docker image, start a container from it, stop and remove it, and keep the model file outside the container with a volume. Every command and output comes from a real run.
- Step 5: Containerising a Model API: A Dockerfile for FastAPI and scikit-learn, Line by Line
Read a 16-line Dockerfile for a FastAPI model API: what .dockerignore leaves out, why packages go before code, why 0.0.0.0 matters, where 671MB really goes, and how a health check watches the app.
- Step 6: Latency Math: p50, p95, p99 and Why the Tail Reaches Your Users
What p50, p95 and p99 really mean, why an average of 109 ms can describe nobody, why a p95 needs its load beside it, and why a page that makes ten calls hits a slow one about 40% of the time.
- Step 7: Measuring Latency of an ML API: Timing Inside with OpenTelemetry, Outside with a Load Test and Locust
Two stopwatches for one ML API: inside, a middleware header and OpenTelemetry spans show where the time goes; outside, an asyncio load test and Locust show how slow it gets under load. All numbers from one local run.
- Step 8: Making ML Inference Fast: ONNX, Micro-Batching and Quantisation, Measured
Speed up a scikit-learn model without a faster machine: ONNX skips the checks around the math (8.38 ms to 0.087 ms here), micro-batching pays when requests overlap, and quantisation does nothing for a small logistic model but a lot for a big network.
- Step 9: Sizing and Autoscaling an Inference Service: From One Replica to a Replica Count
How many copies of a model API do you need, and when do you add more? Measure one replica (it flattens at about 64 requests a second here), pick a row with a latency budget, size for a target with headroom, and scale early on the queue, not on CPU.