Every click, search, and hover on a retailer’s website tells a story about what a shopper wants right now, but feature engineering pipelines, traditionally updated in batches, capture that story after the shopper has left. Databricks Feature Views close this gap by providing near real-time ingestion and transformation of data, allowing models to adapt while shoppers are still browsing. With Feature Views' StreamSource, events from a live stream are turned into fresh features and written to Lakebase, Databricks' online store, where they can be looked up the moment a recommendation is needed. The same events are saved for analysis and model training, and can be combined with slower-moving features updated through batch jobs. The result is recommendations that blend long-term signals with in-the-moment intent, delivered while there's still time to turn interest into a purchase.
Figure 1. The real-time recommendation loop. Each shopper action updates the session's features, the model uses them on the next request, and new recommendations appear while the shopper is still browsing.
A Feature View is a declarative definition of a set of features: where the data comes from, how it is keyed, and how it should be aggregated over time. You define it once, and Databricks uses the same definition to build training data offline and to serve features online. That shared definition is what keeps training and serving consistent.
Every feature view starts with a source, and the source determines how fresh the resulting features can be.
On top of the source, you declare the entity key (for example, a product_id or session_id), a timestamp column, and the aggregations to compute. Aggregations are defined over time windows, such as a rolling window over the current session or a sliding window over several days of product activity.
from datetime import timedelta
from databricks.feature_engineering.entities import (
Feature, StreamSource, AggregationFunction, Count, RollingWindow,
)
# Three-part Unity Catalog name of the Stream (created via fe.create_stream)
STREAM_SOURCE = "my_catalog.my_schema.my_clickstream"
# Specify a data source (StreamSource or DeltaTableSource)
session_source = StreamSource(
full_name=STREAM_SOURCE,
)
# Specify an aggregation type
SESSION_WINDOW = RollingWindow(
window_duration=timedelta(hours=24),
)
# Configure the feature computation
session_event_count_features = Feature(
source=session_source,
entity=["value.user_session"],
timeseries_column="value.event_time",
function=AggregationFunction(Count(input="value.event_type"), SESSION_WINDOW),
name="session_event_count",
)
Feature Views can be registered in Unity Catalog alongside the tables and models that use them. That gives them the same access controls, lineage, and discoverability as the rest of your data and AI assets. A data scientist building a new model can find existing session features instead of rebuilding them, and platform teams can see which models depend on which features.
Streaming feature transformations are enabled by StreamSource, which connects to a stream configured using the Databricks FeatureEngineeringClient’s create_stream method. As events arrive, it does two things with each one. First, it asynchronously appends the raw event to an ingestion Delta table in Unity Catalog, which becomes the offline source for analysis and for building training sets. Second, it computes the Feature View's aggregations and materializes the results to Lakebase for low-latency lookup at inference time.
Because most teams have historical data that predates the stream, create_stream also supports a backfill source. With it, you merge historical events, such as a snapshot exported from your data warehouse, into the same ingestion table. The result is a single table holding both the full history and the live tail of the stream. When building training datasets with StreamSource-derived features, create_training_set triggers the feature computations against the stream’s ingestion table.
Figure 2. Historical and live clickstream events are recorded in a Delta table; streaming aggregates are materialized in Lakebase. Colors show which part of the platform does the work, here and in the diagrams that follow: grey for steps outside Databricks, purple for Feature Views, blue for Delta tables, amber for Lakebase, and green for Model Serving (shown in later diagrams).
Once Feature Views are defined and registered, the same definitions drive every stage of the model lifecycle. Training data is built offline from the full history, while real-time inference reads precomputed features from Lakebase. Materialization is the step that connects the two.
Training. Pass in a DataFrame of entity keys, timestamps, request-time fields, and labels. The FeatureEngineeringClient joins the requested features from each Feature View as of each row's timestamp, producing a complete training dataset without hand-written joins.
from datetime import timedelta
import mlflow
from databricks.feature_engineering import FeatureEngineeringClient
from databricks.feature_engineering.entities import (
Feature, DeltaTableSource, StreamSource, RequestSource, FieldDefinition, ScalarDataType, ColumnSelection, AggregationFunction, Count, LastDistinct, SlidingWindow, RollingWindow,
)
fe = FeatureEngineeringClient()
# Batch: how popular is the product on the page? (7-day views, refreshed hourly).
# For brevity, these features are defined locally. Register them in
# Unity Catalog (fe.register_feature) before materializing them for online serving.
clickstream = DeltaTableSource(
catalog_name="retail", schema_name="recs", table_name="clickstream"
)
product_events_7d = Feature(
name="product_views_7d",
source=clickstream,
entity=["product_id"],
timeseries_column="event_time",
function=AggregationFunction(
operator=Count(input="event_type"),
time_window=SlidingWindow(
window_duration=timedelta(days=7), slide_duration=timedelta(hours=1)
),
),
)
# Streaming: what has this shopper looked at in the last 30 minutes?
session_events = StreamSource(full_name="retail.recs.session_events")
session_recent_products = Feature(
name="session_recent_products",
source=session_events,
entity=["value.user_session"],
timeseries_column="value.event_time",
function=AggregationFunction(
operator=LastDistinct(input="value.product_id", n=10),
time_window=RollingWindow(window_duration=timedelta(minutes=30)),
),
)
# Request-time: context that only exists on this page view (illustrative fields)
page_context = RequestSource(schema=[
FieldDefinition(name="search_query", data_type=ScalarDataType.STRING),
FieldDefinition(name="device_type", data_type=ScalarDataType.STRING),
])
search_query = Feature(name="search_query", source=page_context,
function=ColumnSelection("search_query"))
device_type = Feature(name="device_type", source=page_context,
function=ColumnSelection("device_type"))
features = [product_events_7d, session_recent_products, search_query, device_type]
# One call joins all three cadences, point-in-time, for every labeled interaction.
# label_interactions is the one DataFrame you build yourself: one row
# per product view, holding only keys, a timestamp, request-timefields, and a label.
# It contains no features. create_training_set looks features up for each row
# as of its event_time (see On-the-fly transformations and point-in-time joins).
training_set = fe.create_training_set(
df=labeled_interactions,
features=features,
label="purchased",
)
model = train_recommender(training_set.load_df())
# The feature list travels with the model. To score an observation,
# only user_session, product_id, search_query, and device type are required as inputs.
fe.log_model(
model=model,
artifact_path="recommender",
flavor=mlflow.pyfunc,
training_set=training_set,
registered_model_name="retail.recs.session_recommender",
)
Once the model is trained, logging it with the FeatureEngineeringClient and the training set packages the model with its feature specification: which features it uses, which entity keys look them up, and which request-time fields it expects. That specification travels with the model through registration in Unity Catalog and deployment to Model Serving. It is what lets the endpoint look up features automatically, and it records lineage from each feature to every model that depends on it. A model logged with plain MLflow, without the FeatureEngineeringClient, would need the application to assemble and pass every feature itself.
Materializing features to Lakebase. Real-time inference can't afford to compute features at request time. A shopper won't wait while session activity or a seven-day aggregate is recalculated from raw clickstream data. Instead, features are materialized: precomputed and written to online tables in Lakebase, Databricks' managed Postgres database built for low-latency reads. Materialization is configured per feature with materialize_features, which takes an online store configuration and a trigger that sets the update cadence. StreamingMode keeps StreamSource features continuously up to date as events arrive. A CronSchedule or TableTrigger refreshes batch features on a schedule or whenever the source table changes. Because features must be registered in Unity Catalog before they can be materialized, the online tables inherit the same governance and lineage as the rest of your data.
Real-time inference. Once features are in Lakebase, they can be served in two ways. A Feature Serving endpoint returns feature values directly over a REST API, which is useful when an application needs features without a model, such as showing "recently viewed" items on a page. Alternatively, a model logged with the FeatureEngineeringClient can be deployed to a Model Serving endpoint. The endpoint receives only the entity keys and any request-time fields, retrieves the latest streaming and batch features from Lakebase, and passes the complete feature set to the model, all within a single request. Whether a value was refreshed on a schedule, updated seconds ago from the stream, or sent with the request, the model sees it computed exactly as it was during training.
Training a recommender means pairing each historical interaction with the features that were known at that moment, and nothing more. If a training row for a 12:00 p.m. click includes session activity from 12:05 p.m., the model learns from information it will never have in production. This is called data leakage. It is one of the most common reasons a model looks strong in offline evaluation and then underperforms once it is live. With streaming features the risk is especially high, because session features change with every click, and a few minutes of future activity can quietly leak into the training data.
Point-in-time joins. Feature Views prevent leakage by joining features to each training row as of that row's timestamp. When you call create_training_set, every feature is looked up at the moment of the event it is being paired with. For a 12:00 p.m. click, session features include only the activity up to 12:00 p.m., and seven-day product aggregates cover only the seven days leading up to it. Events after that moment are excluded.
Figure 3. Point-in-time joins calculate features separately for each observation based on its provided timestamp before joining features together across all sources.
One row, many entity keys. Real training data combines features about different things. A single row describes a shopper, in a session, looking at a product. Each input row carries every entity key the features need, such as session_id for session features and product_id for product attributes and aggregates, along with a single timestamp. The FeatureEngineeringClient looks up each feature by its own key, all as of that same moment. Request-time fields, such as the shopper's search query, are passed in on the row as they were at the time. The result is one joined dataset, with no hand-written joins and no chance of pairing a feature with the wrong point in time.
Why on the fly matters. The traditional alternative is to precompute feature tables on a schedule and join them to training data. Each snapshot, however, reflects the moment it was computed, not the moment of each training example. To build a correct dataset for a different period, you either recompute the features or accept some leakage. Feature Views avoid this by computing aggregations on the fly from their sources whenever a training set is built.
Splits you can change at will. Because each row carries its own timestamp and every feature is computed for that moment, the training, validation, and test datasets are defined entirely by the input DataFrame you pass in. Choosing a split means choosing which event times go into which DataFrame. To try a longer history, a new holdout period, or a different validation window, you filter the input differently and call create_training_set again. Nothing needs to be recomputed, copied, or versioned ahead of time, and each dataset contains only the information that was available when its events occurred.
With features registered and materialized and the model deployed, the system is ready to respond to shoppers in real time.
Each shopper action is published to a streaming platform such as Kafka or Kinesis as a clickstream event. StreamSource picks it up, updates the session's rolling aggregates in Lakebase, and appends the raw event to the ingestion Delta table. Batch features, such as product attributes and longer-running product aggregates, refresh on their own schedule alongside it.
When the shopper's next page loads, the website calls the Model Serving endpoint with the session id, the current product id, and any request-time context configured as RequestSource features. Using the feature specification logged with the model, the endpoint looks up the session's latest features and the relevant product features from Lakebase, combines them with the request fields, and passes the complete feature set to the model. Fresh recommendations are returned to the website before the page finishes loading. Every click feeds the next recommendation, so suggestions sharpen as the session unfolds, and the application code never has to assemble a single feature itself.
Figure 4. A model serving endpoint retrieves fresh feature values from multiple sources after each web request.
The open-source e-commerce clickstream dataset from a large multi-category online store gives a realistic basis for this example. It contains over 100 million user events from October and November 2019, and each event records the event time, event type (view, cart, or purchase), product, category, brand, price, user, and session ID. That is everything needed for all three kinds of features in this post: product attributes from the catalog, product aggregates (such as popularity) over a number of days, and the rolling activity within each shopper's session. To prototype a Feature Views pipeline with this dataset, most of the history can be loaded as a backfill and the final day replayed through Kafka as a live stream. As a simulated shopper browses, session features update in Lakebase and the recommendations change with them.
In an example architecture built on the dataset, session features come from a StreamSource on a Kafka topic, which computes rolling aggregates over each shopper's current session and writes them to Lakebase as events arrive. Alongside it, a DeltaTableSource reads a separate product-level Delta table, which holds attributes such as category and brand that rarely change and suit batch updates. Finally, the ingestion Delta table, which holds both the backfilled history and newly streamed events, serves as the basis for a second DeltaTableSource that computes rolling product-level aggregates, such as views and purchases over the past seven days. For another way to handle longer windows, see SawtoothWindow aggregations, which combine batch and streaming updates. Together, these three sources show features with different update cadences and aggregation types being processed and served side by side.
Figure 5. The dataset is divided into multiple Feature View sources, each updating online tables in Lakbase at different cadences.
With the features defined, building training, evaluation, and test datasets takes very little work. Because Feature Views compute every feature as of each row's timestamp, each dataset is simply a filter on event time followed by a call to create_training_set: the earliest period for training, the period after it for evaluation, and the most recent for testing. Trying a different split means changing a date filter and nothing else.
These datasets feed a two-tower model trained on Databricks AI Runtime, a serverless GPU compute offering intended for deep learning workloads. You can use AI Runtime to train and fine-tune custom models using your favorite frameworks and get state-of-the-art efficiency, performance, and quality. Since it has all the necessary dependencies pre-installed, data scientists can start training right away. As the name suggests, a two-tower model is made of two neural networks trained side by side. The query tower turns a shopper's context into an embedding. That context includes the session features from StreamSource, such as recently viewed products and categories, plus request-time fields. The item tower turns each product's attributes into an embedding in the same space, using catalog fields like category, brand, and price along with batch features like popularity over the past week. During training, the model learns to place each session close to the products the shopper went on to view, add to cart, or purchase, and far from the products they ignored. This separation makes two-tower models well suited to real-time retail: item embeddings can be computed ahead of time and indexed, and at inference, only the query tower runs on the fresh session features.
Item embeddings for all products are stored in a Databricks AI Search index, which stays in sync with the product embedding Delta table as the catalog changes. The query tower is wrapped in a custom pyfunc model, logged to an MLflow experiment with the feature engineering client, registered to Unity Catalog, and deployed to a Model Serving endpoint in a few clicks. Because the model was logged with its feature specification, the website only needs to send a session ID, the current product ID, and any request-time fields. The endpoint retrieves the latest session and product features from Lakebase, the query tower turns them into an embedding of the shopper's current intent, and a nearest-neighbor query against the AI Search index returns the best-matching products.
Figure 6. The end-to-end inference flow; a custom inference workflow is deployed through an MLflow pyfunc model. The products returned best match what the shopper is looking for right now.
Every click tells a story about what a shopper wants right now, and with Feature Views and StreamSource, retailers no longer have to wait until the shopper has left to hear it. A single set of feature definitions now covers the full lifecycle. The same features that build point-in-time-correct training data are materialized to Lakebase, updated continuously from the stream, and looked up automatically by the deployed model. Batch, streaming, and request-time signals reach every prediction without custom pipelines or application code. Recommendations are only the beginning. The same pattern applies anywhere in-session behavior should shape the next decision: re-ranking search results, surfacing timely promotions, or stepping in before a cart is abandoned. Try it yourself on your own data, or download the open-source e-commerce dataset and build a minimum viable product. Leverage Databricks Genie Code and its built-in skills for Feature Views to assist with prototyping an end-to-end implementation.
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.