Sub topic 10
Building an online prediction service
This chapter assumes you know basic machine learning vocabulary (training, features, prediction), can read Python, and understand what an HTTP API is. You will build a small service that scores one request at a time, then look at the decisions that decide whether it works under real traffic: startup, validation, feature lookup, latency budgets, concurrency, versioning, and failure behavior.
What an online service has to do
A batch job can take minutes and fail without anyone noticing until morning. An online prediction service has a caller waiting for the answer. That changes the design in four ways:
- The model is loaded once, not once per request.
- Every request is validated, because the caller is another program you do not control.
- Every step has a time limit, because the caller has its own time limit.
- Failure must be a defined response, not a crash or a hang.
The request path looks like this.
A minimal working service
First create a model so the examples run. This script trains a small classifier on synthetic data and saves it. It uses a DataFrame so scikit-learn records the feature names.
import joblib
import numpy as np
import pandas as pd
from sklearn.linear_model import LogisticRegression
rng = np.random.default_rng(0)
X = pd.DataFrame(
{
"tenure_months": rng.uniform(0, 72, 500),
"monthly_spend": rng.uniform(10, 200, 500),
"support_tickets": rng.integers(0, 10, 500),
}
)
y = (X["support_tickets"] > 4).astype(int)
model = LogisticRegression(max_iter=1000).fit(X, y)
joblib.dump(model, "model.joblib")Now the service. It needs fastapi, pydantic version 2, pandas, joblib, and uvicorn. Run it with uvicorn service:app if you save it as service.py.
import logging
import time
from contextlib import asynccontextmanager
import joblib
import pandas as pd
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field
FEATURE_ORDER = ["tenure_months", "monthly_spend", "support_tickets"]
MODEL_VERSION = "2026-11-28"
logger = logging.getLogger("churn")
state = {}
@asynccontextmanager
async def lifespan(app: FastAPI):
state["model"] = joblib.load("model.joblib")
yield
state.clear()
app = FastAPI(lifespan=lifespan)
class Features(BaseModel):
tenure_months: float = Field(ge=0)
monthly_spend: float = Field(ge=0)
support_tickets: int = Field(ge=0)
@app.get("/health")
def health():
if "model" not in state:
raise HTTPException(status_code=503, detail="model not loaded")
return {"status": "ok", "model_version": MODEL_VERSION}
@app.post("/predict")
def predict(features: Features):
start = time.perf_counter()
row = pd.DataFrame([features.model_dump()])[FEATURE_ORDER]
score = float(state["model"].predict_proba(row)[0, 1])
elapsed_ms = (time.perf_counter() - start) * 1000
logger.info("scored in %.1f ms", elapsed_ms)
return {"churn_score": score, "model_version": MODEL_VERSION}Several choices here matter.
Load the model once
The lifespan function runs before the first request. Loading a model can take seconds, so doing it inside the handler would add that delay to every call. Loading at startup also means a broken model file fails the deploy, not a customer request.
Fix the feature order in one place
FEATURE_ORDER is a single list used to build the row. Models read columns by position (or by name, if trained on a DataFrame). If the order differs from training, the model still returns a number, so no error appears. This is the most common source of silent wrong answers, and the next chapter material on training-serving skew builds on it.
Validate at the boundary
The Field(ge=0) constraints reject negative values with a 422 response before the model sees them. Decide what the model should do with inputs it was never trained on. A tenure of 100000 months is valid by type but is probably a bug in the caller. Range checks cost microseconds and catch these cases.
Return the model version
Including model_version in every response lets you tell, during an incident, which model produced a given score. It also lets you compare versions during a rollout.
Where the features come from
The example above assumes the caller sends every feature. That is the simplest design, but often wrong. A caller usually knows the customer ID and perhaps a few values from the current event. Features such as "support tickets in the last 90 days" must be looked up.
There are three common sources:
| Source | Typical lookup time | Trade-off |
|---|---|---|
| Sent by the caller in the request | 0 ms | Simple, but every caller must compute features the same way |
| Key-value store or online feature store | 1 to 10 ms | Fast and consistent, but values are only as fresh as the pipeline that fills them |
| Query against the main database | 10 to 500 ms | Always current, but slow and can overload the database |
Prefer an online store that a batch or streaming job fills ahead of time. The service then does a lookup by key, not a computation. If you compute a feature in the service and in the training pipeline using two separate pieces of code, they will drift apart over time.
import httpx
FEATURE_URL = "http://feature-store.internal/customers"
async def fetch_features(customer_id: str) -> dict:
async with httpx.AsyncClient(timeout=0.05) as client:
response = await client.get(f"{FEATURE_URL}/{customer_id}")
response.raise_for_status()
return response.json()The timeout=0.05 sets 50 ms for the whole call. Without a timeout, a slow feature store makes your service slow, and then everything that calls your service slows too.
Latency budgets
Callers usually state a limit, such as "the page must render in 200 ms". Split that limit across the steps so each has an owner.
| Step | Budget (ms) |
|---|---|
| Network in and out | 40 |
| Input validation | 1 |
| Feature lookup | 30 |
| Model inference | 20 |
| Serialization and logging | 4 |
| Safety margin | 105 |
The margin is large on purpose. Track the 95th and 99th percentile of latency, not the average. An average of 40 ms can hide 1 request in 100 taking two seconds, and a page that makes several calls will hit that slow case often.
Concurrency and throughput
A service handles many requests at once. Two details of the FastAPI example are worth knowing.
- A handler declared with
defruns in a thread pool, so a slow model call does not block other requests. A handler declared withasync defruns on the event loop, so a blocking model call inside it stalls every request. Usedeffor CPU-bound model code, andasync defonly when youawaitnetwork calls. - Python threads share one process, and CPU-heavy inference can be limited by the global interpreter lock unless the library releases it. Many numerical libraries do. To use several CPU cores reliably, run several worker processes, for example
uvicorn service:app --workers 4. Each worker loads its own copy of the model, so memory use is multiplied by the number of workers.
For models where one prediction is cheap, such as a logistic regression, one request at a time is fine. For models that run on a GPU or a large neural network, scoring requests one by one wastes hardware. Servers for these models often collect requests for a few milliseconds and score them as one small batch. This is dynamic batching. It trades a little latency for much higher throughput.
Failure handling
Decide in advance what the service returns when something goes wrong. Each failure should map to a response that the caller can handle.
- Invalid input: return 422 and a message. The caller made the mistake, so retrying does not help.
- Feature store timeout: return 503, or return a score based on defaults only if the business accepts it. If you use defaults, mark the response so the caller can see it was degraded.
- Model not loaded: the health check returns 503, and the orchestrator keeps traffic away from this instance.
- Overload: return 429 or 503 quickly. A fast refusal is better than a slow success that arrives after the caller has given up.
@app.post("/predict-with-fallback")
def predict_with_fallback(features: Features):
row = pd.DataFrame([features.model_dump()])[FEATURE_ORDER]
try:
score = float(state["model"].predict_proba(row)[0, 1])
except Exception:
logger.exception("prediction failed")
raise HTTPException(status_code=503, detail="prediction unavailable")
return {"churn_score": score, "model_version": MODEL_VERSION, "degraded": False}The /health endpoint should check that the service can serve, not only that the process is alive. Orchestrators commonly use one check to decide whether to restart an instance and another to decide whether to send it traffic. Keep these separate: a model that is still loading needs time, not a restart.
Deploying a new model
Replacing a model in a running service is a risk. A safe pattern is:
- Build a new service image containing the new model file and a new
MODEL_VERSION. - Start a few instances of the new version beside the old ones.
- Send a small share of traffic to the new instances and compare error rate, latency, and score distribution.
- Increase the share if the numbers look right, and keep the old version available to roll back.
Because the model is loaded at startup and the version is in every response, you can see exactly which instances served which requests.
Common mistakes
- Loading the model inside the request handler, which adds seconds to every call.
- Building the feature row in a different column order than training.
- Calling a slow dependency without a timeout.
- Declaring a handler
async defand then calling a blocking model inside it. - Reporting only average latency.
- Starting many workers without checking memory, since each holds a full copy of the model.
Exercise
Your service has four workers. Each worker loads a 2 GB model at startup. The machine has 6 GB of memory. What happens, and what are two ways to fix it?
Show answer
The workers need about 8 GB for the models alone, so the machine runs out of memory and the operating system may kill processes or the service may fail to start. Two fixes are to reduce the number of workers to two (or fewer) so the copies fit, or to use a larger machine. Other valid options are shrinking the model (for example by quantization) or moving to a serving tool that shares one model across threads in a single process.
Exercise
A page must respond in 150 ms. Your feature lookup has a 99th percentile latency of 120 ms and inference takes 20 ms. Network overhead is 30 ms. Does the service meet the limit at the 99th percentile, and what would you change first?
Show answer
No. At the 99th percentile the path takes about 120 + 20 + 30 = 170 ms, which is over the 150 ms limit. The feature lookup is the largest part, so change it first: move the features into a key-value online store that a batch or streaming job fills ahead of time, or add a lookup timeout with a defined fallback.