Feature Stores

Centralized feature management for ML systems at scale

1. What is a Feature Store?

Feature Store Definition

A Feature Store is a centralized repository that stores, manages, and serves features for machine learning. It bridges the gap between data engineering and ML, ensuring features are computed consistently for both training and serving.

Problems Feature Stores Solve
  • Feature duplication: Same feature computed differently by teams
  • Training-serving skew: Different code for offline/online
  • Data leakage: Features using future information
  • Feature discovery: Hard to find existing features
  • Backfill complexity: Generating historical features
  • Freshness management: Stale features in production
Key Capabilities
  • Feature Registry: Catalog with metadata and lineage
  • Offline Store: Historical features for training
  • Online Store: Low-latency serving
  • Feature Computation: Transformation pipelines
  • Point-in-time Joins: Prevent data leakage
  • Monitoring: Data quality and freshness
Feature Store Architecture

2. Architecture Deep Dive

Offline vs Online Store

Offline Store

Purpose: Historical feature values for training

Latency: Seconds to minutes (batch queries)

Storage: Data warehouse (BigQuery, Snowflake, S3/Parquet)

  • Full historical data with timestamps
  • Supports point-in-time joins
  • Cost-optimized for large scans
  • Schema evolution friendly
Online Store

Purpose: Latest feature values for inference

Latency: Single-digit milliseconds

Storage: Key-value store (Redis, DynamoDB, Bigtable)

  • Only latest values (no history)
  • Keyed by entity ID
  • Optimized for point lookups
  • Replicated for availability

Feature Types by Computation

Type Computation Freshness Examples
Batch Features Daily/hourly jobs Hours to days User lifetime purchases, 30-day avg
Streaming Features Real-time pipeline Seconds to minutes Transactions in last hour, recent clicks
On-demand Features Request time Immediate Time since last action, current cart size
# Feature definition with Feast
from feast import Entity, Feature, FeatureView, FileSource, ValueType
from datetime import timedelta

# Define entities (primary keys)
user = Entity(
    name="user_id",
    value_type=ValueType.INT64,
    description="User identifier"
)

# Define data source
user_stats_source = FileSource(
    path="s3://bucket/user_stats.parquet",
    event_timestamp_column="event_timestamp",
    created_timestamp_column="created_timestamp"
)

# Define feature view (group of related features)
user_stats_fv = FeatureView(
    name="user_stats",
    entities=["user_id"],
    ttl=timedelta(days=1),  # Feature freshness
    features=[
        Feature(name="total_purchases", dtype=ValueType.INT64),
        Feature(name="avg_order_value", dtype=ValueType.FLOAT),
        Feature(name="days_since_last_purchase", dtype=ValueType.INT64),
        Feature(name="favorite_category", dtype=ValueType.STRING),
    ],
    online=True,  # Materialize to online store
    batch_source=user_stats_source,
    tags={"team": "growth", "domain": "user_behavior"}
)
Interview Insight: Feature Freshness

Not all features need real-time updates. User demographics change rarely (batch daily). Purchase behavior changes moderately (batch hourly). Session features need real-time streaming. Design for the minimum freshness that meets business requirements - over-engineering freshness is expensive.

3. Training-Serving Consistency

The Training-Serving Skew Problem

When features are computed differently during training vs serving, model performance degrades. This is one of the most common causes of ML system failures in production.

Sources of Skew

Common Skew Causes
  • Code duplication: Python for training, Java for serving
  • Data source mismatch: Different tables or schemas
  • Timing issues: Training uses T+1 data, serving uses T
  • Aggregation windows: "Last 7 days" computed differently
  • Missing value handling: Different imputation strategies
  • Feature ordering: Different column order
Prevention Strategies
  • Single source of truth: Feature store serves both
  • Point-in-time joins: Prevent data leakage
  • Feature versioning: Track schema changes
  • Schema validation: Enforce types and constraints
  • Integration tests: Compare offline/online values
  • Monitoring: Alert on distribution shifts

Point-in-Time Correctness

# Point-in-time join: Preventing data leakage
# BAD: Simple join (causes leakage)
def bad_join(labels_df, features_df):
    """
    This causes data leakage!
    We might use features from AFTER the label event.
    """
    return labels_df.merge(features_df, on='user_id')

# GOOD: Point-in-time join
def point_in_time_join(labels_df, features_df):
    """
    Only use features available BEFORE the label timestamp.

    For each (user_id, label_timestamp) in labels:
        Find the most recent feature row where:
        feature_timestamp <= label_timestamp
    """
    result = []

    for _, label_row in labels_df.iterrows():
        user_id = label_row['user_id']
        label_ts = label_row['timestamp']

        # Get features available at label time
        valid_features = features_df[
            (features_df['user_id'] == user_id) &
            (features_df['event_timestamp'] <= label_ts)
        ]

        if len(valid_features) > 0:
            # Get most recent valid features
            latest = valid_features.sort_values('event_timestamp').iloc[-1]
            result.append({**label_row.to_dict(), **latest.to_dict()})

    return pd.DataFrame(result)

# Using Feast for point-in-time joins
from feast import FeatureStore

store = FeatureStore(repo_path=".")

# Entity dataframe with timestamps (labels)
entity_df = pd.DataFrame({
    "user_id": [1001, 1002, 1003],
    "event_timestamp": [
        datetime(2024, 1, 15),
        datetime(2024, 1, 16),
        datetime(2024, 1, 17)
    ]
})

# Feast handles point-in-time join automatically
training_df = store.get_historical_features(
    entity_df=entity_df,
    features=[
        "user_stats:total_purchases",
        "user_stats:avg_order_value",
        "user_stats:favorite_category"
    ]
).to_df()

Feature Versioning

# Feature versioning strategies
class FeatureVersion:
    """
    Track feature computation changes for reproducibility.
    """

    def __init__(self, name, version, computation_fn, schema):
        self.name = name
        self.version = version
        self.computation_fn = computation_fn
        self.schema = schema
        self.created_at = datetime.now()

    def compute(self, data):
        result = self.computation_fn(data)
        self.validate_schema(result)
        return result

    def validate_schema(self, data):
        for col, dtype in self.schema.items():
            assert col in data.columns, f"Missing column: {col}"
            assert data[col].dtype == dtype, f"Type mismatch for {col}"

# Example: User engagement feature with versioning
user_engagement_v1 = FeatureVersion(
    name="user_engagement_score",
    version="1.0.0",
    computation_fn=lambda df: df['clicks'] + df['likes'],
    schema={"user_engagement_score": "float64"}
)

user_engagement_v2 = FeatureVersion(
    name="user_engagement_score",
    version="2.0.0",
    computation_fn=lambda df: df['clicks'] * 0.3 + df['likes'] * 0.5 + df['shares'] * 1.0,
    schema={"user_engagement_score": "float64"}
)

# Feature registry tracks all versions
feature_registry = {
    "user_engagement_score": {
        "current": user_engagement_v2,
        "versions": [user_engagement_v1, user_engagement_v2]
    }
}

4. Implementation Patterns

Batch Feature Pipeline

# Batch feature computation with Spark
from pyspark.sql import SparkSession
from pyspark.sql import functions as F
from pyspark.sql.window import Window

def compute_user_features(spark, date):
    """
    Daily batch job to compute user features.
    """
    # Read raw data
    transactions = spark.read.parquet(f"s3://data/transactions/date={date}")
    users = spark.read.parquet("s3://data/users/")

    # Define window for aggregations
    window_7d = Window.partitionBy("user_id").orderBy(
        F.col("event_timestamp").cast("long")
    ).rangeBetween(-7 * 86400, 0)  # 7 days in seconds

    window_30d = Window.partitionBy("user_id").orderBy(
        F.col("event_timestamp").cast("long")
    ).rangeBetween(-30 * 86400, 0)

    # Compute features
    user_features = transactions.groupBy("user_id").agg(
        # Lifetime features
        F.count("*").alias("total_transactions"),
        F.sum("amount").alias("lifetime_spend"),
        F.avg("amount").alias("avg_transaction_value"),

        # Recency
        F.datediff(F.lit(date), F.max("event_timestamp")).alias("days_since_last_txn"),

        # Frequency
        F.count("*").over(window_7d).alias("transactions_7d"),
        F.count("*").over(window_30d).alias("transactions_30d"),

        # Monetary
        F.sum("amount").over(window_7d).alias("spend_7d"),
        F.sum("amount").over(window_30d).alias("spend_30d"),
    )

    # Add timestamp
    user_features = user_features.withColumn(
        "event_timestamp", F.lit(date).cast("timestamp")
    )

    # Write to offline store
    user_features.write.mode("append").partitionBy("event_timestamp").parquet(
        "s3://feature-store/user_features/"
    )

    # Write to online store (Redis)
    write_to_redis(user_features)

    return user_features

Streaming Feature Pipeline

# Real-time feature computation with Flink (Python API)
from pyflink.datastream import StreamExecutionEnvironment
from pyflink.table import StreamTableEnvironment

def create_streaming_features():
    """
    Real-time feature computation for fraud detection.
    """
    env = StreamExecutionEnvironment.get_execution_environment()
    t_env = StreamTableEnvironment.create(env)

    # Define source (Kafka)
    t_env.execute_sql("""
        CREATE TABLE transactions (
            user_id BIGINT,
            amount DECIMAL(10, 2),
            merchant_id STRING,
            event_time TIMESTAMP(3),
            WATERMARK FOR event_time AS event_time - INTERVAL '5' SECOND
        ) WITH (
            'connector' = 'kafka',
            'topic' = 'transactions',
            'properties.bootstrap.servers' = 'kafka:9092',
            'format' = 'json'
        )
    """)

    # Compute streaming features with tumbling windows
    t_env.execute_sql("""
        CREATE TABLE user_realtime_features AS
        SELECT
            user_id,
            TUMBLE_END(event_time, INTERVAL '1' HOUR) as window_end,
            COUNT(*) as txn_count_1h,
            SUM(amount) as spend_1h,
            COUNT(DISTINCT merchant_id) as unique_merchants_1h,
            AVG(amount) as avg_txn_1h,
            MAX(amount) as max_txn_1h
        FROM transactions
        GROUP BY
            user_id,
            TUMBLE(event_time, INTERVAL '1' HOUR)
    """)

    # Write to online store (Redis sink)
    t_env.execute_sql("""
        INSERT INTO redis_sink
        SELECT * FROM user_realtime_features
    """)

Online Serving

# Feature serving with low latency
import redis
import asyncio
from typing import List, Dict

class FeatureServer:
    """
    Low-latency feature serving from online store.
    """

    def __init__(self, redis_client):
        self.redis = redis_client
        self.feature_cache = {}  # Local cache for hot features

    async def get_features(self, entity_id: str, feature_names: List[str]) -> Dict:
        """
        Fetch features with caching and fallbacks.
        """
        features = {}

        # Check local cache first
        cache_key = f"{entity_id}:{','.join(feature_names)}"
        if cache_key in self.feature_cache:
            return self.feature_cache[cache_key]

        # Batch fetch from Redis (MGET is faster than individual GETs)
        keys = [f"features:{entity_id}:{fn}" for fn in feature_names]
        values = await self.redis.mget(keys)

        for name, value in zip(feature_names, values):
            if value is not None:
                features[name] = self.deserialize(value)
            else:
                # Fallback to default value
                features[name] = self.get_default(name)

        # Update cache
        self.feature_cache[cache_key] = features

        return features

    async def get_features_batch(self, entity_ids: List[str], feature_names: List[str]) -> List[Dict]:
        """
        Batch feature fetch for multiple entities (ranking use case).
        """
        # Use Redis pipeline for efficiency
        pipe = self.redis.pipeline()

        for entity_id in entity_ids:
            for fn in feature_names:
                pipe.get(f"features:{entity_id}:{fn}")

        results = await pipe.execute()

        # Reshape results
        batch_features = []
        idx = 0
        for entity_id in entity_ids:
            entity_features = {"entity_id": entity_id}
            for fn in feature_names:
                value = results[idx]
                entity_features[fn] = self.deserialize(value) if value else self.get_default(fn)
                idx += 1
            batch_features.append(entity_features)

        return batch_features

    def get_default(self, feature_name: str):
        """
        Default values for missing features.
        Should match training defaults!
        """
        defaults = {
            "total_purchases": 0,
            "avg_order_value": 0.0,
            "days_since_last_purchase": 999,
            "favorite_category": "unknown"
        }
        return defaults.get(feature_name, None)

5. Feature Store Tools

Tool Type Strengths Best For
Feast Open Source Flexible, cloud-agnostic, active community Teams wanting control, multi-cloud
Tecton Managed Enterprise features, real-time, managed Enterprise scale, low-latency needs
Databricks Feature Store Managed Unity Catalog integration, Delta Lake Databricks-centric teams
AWS SageMaker FS Managed AWS integration, auto-scaling AWS-centric teams
Vertex AI FS Managed GCP integration, BigQuery native GCP-centric teams
Hopsworks Open Source/Managed Complete ML platform, feature pipelines End-to-end ML platform needs

Feast Example: Complete Workflow

# feast_repo/feature_store.yaml
project: my_project
registry: s3://my-bucket/feast/registry.db
provider: aws
online_store:
  type: redis
  connection_string: "redis://localhost:6379"
offline_store:
  type: file

# feast_repo/features.py
from feast import Entity, FeatureView, FileSource, Feature, ValueType
from datetime import timedelta

# Entity definition
user = Entity(name="user_id", value_type=ValueType.INT64)

# Data source
user_source = FileSource(
    path="s3://my-bucket/data/user_features.parquet",
    event_timestamp_column="event_timestamp"
)

# Feature view
user_features = FeatureView(
    name="user_features",
    entities=["user_id"],
    ttl=timedelta(days=1),
    features=[
        Feature(name="total_purchases", dtype=ValueType.INT64),
        Feature(name="avg_order_value", dtype=ValueType.FLOAT),
        Feature(name="days_since_signup", dtype=ValueType.INT64),
    ],
    online=True,
    batch_source=user_source,
)

# Client usage
from feast import FeatureStore
import pandas as pd

store = FeatureStore(repo_path="feast_repo")

# Apply feature definitions
store.apply([user, user_features])

# Get training data
entity_df = pd.DataFrame({
    "user_id": [1, 2, 3],
    "event_timestamp": pd.to_datetime(["2024-01-01", "2024-01-02", "2024-01-03"])
})

training_df = store.get_historical_features(
    entity_df=entity_df,
    features=["user_features:total_purchases", "user_features:avg_order_value"]
).to_df()

# Materialize to online store
store.materialize_incremental(end_date=datetime.now())

# Get online features
online_features = store.get_online_features(
    features=["user_features:total_purchases", "user_features:avg_order_value"],
    entity_rows=[{"user_id": 1}]
).to_dict()
Interview Insight: Build vs Buy

When asked about feature stores, discuss tradeoffs: Build (Feast) gives flexibility but requires engineering investment. Buy (Tecton, cloud-native) reduces ops burden but creates vendor lock-in. For most companies, start with managed solutions; only build custom when scale/requirements demand it.

6. Interview Questions

Training-serving skew occurs when features computed during training differ from those computed during inference.

Common causes:

  • Different code paths (Python training vs Java serving)
  • Data source inconsistencies
  • Timing differences (batch vs real-time)
  • Missing value handling differences

Prevention strategies:

  • Feature Store: Single source of truth for both training and serving
  • Point-in-time joins: Ensure training uses only past data
  • Schema enforcement: Validate feature types and ranges
  • Integration tests: Compare feature values in both environments
  • Monitoring: Track feature distributions in production

Requirements:

  • Low latency: < 50ms for feature retrieval
  • Real-time features: Transaction velocity, recent patterns
  • Historical features: User profile, lifetime behavior

Architecture:

1. Online Store (Redis Cluster):
   - User profile features (batch updated)
   - Recent transaction aggregates (streaming)
   - p99 latency < 10ms

2. Streaming Pipeline (Kafka + Flink):
   - Compute real-time aggregates
   - Sliding windows: 1min, 5min, 1hour
   - Features: txn_count, amount_sum, unique_merchants

3. Batch Pipeline (Spark):
   - Daily aggregates, historical patterns
   - Features: lifetime_spend, avg_txn_size

4. Feature Serving:
   - Parallel fetch from Redis
   - On-demand features computed at request time
   - Fallback to defaults if feature missing

Key considerations:

  • Redis cluster for high availability
  • Feature TTLs to handle stale data
  • Graceful degradation when features unavailable

Point-in-time correctness ensures that when creating training data, we only use feature values that were available at the time of the prediction event.

Why it matters:

  • Prevents data leakage: Using future information to predict the past
  • Realistic evaluation: Training mimics production conditions
  • Regulatory compliance: Some domains require audit trails

Example:

Scenario: Predicting if user will churn on Jan 15

Wrong: Use user's activity features from Jan 20
       (contains info AFTER the prediction date)

Right: Use user's activity features from Jan 14 or earlier
       (only info available BEFORE prediction)

Implementation:

  • Store features with event_timestamp
  • Join on entity_id WHERE feature_timestamp <= label_timestamp
  • Take most recent feature value before the label time

Feature freshness strategy by computation type:

  1. Static features (demographics, account info):
    • Update: Daily or on-change
    • TTL: Days to weeks
  2. Batch features (aggregates, profiles):
    • Update: Hourly or daily
    • TTL: Hours to days
    • Example: 7-day purchase count
  3. Streaming features (real-time patterns):
    • Update: Seconds to minutes
    • TTL: Minutes to hours
    • Example: Transactions in last hour
  4. On-demand features (request-time):
    • Computed at inference time
    • No storage needed
    • Example: Time since last action

Monitoring freshness:

  • Track feature age in production
  • Alert when features exceed TTL
  • Dashboard showing pipeline lag
Key Takeaways
  • Single source of truth: Eliminates training-serving skew
  • Point-in-time joins: Prevent data leakage
  • Offline + Online stores: Different latency needs
  • Feature versioning: Track computation changes
  • Freshness management: Match business requirements
  • Monitoring: Data quality and distribution shifts