Building a Real-Time Feature Store for Machine Learning

Building a Real-Time Feature Store for Machine Learning

The Feature Store Problem

In production ML systems, the hardest part isn't training the model. It's serving features consistently between training and inference. When your training pipeline computes features differently than your serving system, you get training-serving skew, which silently degrades model performance. A feature store solves this by providing a shared, versioned layer for feature computation and serving.

Architecture Overview

A production feature store consists of three core components:

  • Offline Store: Batch-computed features in a data warehouse (Snowflake, BigQuery) for training.
  • Online Store: Low-latency feature serving from a key-value store (Redis, DynamoDB) for real-time inference.
  • Feature Pipeline: Streaming and batch pipelines that compute, transform, and synchronize features.

Feature Definitions

Define features declaratively with metadata, transformation logic, and serving requirements:

# feature_definitions/user_features.py
from feature_store import Feature, Entity, FeatureGroup

# Define entities (the "keys" for feature lookup)
user_entity = Entity(
    name="user_id",
    description="Unique user identifier",
    dtype="string"
)

# Define feature group
user_features = FeatureGroup(
    name="user_behavioral_features",
    entity=user_entity,
    owner="ml-engineering",
    description="User behavioral features for churn prediction",
    freshness_policy={"max_age": "1h", "schedule": "*/15 * * * *"},
    online_store="redis",
    offline_store="snowflake",
    tags=["churn", "user-profile", "production"]
)

# Feature definitions
features = [
    Feature(
        name="user_avg_session_duration_7d",
        description="Average session duration over last 7 days",
        dtype="float64",
        transform="AVG(session_duration_seconds)",
        window="7d",
        aggregation="mean"
    ),
    Feature(
        name="user_total_purchases_30d",
        description="Total purchase count in last 30 days",
        dtype="int64",
        transform="COUNT(purchase_id)",
        window="30d",
        aggregation="count"
    ),
    Feature(
        name="user_last_login_days_ago",
        description="Days since last login",
        dtype="float64",
        transform="DATEDIFF(day, MAX(login_timestamp), CURRENT_DATE())",
        window="unbounded",
        aggregation="max"
    ),
    Feature(
        name="user_lifetime_value",
        description="Total revenue from user",
        dtype="float64",
        transform="SUM(purchase_amount)",
        window="unbounded",
        aggregation="sum"
    )
]

Streaming Feature Pipeline with Flink

For real-time features, use Apache Flink to compute sliding window aggregations from Kafka streams:

// Flink streaming feature computation
DataStream events = env
    .addSource(new FlinkKafkaConsumer<>("user-events", 
        new EventSchema(), kafkaProps))
    .assignTimestampsAndWatermarks(
        WatermarkStrategy
            .forBoundedOutOfOrderness(Duration.ofSeconds(30))
            .withTimestampAssigner((e, t) -> e.getTimestamp())
    );

// Sliding window feature computation
DataStream sessionFeatures = events
    .keyBy(Event::getUserId)
    .window(SlidingEventTimeWindows.of(
        Time.hours(24), Time.minutes(15)))
    .process(new SessionDurationProcessor());

// Write to Redis online store
sessionFeatures.addSink(new RedisSink<>(
    redisConfig,
    new UserFeatureRedisMapper()
));

// Write to S3 offline store (Parquet)
sessionFeatures
    .map(f -> f.toParquetRow())
    .addSink(new ParquetSink<>(s3Config));

Online Feature Serving

Serve features with sub-millisecond latency for real-time inference:

import redis
import json
from typing import Dict, List

class FeatureStore:
    def __init__(self, redis_host: str, redis_port: int):
        self.redis = redis.Redis(
            host=redis_host, 
            port=redis_port,
            decode_responses=True
        )
    
    def get_online_features(
        self, 
        entity_id: str, 
        feature_names: List[str]
    ) -> Dict[str, float]:
        """Fetch features from online store with fallback."""
        pipe = self.redis.pipeline()
        
        for feature in feature_names:
            pipe.hget(f"features:{entity_id}", feature)
        
        results = pipe.execute()
        
        features = {}
        for name, value in zip(feature_names, results):
            if value is not None:
                features[name] = float(value)
            else:
                # Fallback to default or stale value
                features[name] = self._get_fallback(
                    entity_id, name
                )
        
        return features
    
    def get_historical_features(
        self,
        entity_ids: List[str],
        feature_names: List[str],
        point_in_time: str
    ) -> "DataFrame":
        """Fetch features for training with point-in-time correctness."""
        # Query Snowflake with time-travel to prevent leakage
        query = f"""
            SELECT entity_id, {', '.join(feature_names)}
            FROM feature_store.offline_features
            WHERE entity_id IN ({','.join(f"'{e}'" for e in entity_ids)})
            AND computed_at <= '{point_in_time}'
            QUALIFY ROW_NUMBER() OVER (
                PARTITION BY entity_id ORDER BY computed_at DESC
            ) = 1
        """
        return self._query_snowflake(query)

Feature Monitoring

Monitor feature quality and drift to catch data issues before they impact model performance:

  • Freshness Monitoring: Alert when features haven't been updated within their expected freshness window.
  • Distribution Drift: Compare current feature distributions against training baselines using KS tests.
  • Null Rate Tracking: Monitor null percentages and alert when they exceed thresholds.
  • Feature Importance Changes: Track SHAP values over time to detect concept drift.

Conclusion

A well-designed feature store is the backbone of production ML systems. It ensures consistency between training and serving, reduces feature engineering duplication across teams, and provides the monitoring and governance needed for reliable model deployments. Start with clear feature definitions, build reliable streaming pipelines, and invest in monitoring from day one.

Share this article

Back to Blog See Projects