Sub topic 3
Building an Online Prediction Service
Assume you know basic machine learning, Python, HTTP APIs, and scheduled jobs. An online prediction service receives a request, computes or validates its features, runs the model, and returns a prediction before the request times out.
Building the service
Load the model once when the service starts. Each request should use the same feature names, order, types, and preprocessing steps used during training.
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,
]]
score = model.predict_proba(row)[0, 1]
return {"churn_score": float(score)}The service should validate input, set a timeout, and avoid loading the model for every request. In production, put it behind authentication, logging, and a health check.
Between the two: micro-batch and near-real-time
A micro-batch job collects records for a short interval, such as one minute, scores them together, and publishes the results. It reduces per-record overhead while keeping predictions reasonably fresh. Event-driven systems can use the same pattern by buffering messages until a size or time limit is reached.
Hybrid patterns: precompute with live fallback
A hybrid design stores regular batch scores for existing records. If a record has no stored score, the application calls the live model.
def get_score(customer_id, precomputed, live_predict, features_for):
score = precomputed.get(customer_id)
if score is not None:
return score, "batch"
return live_predict(features_for(customer_id)), "realtime"This pattern lowers online load but requires clear rules for score expiration and fallback errors.
Monitoring and handling failures
Monitor request latency, error rate, traffic, input validation failures, missing features, and prediction distributions. Also record the model version and feature timestamp with each result. Return a controlled error when the model or feature store is unavailable. Do not silently substitute a misleading prediction.
Choosing between batch and real time
Ask these questions:
- Must the prediction affect the current request?
- How fresh must the features be?
- Can the system tolerate a scheduled delay?
- Is request traffic steady enough to keep an online service utilized?
- Can the team operate an always-on service and its dependencies?
Choose batch for large, predictable workloads where hourly or daily freshness is sufficient. Choose real time when a user action requires an immediate decision. Choose micro-batch or hybrid designs when the requirements fall between those cases.
Exercise
A daily marketing list needs churn scores for ten million customers. Should it use an online request for every customer?
Show answer
No. Use batch scoring unless the business requires scores based on events that happened immediately before each message.