Sub topic 6
Where features come from at prediction time
A trained model only accepts features, which are the numeric inputs it learned from. At prediction time you have to build those inputs from raw data, and where that data lives differs a lot between batch and real-time serving. This chapter covers the two places features come from, how each serving mode reaches them, and the errors that follow from getting it wrong.
This chapter assumes you know basic machine learning vocabulary (training, model, features, prediction), can read Python, and have a rough idea of what an HTTP API and a scheduled job are. It builds on the batch and real-time chapters. The next chapter covers training-serving skew in depth. Here it appears only as the main risk.
Offline and online features
Features are stored and read in two different ways.
- Offline features are read from a data warehouse, data lake, or files. Reads are slow per request but efficient for millions of rows at once. Typical sources are Parquet files, SQL tables, and warehouse queries.
- Online features are read from a low-latency store, such as a key-value database or in-memory cache. Each read fetches one entity's values by key, usually in a few milliseconds. The store holds only the latest value per key.
| Property | Offline store | Online store |
|---|---|---|
| Typical access | Scan many rows | Look up one key |
| Latency per read | Seconds to minutes for a query | Milliseconds |
| History | Full history, with timestamps | Usually latest value only |
| Typical size | Terabytes | Gigabytes, only active entities |
| Used by | Training, batch scoring | Real-time scoring |
Training always uses offline data, because it needs history. The serving mode decides which store you read from at prediction time.
How each serving mode gets features
Batch scoring reads from the offline store. The job runs on a schedule, so it can afford a heavy query that joins several tables and computes aggregates over the whole customer base. The first example in this tutorial does this in a small way: it reads a Parquet snapshot and selects three columns.
import pandas as pd
customers = pd.read_parquet("customers_2026-11-28.parquet")
feature_columns = ["tenure_months", "monthly_spend", "support_tickets"]
features = customers[feature_columns]
print(features.describe())Real-time scoring cannot run a warehouse query inside a request that must answer in tens of milliseconds. It gets features in one of three ways:
- The caller sends them in the request. This is the simplest option, and it is what the FastAPI example does. The caller must know every feature and compute it the same way the training pipeline did.
- The service looks them up by key. The request carries only an ID such as
customer_id. The service fetches precomputed features from the online store and then calls the model. - The service computes them from the raw request. Examples are the length of a text field, the hour of day, or the ratio of two numbers in the payload.
Real systems often combine all three. A fraud check might take the transaction amount from the request, look up the customer's 30-day average spend in the online store, and compute the ratio between them on the fly.
The arrow from the offline store to the online store matters. The online store is normally filled from the same data that feeds training, through a scheduled or streaming job. If that load job runs late, online features go stale.
A real-time lookup in code
This example shows option 2. It uses a dictionary to stand in for an online store, so it runs without extra infrastructure. In production you would replace the dictionary with a call to a key-value database.
import joblib
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
app = FastAPI()
model = joblib.load("model.joblib")
FEATURE_ORDER = ["tenure_months", "monthly_spend", "support_tickets"]
# Stand-in for an online feature store, keyed by customer_id.
online_store = {
"c-1001": {"tenure_months": 14.0, "monthly_spend": 52.5, "support_tickets": 1},
"c-1002": {"tenure_months": 3.0, "monthly_spend": 19.0, "support_tickets": 4},
}
class Request(BaseModel):
customer_id: str
@app.post("/predict")
def predict(request: Request):
stored = online_store.get(request.customer_id)
if stored is None:
raise HTTPException(status_code=404, detail="No features for this customer")
row = [[stored[name] for name in FEATURE_ORDER]]
return {"churn_score": float(model.predict_proba(row)[0, 1])}Two details deserve attention. First, FEATURE_ORDER fixes the column order explicitly, because a model trained on a DataFrame will silently accept a list in the wrong order. Second, the service returns a clear 404 when features are missing instead of guessing. How to handle missing features is a design choice, and the section on edge cases below covers it.
Point-in-time correctness
Training data has history, so every training row must use feature values as they were at the moment of the event, not as they are today. If you label a customer who churned in March and attach their December support ticket count, the model sees information from the future. This is called leakage. It makes offline evaluation look better than production will ever be.
The fix is a point-in-time join: for each labeled row with timestamp t, take the latest feature value with a timestamp at or before t. Pandas provides merge_asof for this.
import pandas as pd
labels = pd.DataFrame(
{
"customer_id": ["a", "a", "b"],
"event_time": pd.to_datetime(["2026-03-01", "2026-06-01", "2026-04-15"]),
"churned": [0, 1, 0],
}
).sort_values("event_time")
feature_history = pd.DataFrame(
{
"customer_id": ["a", "a", "b"],
"feature_time": pd.to_datetime(["2026-02-20", "2026-05-10", "2026-04-01"]),
"support_tickets": [0, 3, 1],
}
).sort_values("feature_time")
training = pd.merge_asof(
labels,
feature_history,
left_on="event_time",
right_on="feature_time",
by="customer_id",
)
print(training)The March row for customer a gets 0 tickets, from 20 February. The June row gets 3 tickets, from 10 May. Neither row sees a value recorded after its event.
Batch scoring has a mirror-image rule. A nightly job scores "as of" the snapshot time, so the snapshot must be complete at that time. A job that starts before the upstream table finishes loading will score partial data and not raise any error.
Where the two paths diverge
The same feature, such as support_tickets in the last 30 days, is often computed in three places:
- a SQL query that builds the training set,
- a SQL or Spark job that fills the online store,
- code in the service that handles requests.
Each copy can differ in small ways. One may count calendar days and another rolling 720 hours. One may include closed tickets and another may not. One may fill missing values with 0 and another with the mean. The model was trained on one definition and served with another, and nothing fails. Predictions are just worse. This is training-serving skew, and the next chapter covers how to prevent it.
The structural defenses are worth knowing now:
- Write each feature definition once and reuse it for training, batch, and online loading. A feature store is a system built for this.
- Share the transformation code as a library that the training job and the service both import.
- Log the features the service actually used at prediction time. Later you can compare them with what the offline pipeline would have produced for the same entity and time.
Edge cases and common errors
- Missing keys. A new customer has no row in the online store. Choose a policy: return an error, use defaults that match what training used for missing values, or fall back to a model that needs fewer features. The hybrid pattern chapter covers fallbacks.
- Stale online values. A key may exist but hold a value from days ago because the load job failed. Store a timestamp with each value and check its age before use.
- Feature order or type drift. Passing a list in the wrong order, or an integer where training saw a float, can change results without raising an error. Use named columns or an explicit order constant.
- Features that exist only offline. A 90-day rolling aggregate may be too expensive to compute per request. Either precompute it into the online store, or drop the feature from the real-time model. Do not approximate it in the service with a different formula.
- Latency from lookups. Each online read adds network time. A model that needs ten lookups per request can spend more time fetching features than predicting. Fetch in one batched call where the store allows it.
- Batch jobs reading online data. Scoring millions of rows through a key-value store one key at a time is slow and can overload the store. Batch jobs should read the offline copy.
Choosing based on feature access
Feature access often decides the serving mode before latency does. Ask:
- Which features does the model need, and how fresh must each be?
- Can each one be computed in the request path, or is it a slow aggregate?
- Does an online store with these features already exist, or would you have to build and operate one?
If the strongest features are heavy aggregates and nobody has built an online store, batch scoring is the cheaper path. If the value depends on information that exists only at request time, such as the contents of a cart, real-time scoring is required.
Exercise
A real-time churn service receives only a customer_id, looks up three features in an online store, and calls the model. Last week the job that loads the online store failed for four days. The service kept returning scores with no errors. What went wrong, and what two changes would let the service detect this?
Show answer
The service read stale values. The keys still existed, so lookups succeeded, but the values were four days old, and the model scored customers on outdated data. Two changes: store a timestamp with each feature value and reject or flag values older than an agreed age, and alert on the load job's failure or on the age of the newest write in the online store. Logging the feature values used for each prediction also lets you spot the drift afterward.
Exercise
You build training data by joining each labeled event to the customer's current feature row from the warehouse. Offline accuracy is excellent, but production accuracy is much lower. Name the likely cause and the technique that fixes it.
Show answer
The join leaks future information. Current feature values include events that happened after the label's timestamp, so the model sees data it will not have at prediction time. Use a point-in-time join, such as pandas merge_asof, which picks for each event the latest feature value recorded at or before the event time.