Shipping a model means shipping a contract, not a file
You will build a validating prediction endpoint, containerize it, and leave with a checklist that separates a demo from something you can page someone about.
Prerequisites
- !Python virtual environments and pip dependency pinning
- !Basic REST literacy: methods, status codes, and JSON bodies
- !A trained scikit-learn or PyTorch model saved to disk
What You'll Learn
- 1Explain why model load belongs at startup rather than per request
- 2Write Pydantic request and response models that reject bad input before it reaches the model
- 3Containerize the service with a reproducible image and a working health check
- 4Choose between per-request, batched, and asynchronous inference paths
- 5Load test the endpoint and read the latency percentiles it produces
Why naive inference servers fall over
The first version most people write loads the model inside the request handler. It works in a demo, and it fails in three predictable ways. Loading a two-hundred-megabyte artifact on every call turns a forty-millisecond prediction into a three-second one, and it multiplies memory pressure because concurrent requests each hold their own copy. Unvalidated input reaches the model and produces a stack trace that gets returned to the client, leaking file paths. And with no health endpoint, an orchestrator cannot tell the difference between a slow service and a dead one, so it keeps routing traffic into a container that is still importing libraries.
The fix is structural rather than clever. Load once at startup, validate before inference, and expose machine-readable health. Everything else in this lesson builds on that spine. A second structural decision matters just as much: the API is a contract with consumers who do not read your code, so the request schema is the specification, and the response schema is the promise you can be held to.
A useful way to think about latency is that it decomposes into four parts: model load amortized across the process lifetime, preprocessing, inference, and postprocessing. Only the middle term is the model's fault. When a prediction endpoint feels slow, instrument all four before you reach for a bigger instance, because the fix is often in code you wrote rather than in hardware you can rent.
The service skeleton: typed in, typed out
FastAPI gives you request parsing, schema generation, and async dispatch for free, but only if you describe your payloads with Pydantic models. The service below loads a joblib model once during the lifespan hook, serves predictions with measured latency, and reports its own state through health and metadata endpoints.
from contextlib import asynccontextmanager
from time import perf_counter
import joblib
import numpy as np
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field
model = None
@asynccontextmanager
async def lifespan(app: FastAPI):
global model
model = joblib.load("model.joblib") # paid once per process, not per request
yield
model = None
app = FastAPI(
title="Churn Prediction API",
version="2.1.0",
lifespan=lifespan,
)
class PredictionRequest(BaseModel):
features: list[float] = Field(
..., min_length=8, max_length=8,
description="Eight engineered features in training column order",
)
customer_id: str | None = None
class PredictionResponse(BaseModel):
prediction: int
probability: float
model_version: str
latency_ms: float
@app.post("/predict", response_model=PredictionResponse)
async def predict(request: PredictionRequest) -> PredictionResponse:
start = perf_counter()
try:
X = np.asarray(request.features, dtype=np.float64).reshape(1, -1)
proba = float(model.predict_proba(X)[0, 1])
except ValueError as exc:
raise HTTPException(status_code=422, detail=f"Feature shape rejected: {exc}")
return PredictionResponse(
prediction=int(proba >= 0.5),
probability=round(proba, 5),
model_version="2.1.0",
latency_ms=round((perf_counter() - start) * 1000, 2),
)
@app.get("/health")
async def health() -> dict:
return {"status": "ok", "model_loaded": model is not None}
Two lines deserve emphasis. Declaring response_model=PredictionResponse means FastAPI strips any extra field before serialization, so internal debug values never leak to callers. And returning a fixed feature length in the schema turns the most common integration bug, a column order mismatch, into a four-hundred-twenty-two response with a readable message instead of a silent wrong prediction.
Validation as your first line of defense
Schema validation catches shape errors. Domain validation catches the errors that look plausible and are therefore far more dangerous: a negative tenure, a thirty-sigma income, a category the training pipeline never saw. Pydantic validators are the right place for those checks, because they run before your handler and they produce errors that clients can act on.
import math
from typing import Literal
from pydantic import BaseModel, field_validator
class ScoreRequest(BaseModel):
tenure_months: int = Field(..., ge=0, le=1200)
monthly_charges: float = Field(..., gt=0, lt=1000)
contract: Literal["month", "one_year", "two_year"]
features: list[float]
@field_validator("features")
@classmethod
def features_must_be_finite(cls, values: list[float]) -> list[float]:
if any(not math.isfinite(v) for v in values):
raise ValueError("features must contain only finite numbers")
return values
@field_validator("monthly_charges")
@classmethod
def charges_look_sane(cls, value: float) -> float:
if value > 500:
raise ValueError("monthly charges above 500 indicate a unit error")
return value
class ScoreBatch(BaseModel):
requests: list[ScoreRequest] = Field(..., min_length=1, max_length=256)
The literal contract field is worth copying. Enumerated inputs document the allowed values in the generated OpenAPI page at the docs route, and they stop a typo from becoming a row the model treats as a new category. The finite-number check matters because NaN and infinity survive arithmetic silently and will happily produce a confident, wrong probability.
Containerizing the service
Containers are what make the artifact portable: the same image runs on a laptop, in CI, and in a cluster, with identical dependency resolution. Pin every dependency, copy the model in after the requirements layer so code changes do not invalidate the dependency cache, and configure the process manager explicitly rather than relying on defaults.
FROM python:3.11-slim
ENV PYTHONUNBUFFERED=1 \
PIP_NO_CACHE_DIR=1
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY model.joblib .
COPY app.py .
RUN useradd --create-home --uid 10001 appuser
USER appuser
EXPOSE 8000
HEALTHCHECK --interval=30s --timeout=5s --retries=3 \
CMD python -c "import urllib.request as u; u.urlopen('http://127.0.0.1:8000/health')"
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "2"]
Running as a non-root user costs nothing and blocks a whole class of container escape tricks. Choosing two workers rather than sixteen is deliberate: each worker holds its own copy of the model in memory, so worker count multiplies resident memory. With a four-gigabyte model, two workers already consume eight gigabytes before a single request arrives. Scale horizontally with more containers rather than more workers inside one, unless you have measured that memory headroom.
Batching, async, and the concurrency trap
Async handlers shine when the work is I-O bound. Model inference is usually CPU or GPU bound, so an async handler that blocks the event loop will serialize requests just as effectively as a synchronous one, and it will do so while pretending to be concurrent. The honest options are listed below, and the right one depends on your traffic shape rather than on fashion.
| Strategy | Best for | Main risk | Throughput effect |
|---|---|---|---|
| One model call per request | Low traffic, tight latency budget | Wasted accelerator cycles | Baseline |
| Static micro-batching | GPU inference with steady traffic | Added queueing delay | 3 to 10 times higher |
| Async queue plus worker pool | Bursts, spiky arrival patterns | Unbounded queue growth | Smooths peaks |
| Offline batch scoring | Reporting, nightly jobs | Not usable interactively | Highest per dollar |
When the bound is genuinely I-O, such as calling a remote feature service inside the handler, async pays for itself immediately:
import asyncio
from uuid import uuid4
from fastapi import BackgroundTasks
RESULTS: dict[str, dict] = {}
async def score_many(requests: list[PredictionRequest]) -> list[PredictionResponse]:
return await asyncio.gather(*(predict(r) for r in requests))
async def score_background(request: PredictionRequest, task_id: str) -> None:
await asyncio.sleep(0)
RESULTS[task_id] = {"state": "done", "result": await predict(request)}
@app.post("/predict/async")
async def predict_async(
request: PredictionRequest,
background_tasks: BackgroundTasks,
) -> dict:
task_id = str(uuid4())
background_tasks.add_task(score_background, request, task_id)
return {"task_id": task_id, "state": "queued"}
@app.get("/predict/status/{task_id}")
async def status(task_id: str) -> dict:
if task_id not in RESULTS:
return {"state": "pending"}
return RESULTS[task_id]
Bound the queue anyway. An unbounded queue under overload converts a latency problem into an out-of-memory crash, which is much harder to recover from. When the queue exceeds a threshold, reject with a five-hundred-three and a Retry-After header so callers back off predictably.
Observability and load testing
You cannot fix what you do not measure, and averages hide exactly the tail latency that makes an application feel broken. Track the ninetieth and ninety-ninth percentiles alongside the mean, plus error rate and saturation. Four signals cover nearly every serving incident: request rate, error rate, latency distribution, and process memory.
Load testing before launch is a half-day investment that routinely prevents a weekend outage. Drive real traffic at the service, then read percentiles rather than averages.
# Generate sustained load: 50 virtual users for 60 seconds
hey -z 60s -c 50 -m POST \
-H "Content-Type: application/json" \
-d '{"features":[12.5, 0.42, 3, 1, 0, 2, 70.0, 1.2]}' \
http://localhost:8000/predict
# Compare cold-start cost against steady state
for i in 1 2 3; do
docker compose up -d --force-recreate api
sleep 5
curl -s -o /dev/null -w "startup probe: %{time_total}s\n" \
http://localhost:8000/health
done
# Confirm the container image stayed lean
docker images --format "{{.Repository}}:{{.Tag}} {{.Size}}"
The cold-start loop is the one people skip. A service that answers health checks in two hundred milliseconds but takes eight seconds to load its model will pass a naive readiness probe and then drop its first requests, which looks to users like random failure. Readiness must include a successful model load, not merely an open socket.
Production readiness checklist
Treat this as a gate rather than an aspiration. Each row has a failure it prevents, and every failure on the list has happened to somebody this month.
| Check | Why it exists | Cheap way to verify |
|---|---|---|
| Pinned dependencies | Stops surprise upgrades breaking deployments | Rebuild image from cache-less CI |
| Startup and readiness probes | Keeps traffic away from unloaded processes | Restart container and watch routing |
| Structured JSON logs | Makes field-level debugging possible | grep one request_id end to end |
| Latency and error metrics | Reveals degradation before users complain | Grafana panel with p95 and 5xx rate |
| Request size limits | Blocks memory exhaustion attacks | Send a ten-megabyte body, expect 413 |
| Rate limiting | Protects shared downstream capacity | Burst test and confirm 429 responses |
| Model version in responses | Enables rollback attribution | Compare two deployments' payloads |
| Graceful shutdown | Drains in-flight work on redeploy | Send SIGTERM during an active request |
| Auth on write endpoints | Prevents unauthorized scoring | Call without a key, expect 401 |
None of these require a platform. Every one of them is a few lines or a configuration flag, and together they are the difference between a script that predicts and a service that serves.
Common Mistakes
Loading the model inside the request handler for simplicity
Fix: Load during startup lifespan hooks so the first request pays the cost once per process and memory stays shared
Returning generic five-hundred errors with raw exception text to the client
Fix: Catch domain exceptions, log full context with a request id, and return a short stable error code the caller can branch on
Declaring async handlers around CPU-bound inference and expecting parallelism
Fix: Measure the event loop stall; if inference blocks it, run sync handlers in a worker pool or batch on an accelerator
Calling the service healthy as soon as the port opens
Fix: Gate readiness on a completed model load and a successful self-prediction against known input
Scaling worker count without multiplying available memory
Fix: Compute resident memory per worker, size the container from that number, and prefer more containers over more workers
Best Practices
- Pin every dependency with an exact version and rebuild images on a schedule to surface drift early
- Expose the model version and a request id in every response so incidents are traceable to a deployment
- Record p50, p90, and p99 latency separately; alert on the tail and on error rate rather than on averages
- Enforce request size limits and rate limits at the edge before requests reach Python
- Run the load test in CI against the release candidate, not only on the day before launch
- Keep preprocessing in the service so the API reproduces training-time feature order exactly
Interview Questions
Q1: Where should a model be loaded, and what breaks if it is loaded per request?
At process startup, inside a lifespan or warm-up hook. Per-request loading multiplies latency by the artifact size, defeats caching across requests, and can exhaust memory under concurrency because each in-flight request holds its own copy. Startup loading also lets readiness gating wait for the model to be usable.
Q2: How do you decide between sync and async handlers in FastAPI?
Classify the work. If inference is CPU or GPU bound and blocks, an async handler buys nothing and can serialize requests behind a stalled event loop. If the handler spends its time waiting on a feature store or database, async lets one worker serve many in-flight requests. In practice, use async for I-O, worker processes for compute, and batching when an accelerator would otherwise sit idle.
Q3: What signals do you monitor on a model API?
Request rate, error rate broken down by status class, latency percentiles, and saturation such as queue depth or memory. On the model side, track score distribution and input feature drift so you notice when the data changes rather than only when the service breaks. Alert on the tail of latency and on error rate, not on means.
Q4: A deployment doubles response times for one hour, then recovers. How do you investigate?
Correlate with deploy events, CPU and memory saturation, and downstream latency. Check whether an autoscaler overshot or undershot, whether the new model is heavier than its predecessor, and whether garbage collection pauses grew. Compare p99 against p50: if only the tail moved, contention or queueing is the likely cause; if the whole distribution shifted, the code path itself got slower.
Key Takeaways
- Load the model once at startup and gate readiness on it, so the first request is not the one that pays the cost
- Pydantic schemas are the API contract: validate shape and domain plausibility before inference, and use response models to prevent leaks
- Container images should be pinned, non-root, and lean, with worker count chosen from measured memory per worker rather than core count
- Async helps only when work is I-O bound; CPU-bound inference needs batching or a worker pool instead
- Load test with percentiles, verify cold-start behaviour, and treat the production checklist as a release gate