Sub topic 3
Real-time prediction: scoring one request on demand
Prerequisites
This chapter assumes you know basic machine learning vocabulary (training, model, features, prediction), can read Python, and understand what an HTTP API is. You should also have read the chapters on inference basics and batch prediction.
What real-time prediction is
Real-time prediction, also called online prediction, scores one request at the moment it arrives. A caller sends the features for one entity, such as one customer or one transaction. The service returns a prediction in the same request-response cycle. The caller waits for the answer, so the response has to arrive within a latency budget, often tens to hundreds of milliseconds.
The model is not retrained on each call. A trained model file is loaded into a long-running process. Each request runs a single forward pass through that already-loaded model.
A minimal service
The example below loads the model once at startup and scores one request per call.
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])}Three details matter here:
joblib.loadruns at module import, not insidepredict. Loading a model on every request would add far more latency than the prediction itself.- The
Featuresclass validates input. A request with a missing field or a string where a number belongs is rejected before it reaches the model. - The row is a plain list, so the order of values must match the column order used in training. A swapped order raises no error. It produces wrong scores.
What real-time prediction gives you
Real-time prediction suits cases where the input is only known at request time, or where the answer must reflect the latest state. Examples are fraud checks on a payment, search ranking, and recommendations during a session. It also covers new entities that no batch job has seen yet.
The cost is that you now run a service. It needs to stay available, meet a latency target, and handle traffic spikes. A batch job can fail and rerun at night. A failed online call can block a user, so you need timeouts, a fallback response, and monitoring.
Common errors
- Feature order mismatch. Pass columns by name, for example with a DataFrame, when you can. A bare list depends on position.
- Loading the model per request. This makes every call slow. Load once at startup.
- Different feature logic than training. If training computed
monthly_spendas a 30-day average and the service receives a 7-day total, the model sees a different distribution. This is training-serving skew, covered in a later chapter. - Slow feature lookups. The model may run in 2 ms while a database call takes 80 ms. Measure the whole request path, not only the model.
- No timeout. A hung feature store can tie up every worker. Set a timeout on each dependency call.
Summary
Real-time prediction keeps a model loaded in a running service and scores one request per call. It gives fresh, per-request answers. In exchange, you take on latency targets, availability duties, and the need to get features at request time.
Exercise
A teammate's service calls joblib.load("model.joblib") inside the predict function. Predictions are correct but every response takes about 400 ms. What is the likely cause, and what is the fix?
Show answer
The model file is read from disk and deserialized on every request, which dominates the response time. Move joblib.load to module level (or an application startup hook) so the model loads once and each request only runs the forward pass.
Exercise
Your service accepts a list of three numbers and passes it to the model. After a refactor, the order of fields in the client's payload changes, and no errors appear, but scores look wrong. Why, and how would you prevent it?
Show answer
The model expects values in training column order, and a positional list silently maps the wrong values to the wrong features. Prevent it by validating named fields (as with the Pydantic model) and building the row in a fixed, explicit order, or by passing a DataFrame with named columns.