Sub topic 3
Real-time prediction: scoring one request on demand
This chapter covers how real-time (online) prediction works, what the service has to do for each request, and where it tends to fail. It assumes you know basic machine learning vocabulary (training, model, features, prediction). It also assumes you can read Python and know what an HTTP API is. Batch scoring was covered in the previous chapter, and later chapters treat latency, freshness and cost in more detail.
What real-time prediction means
Real-time prediction, also called online prediction, scores one request at the moment it arrives. A caller sends the inputs for one entity, such as a customer, a transaction or a search query. The service computes the prediction and returns it. The caller waits for the answer, so the prediction is part of a larger user-facing or system-facing operation.
The key differences from batch scoring are these:
- Trigger: a request starts the work, not a schedule.
- Unit of work: usually one record, or a handful.
- Caller behavior: the caller blocks until the response arrives or a timeout expires.
- Availability: the service must be up whenever callers need it, not just during a job window.
Typical uses are fraud checks during payment, product recommendations on a page load, and a support-chat model that routes a message while the customer waits.
The request lifecycle
Each request goes through the same steps. Knowing them helps you find where time is spent and where errors enter.
The model is loaded once, when the process starts. Loading a file from disk on every request would add tens or hundreds of milliseconds and gain you nothing. The per-request work is only validation, feature assembly and one call to the model.
A minimal working service
The service below needs a saved model. This short script trains a toy classifier on synthetic data and saves it, so you can run everything that follows. The synthetic labels are made up. The point is the serving code.
import joblib
import numpy as np
from sklearn.linear_model import LogisticRegression
rng = np.random.default_rng(0)
n = 500
X = np.column_stack([
rng.uniform(0, 72, n), # tenure_months
rng.uniform(10, 200, n), # monthly_spend
rng.integers(0, 10, n), # support_tickets
])
y = ((X[:, 2] > 4) | (X[:, 0] < 6)).astype(int)
model = LogisticRegression(max_iter=1000).fit(X, y)
joblib.dump(model, "model.joblib")
print("saved model.joblib")Save the service in a file named service.py. It adds range checks on the inputs and names the feature order explicitly:
import joblib
from fastapi import FastAPI
from pydantic import BaseModel, Field
app = FastAPI()
model = joblib.load("model.joblib")
FEATURE_ORDER = ["tenure_months", "monthly_spend", "support_tickets"]
class Features(BaseModel):
tenure_months: float = Field(ge=0, le=1200)
monthly_spend: float = Field(ge=0)
support_tickets: int = Field(ge=0)
@app.post("/predict")
def predict(features: Features):
values = features.model_dump()
row = [[values[name] for name in FEATURE_ORDER]]
return {"churn_score": float(model.predict_proba(row)[0, 1])}Run it with uvicorn service:app --port 8000, then call it:
curl -s -X POST http://localhost:8000/predict \
-H "Content-Type: application/json" \
-d '{"tenure_months": 3, "monthly_spend": 40.5, "support_tickets": 6}'The response is a JSON object such as {"churn_score": 0.97}. The exact value depends on the toy model.
A few details in this code matter in production:
def, notasync def.predict_probais a blocking CPU call. FastAPI runs plaindefhandlers in a thread pool, so one slow call does not freeze the event loop. If you declared the handlerasync defand called the model inside it, every request would queue behind that call.- Explicit feature order. Scikit-learn models trained on plain arrays do not check column names. If the row is built in a different order than in training, the model still returns a number, and the number is wrong. Building the row from a named list makes the order visible and reviewable.
- Input validation. Pydantic rejects a missing field or a wrong type with a 422 response before the model sees anything. The
Fieldbounds reject values that are clearly impossible, such as negative spend.
Where the features come from
The example above has a convenient property: the caller sends every feature in the request. Real systems often cannot rely on that. A fraud model may need "number of transactions this card made in the last hour", which the caller does not know. The service then has to fetch it, usually from a low-latency store such as a key-value database or an online feature store, keyed by an entity ID.
This changes the request path. The request carries an ID plus some raw context, the service looks up stored features, merges them with the request values, and only then calls the model. Each lookup adds latency and a new way to fail. The later chapters on feature access and training-serving skew cover this in detail. For now, remember that the feature logic used here must produce the same values as the logic used in training.
Latency is a budget
The caller usually has a deadline. A web page might allow 100 ms for all backend work, so the prediction service gets a fraction of that. Think of the time as a budget split across steps:
| Step | Typical contribution |
|---|---|
| Network between caller and service | Fixed overhead, often a few milliseconds |
| Parsing and validating the request | Under 1 ms for small payloads |
| Feature lookups | Often the largest part, since each remote call costs a round trip |
| Model computation | Under 1 ms for a linear model, much more for a large neural network |
| Serializing the response | Under 1 ms |
These figures are rough and vary a lot by system. Measure your own. Two habits help. First, track a high percentile such as p95 or p99, not the average, because a few slow requests are what callers notice. Second, set a timeout on every outgoing call (feature store, database) so one slow dependency cannot hold your threads indefinitely.
Concurrency and scaling
One process handles a limited number of requests at once. To handle more traffic you run several copies of the service behind a load balancer. Because the service keeps no per-request state (the model is read-only after loading), copies are interchangeable and you can add or remove them freely.
Points to watch:
- Memory per copy. Each process loads its own copy of the model. A 2 GB model run in eight worker processes needs about 16 GB, unless the framework shares memory.
- Thread safety. Scikit-learn prediction is generally safe to call from multiple threads. Do not assume this for every library, so check the documentation of whatever you use.
- Warm-up. The first request after startup can be slower, since libraries initialize lazily. Send a dummy prediction at startup, and do not mark the instance healthy until it has succeeded.
- Idle capacity. Instances must be sized for peak traffic, so at quiet times they sit mostly idle. This is a cost difference from batch jobs, which use resources only while they run.
Failure modes and edge cases
A real-time service has to answer something for every request, even when things go wrong. Plan for these cases:
- Missing or stale features. If a lookup returns nothing (a new customer, a cache miss), decide ahead of time what happens. Options are a default value that was also used in training, a simpler model, or an explicit error. Do not let a
Noneslip silently into the model. - Out-of-range inputs. A value far outside the training range may still produce a confident-looking score. Validation bounds catch the worst cases. Monitoring catches the subtler ones.
- Timeouts. If the caller times out at 100 ms and your service takes 150 ms, the work is wasted. Make the service's internal timeouts shorter than the caller's.
- Model deployment. Replacing the model file while the service runs can serve a half-written file or mix versions. Deploy a new version as new instances, shift traffic gradually, and return the model version in logs or responses.
- Dependency outages. If the feature store is down, a fallback such as a default score, a cached last-known score, or a rules-based answer is usually better than a 500 error. The hybrid chapter covers the precompute-with-live-fallback pattern.
When real time is the right choice
Real-time serving fits when the input does not exist until the moment of the request, or when the answer must reflect something that just happened. A fraud check on a payment that is happening now is the standard example. A nightly job cannot score a payment that has not occurred yet.
It is a poor fit when the same predictions could be computed ahead of time and nobody needs them within seconds. In that case you pay for always-on servers, strict latency work and on-call duty without any benefit. The decision chapter at the end of this tutorial turns this into a checklist.
Exercise
A teammate writes the prediction handler as async def predict(...) and calls model.predict_proba(row) directly inside it. Under load, latency for all requests rises sharply even though CPU use is modest. Why can this happen, and what are two ways to fix it?
Show answer
predict_proba is a blocking call. Inside an async def handler it runs on the event loop thread, so while one prediction runs, no other request can make progress. Requests queue behind each other. Fixes: declare the handler with plain def so FastAPI runs it in a thread pool, or keep async def and run the model call in a worker thread or process pool (for example with run_in_threadpool). Running more service instances behind a load balancer also helps, but it does not remove the blocking.
Exercise
The service builds its input row as [[tenure_months, support_tickets, monthly_spend]], but the model was trained with the order tenure_months, monthly_spend, support_tickets. The service returns scores with no errors. Why is this dangerous, and how does the example in this chapter reduce the risk?
Show answer
The model does not know feature names when trained on plain arrays, so it treats each position as the feature it was trained on. Spend and ticket counts get swapped, and the scores are wrong but look valid. Nothing raises an error. The chapter's service defines a single FEATURE_ORDER list and builds the row from it, which makes the order explicit in one place. You can then review it and test it against the order used in training.