Sub topic 15
Request-time transformations with on-demand feature views
This chapter assumes you have defined an entity, a data source and a FeatureView as in earlier chapters. It also assumes you have run feast apply, and that you know how get_historical_features and get_online_features differ. It adds a way to compute features at read time, from stored features and from values that only exist at request time.
The problem: features that cannot be precomputed
A regular feature view reads values from a source, and materialization copies them to the online store. That works when a feature depends only on stored data. Some features do not:
- A value arrives with the request, such as the surge multiplier of the trip being priced or the user's current location.
- A value combines a stored feature with a request value, such as a stored conversion rate scaled by that multiplier.
You cannot precompute these in a batch job, because the request value is unknown until inference time. You could compute them in the model service, but then training code and serving code each carry their own copy of the formula. That is a source of training-serving skew.
An on-demand feature view (ODFV) is a feature view whose values are computed by a Python function each time features are requested. Feast runs the same function when you build a training set and when you serve online, so the logic is defined once.
How it works
An ODFV has three parts:
- Sources. These are feature views whose stored values are inputs, and
RequestSourceobjects that describe values supplied by the caller. - A schema. It declares the name and type of each output feature.
- A transformation function. It receives the input columns and returns the output columns.
Nothing is stored for an ODFV. Materialization skips it, because there is nothing to copy. At read time Feast first fetches the input features from the online or offline store. It then adds the request values you supplied, and then calls your function.
Defining an on-demand feature view
This code extends the repository file from earlier chapters. It reuses driver_stats_fv and adds a request source and one on-demand feature view.
import pandas as pd
from feast import Field, RequestSource
from feast.on_demand_feature_view import on_demand_feature_view
from feast.types import Float64
# Values the caller must supply with every request.
trip_request = RequestSource(
name="trip_request",
schema=[Field(name="surge_multiplier", dtype=Float64)],
)
@on_demand_feature_view(
sources=[driver_stats_fv, trip_request],
schema=[Field(name="adjusted_conv_rate", dtype=Float64)],
mode="pandas",
)
def adjusted_conv_rate(inputs: pd.DataFrame) -> pd.DataFrame:
out = pd.DataFrame()
out["adjusted_conv_rate"] = inputs["conv_rate"] * inputs["surge_multiplier"]
return outKey points:
- The decorated function's name becomes the feature view name, here
adjusted_conv_rate. inputsis a DataFrame holding the columns of every source. It hasconv_ratefromdriver_stats_fvandsurge_multiplierfrom the request.- The returned DataFrame must contain exactly the columns declared in
schema, with compatible types. - Run
feast applyafter adding it. The registry stores the definition and its sources, so Feast knows which stored features to fetch.
Using it online
At inference, pass the request values in the entity rows next to the entity key. Reference the ODFV like any other view, as view_name:feature_name.
from feast import FeatureStore
store = FeatureStore(repo_path=".")
result = store.get_online_features(
features=[
"driver_hourly_stats:acc_rate",
"adjusted_conv_rate:adjusted_conv_rate",
],
entity_rows=[{"driver_id": 1001, "surge_multiplier": 1.4}],
).to_dict()Feast reads conv_rate for driver 1001 from the online store. It needs that column as an input even though you did not request it directly. It then runs your function and returns the requested features, stored and computed together. The stored inputs must already be materialized, or conv_rate comes back as null and the computed value is null too.
Using it for training
For training, the entity DataFrame carries the request column as well as the entity key and timestamp:
from datetime import datetime
import pandas as pd
from feast import FeatureStore
store = FeatureStore(repo_path=".")
entity_df = pd.DataFrame(
{
"driver_id": [1001, 1002],
"event_timestamp": [datetime(2025, 1, 1, 12, 0), datetime(2025, 1, 1, 13, 0)],
"surge_multiplier": [1.4, 1.0],
}
)
training_df = store.get_historical_features(
entity_df=entity_df,
features=[
"driver_hourly_stats:acc_rate",
"adjusted_conv_rate:adjusted_conv_rate",
],
).to_df()Feast first performs the point-in-time join for the stored inputs. It then applies the same function to each joined row. The request values you log at serving time become a column in the entity DataFrame, so training sees what serving saw.
Pandas mode and Python mode
The mode argument selects how the function receives data.
| Mode | Function input | Function output | Typical use |
|---|---|---|---|
| `pandas` | A DataFrame of many rows | A DataFrame | Batch training sets, vectorized math |
| `python` | A dict mapping column names to lists | A dict of lists | Low-latency online calls with few rows |
Pandas has per-call overhead that is noticeable when you score one entity at a time. If your online path is latency-sensitive and the logic is simple arithmetic, python mode is often faster. Check which modes your installed Feast version supports before relying on one. This API has changed across releases.
Common errors and gotchas
- Missing request field. If a request value is absent from
entity_rowsor fromentity_df, retrieval raises an error naming the missing field. Fix the caller and do not add a default inside the function. - Schema mismatch. Returning a column not in
schema, or omitting one that is, fails at retrieval. Keep the function and schema edited together. - Added latency. The function runs inside every online request. Avoid network calls, file reads and heavy computation in it. If a feature is expensive and depends only on stored data, compute it in a batch pipeline and store it as a regular feature.
- Hidden dependency on stored data. The ODFV is only as fresh as its inputs. Its inputs obey the same TTL and materialization schedule as any feature view, so staleness in
conv_rateshows up inadjusted_conv_rate. - Non-deterministic logic. Do not call the current time or random numbers inside the function. Training would then not reproduce what serving produced.
- Version drift. If you change the function body, old training sets no longer match what the model sees online. Treat a changed formula as a new feature, for example by creating
adjusted_conv_rate_v2.
When to choose an ODFV
| Situation | Better choice |
|---|---|
| Feature depends on a value only known at request time | On-demand feature view |
| Feature derives from stored features with cheap arithmetic | On-demand feature view |
| Feature is expensive and depends only on stored data | Batch pipeline plus a regular feature view |
| Feature must update within seconds of an event | Push ingestion, covered next |
Exercise
A model needs trip_cost_estimate, defined as avg_daily_trips * price_per_km, where price_per_km is sent by the app with each request and avg_daily_trips is a stored feature. Sketch the objects you would define, and say what the caller must pass when building a training set.
Show answer
Define a RequestSource (for example price_request) with a Float64 field price_per_km. Define an on-demand feature view with sources [driver_stats_fv, price_request], a schema containing trip_cost_estimate, and a function that multiplies inputs["avg_daily_trips"] by inputs["price_per_km"]. Run feast apply. When calling get_historical_features, the entity DataFrame needs the entity key (driver_id), event_timestamp, and a price_per_km column with the values that were sent at request time. Online, pass price_per_km in each entity row.
Exercise
Online, adjusted_conv_rate comes back null for driver 1001 even though the request included surge_multiplier. What is the most likely cause, and how do you check it?
Show answer
The stored input conv_rate is probably missing from the online store, either because materialization has not run for that driver or because its values are older than the TTL. Request driver_hourly_stats:conv_rate directly with get_online_features. If that is null, run feast materialize-incremental and recheck.