Sub topic 10
Building an online prediction service
This chapter assumes you know basic machine learning vocabulary, can read Python, and understand what an HTTP API is. An online prediction service is a small program that waits for requests, scores one record per request, and returns the result within a tight time limit.
The shape of the service
The service follows the same steps for every request:
- Receive a request containing the features, or an ID used to look them up.
- Validate the input.
- Build the feature row in the order used in training.
- Call the model.
- Return the score.
A minimal service
The example below loads the model once, when the process starts. It does not reload the model on each request. Reading a model file from disk can take far longer than the prediction itself.
import joblib
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
model = joblib.load("model.joblib")
class Features(BaseModel):
tenure_months: float
monthly_spend: float
support_tickets: int
@app.post("/predict")
def predict(features: Features):
row = [[features.tenure_months, features.monthly_spend, features.support_tickets]]
return {"churn_score": float(model.predict_proba(row)[0, 1])}Run it with uvicorn app:app after saving the code as app.py. Then send a POST request to /predict with a JSON body that has the three fields.
Design decisions that matter
Input validation
The Features class makes FastAPI reject requests with missing fields or wrong types before the model sees them. A request with a text value in monthly_spend gets an error response instead of a crash or a silent wrong score. You can tighten the class further, for example by rejecting negative values.
Feature order
The model sees only a list of numbers. If the row is built as [spend, tenure, tickets] but training used [tenure, spend, tickets], the service still returns a score, and the score is wrong. Keep the column order in one shared definition that both training and serving import. This is a common source of training-serving skew.
Where features come from
This example makes the caller send every feature. Many services instead receive only a customer_id and fetch features from an online store, which is a low-latency key-value database. That lookup adds latency to every request, so measure it separately from model time.
Latency budget
Set a target, such as 100 ms at the 95th percentile, and divide it among the steps: network, feature lookup, model call, and serialization. A large model or a slow lookup can use up the whole budget on its own.
Scaling
Run several copies of the service behind a load balancer. Each copy holds its own model in memory, so memory use grows with the number of copies. Add copies when request volume rises, and keep enough running that a traffic spike does not queue requests.
Common errors
- Loading the model inside the handler. Every request pays the file-read cost. Load once at startup.
- No health check. A load balancer needs an endpoint, such as
GET /health, to tell whether a copy is ready to receive traffic. - Mismatched library versions. A model saved with one scikit-learn version may fail or behave differently under another. Pin the version in both training and serving.
- No timeout on feature lookups. A slow database then stalls every request. Set a timeout and decide on a fallback, such as a default score or an error.
Exercise
A teammate's service passes the unit tests and starts without errors. In production, its scores for the same customers differ from the batch job's scores. Name two likely causes related to this chapter.
Show answer
First, the feature order in the service's row differs from the order used in training. Second, the service computes a feature differently from the training pipeline, or runs a different library version, which is training-serving skew. Comparing both pipelines' outputs on the same rows would show which one is at fault.