Sub topic 10
Prevention: feature stores and a single feature definition
This chapter assumes you have read the earlier chapters on code skew and point-in-time correctness. It also assumes you can read pandas code and know the difference between a batch job and an online API. It covers what a feature store is, which skew causes it removes, and which ones it leaves in place.
The problem a feature store addresses
Sharing a transformation function between training and serving works well for one model owned by one team. Trouble starts when several models and teams reuse the same features. Each team copies the logic into its own notebook and service, and the copies drift apart. Training data comes from a warehouse and serving data comes from a key-value lookup, so each path ends up with its own code, defaults, and timestamps.
A feature store is a system that treats a feature as a managed, named object. It has one definition, one computation, and two ways to read the result. Most feature stores share the same building blocks:
- Entity: the thing a feature describes, such as
user_id. - Feature definition: the code or query that computes a feature from raw data, plus its data types, window, and default value.
- Offline store: historical feature values with timestamps, usually in a warehouse or data lake. Training reads from here.
- Online store: the latest value per entity in a low-latency key-value database. Serving reads from here.
- Materialization: the job that computes features and writes them to the online store, and also to the offline store if it is not already there.
- Registry: the catalog of definitions, so teams find and reuse features instead of rewriting them.
Feast, Tecton, Databricks Feature Store, SageMaker Feature Store, and Vertex AI Feature Store follow this model. Their APIs differ, but the idea is the same.
What "single definition" removes
A feature store attacks three of the causes covered earlier.
| Cause of skew | How the feature store helps |
|---|---|
| Same feature written twice | Both paths run the one registered definition. |
| Different missing-value rules | The default value is part of the definition, not of each consumer. |
| Time leakage in training sets | The offline retrieval API joins on timestamps, so each label gets only values that existed at its time. |
The point-in-time join is the same idea as the merge_asof example earlier, applied at scale. You give the store a table of entity keys and label timestamps. It returns, for each row, the latest feature value at or before that timestamp. You do not write the join yourself, so you cannot get the direction wrong.
A minimal sketch of the pattern
You do not need a vendor product to see the pattern. The code below is a small, runnable stand-in. It has one definition with its window and default, an offline retrieval function that respects time, and a materialization step that fills an online store using the same function.
import pandas as pd
WINDOW = pd.Timedelta(days=30)
DEFAULTS = {"logins_30d": 0} # the missing-value rule lives with the definition
def compute_logins_30d(events: pd.DataFrame, user_id: int, as_of: pd.Timestamp) -> int:
"""The single definition: logins in the 30 days up to and including as_of."""
mask = (
(events["user_id"] == user_id)
& (events["event_time"] <= as_of)
& (events["event_time"] > as_of - WINDOW)
)
return int(mask.sum())
def get_historical_features(labels: pd.DataFrame, events: pd.DataFrame) -> pd.DataFrame:
"""Offline path: each label row gets the value as of its own label_time."""
out = labels.copy()
out["logins_30d"] = [
compute_logins_30d(events, row.user_id, row.label_time)
for row in labels.itertuples()
]
return out
def materialize(events: pd.DataFrame, user_ids, as_of: pd.Timestamp) -> dict:
"""Write the latest value per entity to the online store (a dict here)."""
return {
uid: {"logins_30d": compute_logins_30d(events, uid, as_of)}
for uid in user_ids
}
def get_online_features(store: dict, user_id: int) -> dict:
"""Online path: look up the stored value, falling back to the shared default."""
return {**DEFAULTS, **store.get(user_id, {})}
events = pd.DataFrame({
"user_id": [1, 1, 1, 1, 1],
"event_time": pd.to_datetime(
["2025-12-20", "2026-01-05", "2026-01-12", "2026-01-18", "2026-01-28"]
),
})
labels = pd.DataFrame({
"user_id": [1, 1],
"label_time": pd.to_datetime(["2026-01-10", "2026-01-20"]),
"churned": [0, 1],
})
print(get_historical_features(labels, events))
store = materialize(events, [1], pd.Timestamp("2026-01-31"))
print(get_online_features(store, 1)) # {'logins_30d': 4}
print(get_online_features(store, 2)) # unseen user -> {'logins_30d': 0}The two training rows get 2 and 3, because each is computed as of its own label time. The online lookup returns 4, because it is computed as of the materialization time. The default of 0 for an unseen user is defined once and used by the online path. A real store would also apply the same default when it builds a training set.
What a feature store does not fix
A feature store reduces skew, but it does not remove it. These failure modes remain, and each one needs its own check.
- Staleness. The online store holds the value from the last materialization run. If the job runs hourly but training assumed fresh values, the model sees older data in production than it saw in training. Set a time-to-live (TTL), which is the maximum age at which a value counts as valid. Monitor materialization lag as a metric.
- Backfill versus live computation. Offline values may be backfilled from a warehouse with different late-arriving data than the live stream. A feature can have one definition on paper and still be computed from two pipelines, one batch and one streaming. If a vendor lets you write the batch and streaming versions separately, you have the duplication problem again.
- Request-time features. Some inputs exist only inside the request, such as the cart contents or the time since the last click. These cannot come from a precomputed store. They need an on-demand transformation, and that code must be the same function used when building the training set.
- Features outside the store. If the model also takes features that bypass the store, those still need shared code and bundled preprocessing from the earlier chapters.
- Schema changes. Changing a definition changes every consumer. Version features and retrain models that depend on the old version before you retire it.
Decision criteria
A feature store adds infrastructure, operating cost, and a learning curve. Use these questions to decide whether it is worth it.
- Do several models share features? If so, a registry and a single definition prevent each team from rewriting the logic.
- Do you need low-latency lookups of aggregated history? Features like "purchases in the last 30 days" are costly to compute inside a request, so an online store makes sense.
- Is point-in-time correctness hard to get right by hand? Many time-windowed features across many label tables increase the risk of leakage.
- Is one model served from request data alone? In that case a bundled pipeline from the previous chapter is simpler, and a store is probably unnecessary.
A reasonable path is to start with shared code and a bundled pipeline. Adopt a store when you see repeated feature code across projects or when you build time-windowed aggregates that you cannot compute at request time.
Practical checklist
- Register each feature with its entity, window, data type, default, and owner.
- Build every training set through the store's historical retrieval API, never a hand-written join.
- Record the feature definition version with the model artifact, so you can tell later which definition produced the training data.
- Alert on materialization failures and on online-store age, not only on model metrics.
- Keep the next step in mind: a store gives you one definition, but you still verify that both paths return the same values. The next chapter covers parity tests for that.
Exercise
A team defines purchases_7d once in a feature store. Training sets come from the offline store with a point-in-time join. In production, the model's accuracy still falls and the online values for purchases_7d are on average lower than the training values. Give two plausible causes that the single definition does not rule out, and one check for each.
Show answer
First, staleness: the materialization job may run late or fail, so the online store holds values older than those used in training. Check the age of the stored values (current time minus the value's timestamp) and the job's success history, and compare against the TTL. Second, a data-source difference: the online path may be fed by a streaming pipeline that misses late-arriving or filtered events that the batch backfill includes, so counts come out lower. Check by replaying the same raw events through both pipelines and comparing the resulting purchases_7d values. Missing-entity defaults are a third candidate: look at how many online lookups fall back to the default.