Real-Time Feature Store and Feature Engineering with Streaming SQL

Real-Time Feature Store and Feature Engineering with Streaming SQL

·

Updated

·

16 min read

A real-time feature store computes machine learning features from live event streams and database changes, stores the results, and serves them to models within seconds of the underlying data changing. This guide builds one on RisingWave, a PostgreSQL-compatible streaming database, with SQL materialized views as the single feature definition for both training and inference. It covers Kafka and CDC sources, the common feature patterns, serving over the PostgreSQL protocol, point-in-time correctness, and continuous feature drift monitoring.

The Feature Store Problem

Every production ML system hits the same wall: getting fresh features to models fast enough to matter. You trained a fraud model on features computed from the last 30 minutes of behavior, and in production your feature store refreshes hourly. A fraudster has a 60-minute window.

Feature stores exist because teams kept solving the same problems: data scientists wrote feature logic in Python notebooks for training, and engineers rewrote it in Java or Scala for serving. A feature store manages three things: computation (aggregations, joins, encodings), storage (an offline store for training and an online store for inference), and serving (low-latency delivery at high throughput).

The traditional architecture splits those across systems. Airflow and Spark compute features into a warehouse; a separate path materializes them into Redis; the model reads Redis. That design has two structural costs:

  • Training/serving skew. Spark computes features one way at training time, and a Python microservice or Redis precomputation computes them another way at serving time. The implementations drift. The gap is usually 1 to 3 percent in feature values, enough for the model to underperform its offline benchmark, and it is silent until someone investigates a production incident.
  • Staleness. If the batch job runs hourly, every feature is up to 60 minutes old. For fraud, risk, and recommendations, the most predictive signals have a half-life measured in minutes.

Feast handles registration, serving, and point-in-time joins well but does not compute features; you still run Spark or dbt to fill its online store. Tecton covers more of the pipeline but relies on microbatch Spark with minutes of minimum latency. Redis plus batch jobs is what most teams actually run: fast lookups, no compute, no freshness.

Why Streaming SQL Collapses the Stack

A streaming database handles all three feature store responsibilities from one SQL interface. Feature computation is a CREATE MATERIALIZED VIEW that RisingWave updates incrementally as events arrive. Feature storage is the view itself, persisted to S3-backed state. Feature serving is the PostgreSQL wire protocol, so psycopg2, SQLAlchemy, JDBC, and any ML serving framework read features with a normal query.

There is one definition of each feature, in SQL, running continuously. The same SQL runs over the historical event log to produce training data, which removes training/serving skew at the architecture level rather than by discipline. RisingWave is open source under Apache 2.0, written in Rust, and separates compute from S3 storage, so feature state for millions of entities is not bounded by memory.

Sources: Kafka Events and Database CDC

Application events typically arrive through Kafka. Your database is often the richer source: an order row that moves from pending to shipped to returned tells a fuller story than a single "order placed" event, and it includes the corrections and refunds that event streams miss. RisingWave reads PostgreSQL and MySQL replication logs directly, with no Debezium or Kafka Connect in between.

CREATE SOURCE user_events (
    event_id        BIGINT,
    user_id         BIGINT,
    session_id      VARCHAR,
    event_type      VARCHAR,       -- 'view', 'click', 'add_to_cart', 'purchase'
    item_id         BIGINT,
    category        VARCHAR,
    revenue         NUMERIC(10,2),
    duration_seconds INT,
    event_time      TIMESTAMPTZ
) WITH (
    connector = 'kafka',
    topic = 'user-events',
    properties.bootstrap.server = 'kafka:9092',
    scan.startup.mode = 'latest'
) FORMAT PLAIN ENCODE JSON;

For PostgreSQL CDC, enable logical replication on the source (wal_level = logical, then a publication for the tables you want), and map each table in RisingWave:

CREATE SOURCE pg_source WITH (
    connector = 'postgres-cdc',
    hostname = 'db-host', port = '5432',
    username = 'replication_user', password = 'secure_password',
    database.name = 'production',
    slot.name = 'risingwave_features',
    publication.name = 'features_publication'
);

CREATE TABLE orders (
    order_id     INT PRIMARY KEY,
    customer_id  INT,
    order_total  DECIMAL,
    status       VARCHAR,
    created_at   TIMESTAMP,
    updated_at   TIMESTAMP
) FROM pg_source TABLE 'public.orders';

CREATE TABLE payments (
    payment_id      INT PRIMARY KEY,
    customer_id     INT,
    amount          DECIMAL,
    payment_method  VARCHAR,
    status          VARCHAR,
    paid_at         TIMESTAMP
) FROM pg_source TABLE 'public.payments';

CREATE TABLE transactions (
    transaction_id  VARCHAR PRIMARY KEY,
    user_id         BIGINT,
    merchant_id     VARCHAR,
    country         VARCHAR,
    amount          DECIMAL,
    txn_time        TIMESTAMPTZ
) FROM pg_source TABLE 'public.transactions';

CREATE TABLE stock_changes (
    change_id       INT PRIMARY KEY,
    product_id      INT,
    warehouse_id    INT,
    quantity_delta  INT,
    changed_at      TIMESTAMP
) FROM pg_source TABLE 'public.stock_changes';

Every insert, update, and delete on those tables lands in RisingWave within seconds. The primary key is what lets an upstream UPDATE modify the existing row and flow through every dependent view. For MySQL, enable the binlog in row format and use the mysql-cdc connector the same way.

Feature Groups as Materialized Views

Keep each feature group in its own view so groups evolve independently and a change to purchase logic does not recompute browsing features.

Behavioral features from the event stream, with several horizons exposed as separate columns. NOW() in a WHERE or FILTER clause acts as a temporal filter in RisingWave: new events enter the window and old ones expire automatically.

CREATE MATERIALIZED VIEW user_activity_features AS
SELECT
    user_id,
    COUNT(*) FILTER (WHERE event_time > NOW() - INTERVAL '5 MINUTES')                 AS clicks_5m,
    COUNT(*) FILTER (WHERE event_time > NOW() - INTERVAL '1 HOUR')                    AS clicks_1h,
    COUNT(*) FILTER (WHERE event_time > NOW() - INTERVAL '24 HOURS')                  AS clicks_24h,
    COUNT(DISTINCT session_id) FILTER (WHERE event_time > NOW() - INTERVAL '7 DAYS')  AS sessions_7d,
    COUNT(DISTINCT category)   FILTER (WHERE event_time > NOW() - INTERVAL '1 HOUR')  AS categories_1h,
    AVG(duration_seconds)      FILTER (WHERE event_time > NOW() - INTERVAL '1 HOUR')  AS avg_duration_1h,
    COUNT(*) FILTER (WHERE event_type = 'add_to_cart' AND event_time > NOW() - INTERVAL '30 DAYS') AS carts_30d,
    COUNT(*) FILTER (WHERE event_type = 'purchase'    AND event_time > NOW() - INTERVAL '30 DAYS') AS purchases_30d,
    MAX(event_time)                                                                    AS last_active_at
FROM user_events
GROUP BY user_id;

Session-level engagement, grouped by session rather than user, for models that score the current visit:

CREATE MATERIALIZED VIEW feature_session_engagement AS
SELECT
    session_id,
    user_id,
    COUNT(*)                                             AS event_count,
    COUNT(DISTINCT item_id)                              AS unique_items_viewed,
    COUNT(*) FILTER (WHERE event_type = 'click')         AS click_count,
    COUNT(*) FILTER (WHERE event_type = 'add_to_cart')   AS add_to_cart_count,
    SUM(revenue) FILTER (WHERE event_type = 'purchase')  AS session_revenue,
    MAX(event_time) - MIN(event_time)                    AS session_duration,
    MIN(event_time)                                      AS session_start
FROM user_events
GROUP BY session_id, user_id;

Order and payment features from CDC. Because the source is the transactional database, status changes such as returns and refunds are first-class:

CREATE MATERIALIZED VIEW customer_order_features AS
SELECT
    customer_id,
    COUNT(*)                                                               AS total_orders,
    COUNT(*) FILTER (WHERE created_at > NOW() - INTERVAL '7 DAYS')         AS orders_last_7d,
    COUNT(*) FILTER (WHERE created_at > NOW() - INTERVAL '30 DAYS')        AS orders_last_30d,
    AVG(order_total)                                                       AS avg_order_value,
    MAX(created_at)                                                        AS last_order_at,
    COUNT(*) FILTER (WHERE status = 'returned')                            AS return_count,
    ROUND(COUNT(*) FILTER (WHERE status = 'returned')::DECIMAL / NULLIF(COUNT(*), 0), 3) AS return_rate
FROM orders
GROUP BY customer_id;

CREATE MATERIALIZED VIEW customer_ltv_features AS
SELECT
    customer_id,
    SUM(amount)                                                            AS total_lifetime_spend,
    SUM(amount) FILTER (WHERE paid_at > NOW() - INTERVAL '90 DAYS')        AS spend_last_90d,
    COUNT(*)                                                               AS total_payments,
    AVG(amount)                                                            AS avg_payment_amount,
    COUNT(DISTINCT payment_method)                                         AS distinct_payment_methods,
    ROUND(SUM(amount) FILTER (WHERE status = 'refunded')::DECIMAL / NULLIF(SUM(amount), 0), 3) AS refund_rate_by_value
FROM payments
GROUP BY customer_id;

Fraud velocity features, which only make sense when fresh. A customer who made three purchases in three countries in the last five minutes is invisible to last night's batch:

CREATE MATERIALIZED VIEW fraud_features AS
SELECT
    user_id,
    COUNT(*) FILTER (WHERE txn_time > NOW() - INTERVAL '1 MINUTE')                   AS txns_1min,
    COUNT(*) FILTER (WHERE txn_time > NOW() - INTERVAL '1 HOUR')                     AS txns_1h,
    COUNT(DISTINCT merchant_id) FILTER (WHERE txn_time > NOW() - INTERVAL '1 HOUR')  AS unique_merchants_1h,
    COUNT(DISTINCT country)     FILTER (WHERE txn_time > NOW() - INTERVAL '1 HOUR')  AS unique_countries_1h,
    SUM(amount) FILTER (WHERE txn_time > NOW() - INTERVAL '1 HOUR')                  AS total_amount_1h,
    MAX(amount) FILTER (WHERE txn_time > NOW() - INTERVAL '24 HOURS')                AS max_txn_24h,
    AVG(amount) FILTER (WHERE txn_time > NOW() - INTERVAL '30 DAYS')                 AS avg_txn_30d,
    MAX(amount) FILTER (WHERE txn_time > NOW() - INTERVAL '1 HOUR')
        / NULLIF(AVG(amount) FILTER (WHERE txn_time > NOW() - INTERVAL '30 DAYS'), 0) AS amount_ratio
FROM transactions
GROUP BY user_id;

Item popularity, inventory velocity, and sequence features complete the common patterns:

CREATE MATERIALIZED VIEW feature_item_popularity_1h AS
SELECT
    item_id,
    category,
    COUNT(*)                                             AS views_1h,
    COUNT(*) FILTER (WHERE event_type = 'purchase')      AS purchases_1h,
    COUNT(DISTINCT user_id)                              AS unique_users_1h
FROM user_events
WHERE event_time > NOW() - INTERVAL '1 HOUR'
GROUP BY item_id, category;

CREATE MATERIALIZED VIEW inventory_velocity_features AS
SELECT
    product_id,
    warehouse_id,
    SUM(quantity_delta) FILTER (WHERE changed_at > NOW() - INTERVAL '1 HOUR')        AS net_change_1h,
    SUM(quantity_delta) FILTER (WHERE changed_at > NOW() - INTERVAL '24 HOURS')      AS net_change_24h,
    SUM(ABS(quantity_delta)) FILTER (WHERE changed_at > NOW() - INTERVAL '24 HOURS') AS absolute_movement_24h,
    SUM(quantity_delta) FILTER (WHERE quantity_delta < 0 AND changed_at > NOW() - INTERVAL '24 HOURS') AS total_sold_24h
FROM stock_changes
GROUP BY product_id, warehouse_id;

CREATE MATERIALIZED VIEW feature_purchase_sequence AS
SELECT
    user_id,
    (ARRAY_AGG(category ORDER BY event_time DESC))[1:3]   AS last_3_categories,
    MAX(event_time)                                        AS last_purchase_at
FROM user_events
WHERE event_type = 'purchase'
GROUP BY user_id;

A product whose net_change_1h is falling sharply signals a demand spike; high absolute_movement_24h with a flat net change signals inventory churn.

Combined Feature Vectors

Models consume features from several groups. A view that joins the groups is the serving contract. LEFT JOIN plus COALESCE keeps users who have browsed but never purchased in the feature set with zeros rather than dropping them:

CREATE MATERIALIZED VIEW feature_vector_purchase_propensity AS
SELECT
    s.session_id,
    s.user_id,
    s.event_count,
    s.unique_items_viewed,
    s.click_count,
    s.add_to_cart_count,
    EXTRACT(EPOCH FROM s.session_duration)      AS session_duration_seconds,
    COALESCE(a.sessions_7d, 0)                  AS sessions_7d,
    COALESCE(a.purchases_30d, 0)                AS purchases_30d,
    COALESCE(o.orders_last_30d, 0)              AS orders_last_30d,
    COALESCE(o.avg_order_value, 0)              AS avg_order_value,
    COALESCE(o.return_rate, 0)                  AS return_rate,
    COALESCE(l.total_lifetime_spend, 0)         AS total_lifetime_spend,
    COALESCE(l.refund_rate_by_value, 0)         AS refund_rate_by_value,
    s.session_start
FROM feature_session_engagement s
LEFT JOIN user_activity_features a   ON a.user_id = s.user_id
LEFT JOIN customer_order_features o  ON o.customer_id = s.user_id
LEFT JOIN customer_ltv_features l    ON l.customer_id = s.user_id;

This view updates when any of its inputs change: a click on the Kafka stream, a refund committed in PostgreSQL, a new order row. Nothing is recomputed from scratch.

Serving Features to Models

The inference service issues a parameterized point lookup over any PostgreSQL driver. Point lookups on materialized views return in roughly 10 to 20 milliseconds at p99, well inside an online inference budget:

import psycopg2

conn = psycopg2.connect(host="risingwave", port=4566, user="root", dbname="dev")

def get_session_features(session_id: str) -> dict:
    cur = conn.cursor()
    cur.execute("""
        SELECT event_count, unique_items_viewed, click_count, add_to_cart_count,
               session_duration_seconds, sessions_7d, purchases_30d,
               orders_last_30d, avg_order_value, return_rate,
               total_lifetime_spend, refund_rate_by_value
        FROM feature_vector_purchase_propensity
        WHERE session_id = %s
    """, (session_id,))
    row = cur.fetchone()
    if row is None:
        return {}
    return dict(zip([d[0] for d in cur.description], row))

Training pipelines read the same views in bulk with pandas.read_sql, which removes the offline/online store split for current-state features. For higher serving throughput than a single RisingWave instance handles, cache hot feature vectors in the application tier or sink the serving view to the store your platform already reads:

CREATE SINK customer_features_sink FROM feature_vector_purchase_propensity
WITH (
    connector = 'jdbc',
    jdbc.url = 'jdbc:postgresql://feature-store-db:5432/features',
    table.name = 'purchase_propensity_features',
    type = 'upsert',
    primary_key = 'session_id'
);

Kafka, Redis, DynamoDB, and Iceberg sinks follow the same pattern. The computation stays in SQL; the serving store is a choice.

Point-in-Time Correctness and Training Data

Point-in-time correctness means a training example sees the feature values that existed when the labeled event happened, not values that leaked in afterward. Traditional feature stores handle this with versioned snapshots or time-travel lookups, which adds infrastructure.

With streaming SQL, the feature logic is the same for training and serving. The streaming view runs it incrementally; the training job runs it over a historical event log with an explicit time bound per example:

WITH session_features AS (
    SELECT session_id, user_id,
           COUNT(*) AS event_count,
           COUNT(*) FILTER (WHERE event_type = 'add_to_cart') AS add_to_cart_count,
           SUM(revenue) FILTER (WHERE event_type = 'purchase') AS session_revenue,
           MIN(event_time) AS session_start
    FROM user_events_history
    WHERE event_time BETWEEN '2025-01-01' AND '2025-12-31'
    GROUP BY session_id, user_id
),
user_features_at_session_time AS (
    SELECT s.session_id,
           COUNT(DISTINCT e.session_id) AS sessions_7d,
           COUNT(*) FILTER (WHERE e.event_type = 'purchase') AS purchases_7d
    FROM session_features s
    JOIN user_events_history e
      ON e.user_id = s.user_id
     AND e.event_time BETWEEN s.session_start - INTERVAL '7 DAYS' AND s.session_start
    GROUP BY s.session_id
)
SELECT sf.session_id, sf.event_count, sf.add_to_cart_count,
       COALESCE(uf.sessions_7d, 0) AS sessions_7d,
       COALESCE(uf.purchases_7d, 0) AS purchases_7d,
       CASE WHEN sf.session_revenue > 0 THEN 1 ELSE 0 END AS label
FROM session_features sf
LEFT JOIN user_features_at_session_time uf USING (session_id);

The BETWEEN s.session_start - INTERVAL '7 DAYS' AND s.session_start bound is what makes the user features point-in-time correct: only events before the session contribute. For streaming sources, RisingWave applies watermarks and handles late data by event time, so windowed features reflect when events happened rather than when they were processed. Sinking the feature views to Iceberg gives you a history of feature values for training with the same definitions the model sees in production.

Monitoring Feature Drift Continuously

A fraud model that performed well in Q4 lets 15 percent more fraud through by February. Nothing threw an exception; the input distribution moved. Feature drift is silent, and batch monitoring that runs once a day turns a six-minute problem into a six-week incident.

Four statistics catch different failure modes: mean and standard deviation for value shift, null rate for pipeline breaks (almost always the earliest signal of an upstream incident), cardinality for categorical coverage, and quantiles for shape changes the mean misses. Each needs a baseline from the training window and a current rolling window, and the drift signal is the delta.

Log model inputs as one row per feature per prediction, then compute both windows as views:

CREATE TABLE feature_log_unpivoted (
    prediction_id  VARCHAR,
    feature_name   VARCHAR,
    value          VARCHAR,     -- cast at query time
    logged_at      TIMESTAMPTZ
);

CREATE MATERIALIZED VIEW feature_baseline AS
SELECT
    feature_name,
    AVG(value::FLOAT)                                        AS baseline_mean,
    STDDEV(value::FLOAT)                                     AS baseline_stddev,
    COUNT(*) FILTER (WHERE value IS NULL)::FLOAT / COUNT(*)  AS null_rate
FROM feature_log_unpivoted
WHERE logged_at BETWEEN '2026-01-01' AND '2026-03-31'
GROUP BY feature_name;

CREATE MATERIALIZED VIEW feature_current_stats AS
SELECT
    feature_name,
    AVG(value::FLOAT)                                        AS current_mean,
    STDDEV(value::FLOAT)                                     AS current_stddev,
    COUNT(*) FILTER (WHERE value IS NULL)::FLOAT / COUNT(*)  AS null_rate,
    COUNT(*)                                                 AS sample_count
FROM feature_log_unpivoted
WHERE logged_at >= NOW() - INTERVAL '1 HOUR'
GROUP BY feature_name;

CREATE MATERIALIZED VIEW feature_drift_alerts AS
SELECT
    c.feature_name,
    ABS(c.current_mean - b.baseline_mean) / NULLIF(b.baseline_stddev, 0)  AS z_score,
    c.null_rate - b.null_rate                                             AS null_rate_delta,
    c.sample_count,
    CURRENT_TIMESTAMP                                                     AS detected_at
FROM feature_current_stats c
JOIN feature_baseline b USING (feature_name)
WHERE c.sample_count >= 100
  AND (ABS(c.current_mean - b.baseline_mean) / NULLIF(b.baseline_stddev, 0) > 3
       OR ABS(c.null_rate - b.null_rate) > 0.1);

CREATE SINK feature_drift_sink FROM feature_drift_alerts
WITH (connector = 'kafka', properties.bootstrap.server = 'kafka:9092', topic = 'feature-drift-alerts', type = 'append-only', force_append_only = 'true');

In practice, seed the baseline from a table your training pipeline writes rather than aggregating months of history continuously. A z-score above 3 would occur by chance less than 0.3 percent of the time under no change. The null-rate condition is the pipeline break detector: when a deployment at 14:32 breaks the user profile join, user_age goes from 2 percent null to 41 percent null by 14:38 while its mean barely moves, the alert fires at 14:39, and the rollback lands at 14:52. Mean-based monitoring alone would have missed it.

Z-scores are easy to compute in SQL and interpretable, but blind to shape changes that preserve the mean. The Population Stability Index compares bucketed distributions and catches those, at the cost of predefined buckets and a harder SQL implementation. Start with z-score plus null-rate delta, add PSI for your highest-impact features. Be honest about the limits: one-hour windows on low-traffic features have high variance, correlated drift across many features can evade per-feature thresholds, a months-old baseline eventually becomes meaningless, and drift in inputs does not prove the predictions are wrong. Pair feature drift monitoring with outcome monitoring.

Streaming SQL vs Dedicated Feature Stores

AspectRisingWave (streaming SQL)FeastTecton
Feature definitionSQL materialized viewsPython SDKPython SDK
Real-time computationBuilt inRequires Flink or Spark StreamingBuilt in, microbatch
ServingPostgreSQL protocol, or sinksREST and gRPC over RedisREST
Training/serving skewOne definition for bothSeparate compute pathsManaged
InfrastructureOne system plus Kafka or CDCRedis, offline store, orchestrator, stream processorManaged platform
Registry, lineage, versioningNot built inYesYes
LicenseApache 2.0Apache 2.0Commercial

Use streaming SQL when your features are expressible in SQL, you want one system for computation and serving, and your team is stronger in SQL than in Python feature frameworks. Use a dedicated feature store when you need a registry with discovery, feature versioning and lineage, governance controls, or features from non-SQL sources such as image models and text embeddings. Many teams run both: RisingWave computes and serves, and a registry catalogs the views.

Frequently Asked Questions

Can RisingWave be both the stream processor and the feature serving layer? Yes. The same cluster ingests from Kafka or CDC, maintains the feature views, and answers point lookups over PostgreSQL. For very high query rates, add an application cache or sink to a key-value store.

How do I get exact training-time baselines for drift monitoring? Have the training pipeline write mean, standard deviation, and null rate per feature to a table in RisingWave and join feature_current_stats against that table instead of recomputing the baseline from logs.

What about features that need NOW() in the SELECT list, such as exponential decay? Streaming views cannot evaluate NOW() in projections because the result would change with no input event. Expose several time horizons as separate columns, as the activity and fraud views do, and let the model weight them.

Does CDC add load to the production database? Logical replication reads the write-ahead log and does not run queries against tables. Give RisingWave its own replication slot and monitor slot lag so a long RisingWave outage does not cause WAL to accumulate on the source.

How do I version a feature definition? Create the new view alongside the old one, point the serving query at the new name after validation, and drop the old view. Because views are SQL, the definition lives in version control like any other code.

The engine for real-time streaming data.
Analyze, search, and decide.
GitHubXLinkedInSlackYouTube
Sign up for our to stay updated.