📊Data Engineering

Feature Store

Feature Store

A system that centrally stores, manages, and serves ML features. It improves ML development efficiency by ensuring training-serving consistency and enabling feature reuse.

📖 Detailed Explanation

A Feature Store is a system that centrally manages features in ML workflows and provides consistent features for both training and serving. It addresses problems such as feature reuse, training-serving consistency (preventing Training-Serving Skew), feature version management, and feature discovery.

The need for a Feature Store becomes clearer as an ML project matures. In the early stages, features are computed directly in Jupyter Notebook, but as the number of models grows, duplicated work increases. For example, the feature "number of purchases by a user in the last 30 days" is needed in the same way by many models, such as recommendation, churn prediction, and fraud detection.

┌─────────────────────────────────────────────────────────────────────────────────┐ │ Feature Store 아키텍처 │ ├─────────────────────────────────────────────────────────────────────────────────┤ │ │ │ ┌───────────────────┐ │ │ │ Data Sources │ │ │ │ ┌─────┐ ┌─────┐ │ │ │ │ │ DB │ │Kafka│ │ ┌─────────────────────────────────────┐ │ │ │ └─────┘ └─────┘ │ │ Feature Store │ │ │ │ ┌─────┐ ┌─────┐ │ │ │ │ │ │ │ S3 │ │ API │ │ │ ┌─────────────────────────────┐ │ │ │ │ └─────┘ └─────┘ │───────▶│ │ Feature Registry │ │ │ │ └───────────────────┘ │ │ (메타데이터, 스키마, 버전) │ │ │ │ │ └─────────────────────────────┘ │ │ │ ┌───────────────────┐ │ │ │ │ │ │ Feature │ │ ▼ │ │ │ │ Engineering │───────▶│ ┌─────────────────────────────┐ │ │ │ │ Pipelines │ │ │ Transformation Engine │ │ │ │ │ (Spark, Flink) │ │ │ (피처 계산 로직) │ │ │ │ └───────────────────┘ │ └─────────────────────────────┘ │ │ │ │ │ │ │ │ │ ┌───────┴───────┐ │ │ │ │ ▼ ▼ │ │ │ │ ┌──────────┐ ┌──────────┐ │ │ │ │ │ Offline │ │ Online │ │ │ │ │ │ Store │ │ Store │ │ │ │ │ │(Parquet, │ │ (Redis, │ │ │ │ │ │ BigQuery)│ │ DynamoDB)│ │ │ │ │ └────┬─────┘ └────┬─────┘ │ │ │ └──────┼──────────────┼───────────────┘ │ │ │ │ │ │ ▼ ▼ │ │ ┌────────────┐ ┌────────────┐ │ │ │ Training │ │ Serving │ │ │ │ Pipeline │ │ (Real-time│ │ │ │ (Batch) │ │ Inference)│ │ │ └────────────┘ └────────────┘ │ │ │ └─────────────────────────────────────────────────────────────────────────────────┘

The key components are as follows:

  • Offline Store: Stores large volumes of data for training. Uses analytical storage such as Parquet, Delta Lake, and BigQuery. Retrieves accurate features as of a past point in time with Point-in-time Join.
  • Online Store: Stores the latest features for real-time inference. Uses low-latency Key-Value stores such as Redis and DynamoDB. Targets p99 latency within 10ms.
  • Feature Registry: Manages feature metadata. Stores schema, version, owner, tag, and dependency information. Supports feature discovery and governance.
  • Transformation Engine: Executes feature computation logic. Supports batch pipelines (Spark) and streaming pipelines (Flink, Kafka Streams).

Representative solutions include the open-source Feast, the commercial Tecton, and cloud services (Databricks, AWS SageMaker, Vertex AI Feature Store).

🎯 Core Value

🔄 Feature Reuse

Shares a feature, once defined, across multiple models. Eliminating duplicate computation reduces cost and ensures consistency.

🎯 Training-Serving Consistency

Generates offline/online features from the same feature definition. Prevents model performance degradation caused by Skew.

⏱️ Point-in-Time Join

Accurately retrieves feature values as of a specific point in the past. Prevents Data Leakage.

🔍 Feature Discovery

Explores the features available within an organization. Promotes reuse through a catalog and search.

📋 Version Management

Tracks the change history of feature schemas. Rollback to a previous version is possible.

📊 Monitoring

Detects changes in feature distribution (Drift). Enables early detection of data quality problems.

📊 Feature Store Solution Comparison

Solution Type Online Store Offline Store Streaming Features
Feast Open Source Redis, DynamoDB, etc. Files, BigQuery, etc. Limited Lightweight, supports various backends
Tecton Commercial Managed Managed Native Enterprise-grade, specialized for real-time
Databricks FS Cloud Computing Unity Catalog Delta Lake Spark integration Databricks ecosystem integration
SageMaker FS Cloud Computing Managed S3 Parquet Limited AWS ecosystem integration
Vertex AI FS Cloud Computing Bigtable BigQuery Dataflow integration GCP ecosystem integration
Hopsworks Open source/commercial RonDB Hudi Native Specialized for time series, Python SDK

💻 Code Example

# Feast Feature Store 기본 설정 (Python)

# feature_repo/entities.py - Entity 정의
from feast import Entity

# Entity: 피처의 기준이 되는 키
user = Entity(
    name="user_id",
    description="Unique user identifier",
    join_keys=["user_id"]
)

product = Entity(
    name="product_id",
    description="Product SKU",
    join_keys=["product_id"]
)

# feature_repo/feature_views.py - Feature View 정의
from datetime import timedelta
from feast import FeatureView, Field, FileSource
from feast.types import Float32, Int64, String

# 데이터 소스 정의
user_stats_source = FileSource(
    path="data/user_stats.parquet",
    timestamp_field="event_timestamp",
    created_timestamp_column="created_timestamp"
)

# Feature View: 피처 그룹 정의
user_behavior_fv = FeatureView(
    name="user_behavior",
    entities=[user],
    ttl=timedelta(days=1),  # 온라인 스토어 TTL
    schema=[
        Field(name="purchase_count_7d", dtype=Int64),
        Field(name="purchase_count_30d", dtype=Int64),
        Field(name="total_amount_30d", dtype=Float32),
        Field(name="avg_order_value", dtype=Float32),
        Field(name="days_since_last_purchase", dtype=Int64),
        Field(name="favorite_category", dtype=String),
    ],
    source=user_stats_source,
    online=True,  # 온라인 스토어에 동기화
    tags={
        "team": "ml-platform",
        "domain": "user-behavior",
        "tier": "gold"
    }
)

# feature_store.yaml - 설정 파일
"""
project: ecommerce_ml
registry: s3://my-bucket/feast/registry.db
provider: aws
online_store:
  type: redis
  connection_string: redis-cluster.abc123.cache.amazonaws.com:6379
offline_store:
  type: file
entity_key_serialization_version: 2
"""

# 레지스트리에 적용
# CLI: feast apply

from feast import FeatureStore

fs = FeatureStore(repo_path="feature_repo/")

# 등록된 피처 확인
for fv in fs.list_feature_views():
    print(f"Feature View: {fv.name}")
    print(f"  Entities: {[e.name for e in fv.entities]}")
    print(f"  Features: {[f.name for f in fv.schema]}")
# 학습 데이터 생성 - Point-in-Time Join
from feast import FeatureStore
import pandas as pd
from datetime import datetime, timedelta

fs = FeatureStore(repo_path="feature_repo/")

# 학습할 레이블 데이터 (entity + timestamp + label)
entity_df = pd.DataFrame({
    "user_id": [1001, 1002, 1003, 1004, 1005],
    "event_timestamp": [
        datetime(2024, 1, 15, 10, 0),
        datetime(2024, 1, 15, 11, 30),
        datetime(2024, 1, 16, 9, 0),
        datetime(2024, 1, 16, 14, 0),
        datetime(2024, 1, 17, 8, 0),
    ],
    "churned": [0, 1, 0, 1, 0]  # 레이블
})

# Point-in-Time Join: 각 시점에 맞는 피처 조회
# 데이터 누수(Data Leakage) 자동 방지!
training_df = fs.get_historical_features(
    entity_df=entity_df,
    features=[
        "user_behavior:purchase_count_7d",
        "user_behavior:purchase_count_30d",
        "user_behavior:total_amount_30d",
        "user_behavior:avg_order_value",
        "user_behavior:days_since_last_purchase",
    ]
).to_df()

print("학습 데이터:")
print(training_df)

# 모델 학습
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split

feature_cols = [
    "purchase_count_7d", "purchase_count_30d",
    "total_amount_30d", "avg_order_value",
    "days_since_last_purchase"
]

X = training_df[feature_cols].fillna(0)
y = training_df["churned"]

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)

model = RandomForestClassifier(n_estimators=100)
model.fit(X_train, y_train)

# 온라인 스토어에 피처 동기화 (Materialization)
from datetime import datetime

fs.materialize(
    start_date=datetime(2024, 1, 1),
    end_date=datetime.now()
)
print("피처가 온라인 스토어에 동기화되었습니다.")

# 온라인 서빙 (실시간 추론)
online_features = fs.get_online_features(
    features=[
        "user_behavior:purchase_count_7d",
        "user_behavior:purchase_count_30d",
        "user_behavior:total_amount_30d",
        "user_behavior:avg_order_value",
        "user_behavior:days_since_last_purchase",
    ],
    entity_rows=[{"user_id": 1001}]
).to_dict()

# 예측
features_for_prediction = [
    online_features["purchase_count_7d"][0],
    online_features["purchase_count_30d"][0],
    online_features["total_amount_30d"][0],
    online_features["avg_order_value"][0],
    online_features["days_since_last_purchase"][0],
]
prediction = model.predict([features_for_prediction])
print(f"이탈 예측: {'이탈 위험' if prediction[0] == 1 else '정상'}")
# 스트리밍 피처 (실시간 피처 업데이트)
# Tecton 또는 Flink + Feast 통합 예제

# 방법 1: Push API를 이용한 실시간 피처 업데이트 (Feast)
from feast import FeatureStore, PushSource, FeatureView, Field
from feast.types import Float32, Int64
from datetime import timedelta

# Push Source 정의 (실시간 데이터 입력)
user_activity_push_source = PushSource(
    name="user_activity_push",
    batch_source=...,  # 배치 소스 (백필용)
)

# 실시간 Feature View
user_realtime_fv = FeatureView(
    name="user_realtime_activity",
    entities=["user_id"],
    ttl=timedelta(minutes=30),
    schema=[
        Field(name="clicks_last_5min", dtype=Int64),
        Field(name="page_views_last_5min", dtype=Int64),
        Field(name="cart_value", dtype=Float32),
    ],
    source=user_activity_push_source,
    online=True,
)

# 스트림 처리 후 Push
from feast import FeatureStore
import pandas as pd
from datetime import datetime

fs = FeatureStore(repo_path="feature_repo/")

# Kafka Consumer에서 이벤트 처리 후 피처 Push
def process_event(event):
    """Kafka 이벤트를 처리하여 Feature Store에 Push"""
    user_id = event["user_id"]

    # 집계 로직 (Redis 등에서 윈도우 집계)
    aggregated_features = aggregate_user_activity(user_id)

    feature_df = pd.DataFrame({
        "user_id": [user_id],
        "clicks_last_5min": [aggregated_features["clicks"]],
        "page_views_last_5min": [aggregated_features["page_views"]],
        "cart_value": [aggregated_features["cart_value"]],
        "event_timestamp": [datetime.now()],
    })

    # Online Store에 직접 Push
    fs.push(
        push_source_name="user_activity_push",
        df=feature_df,
        to="online"
    )

# 방법 2: Flink + Feature Store 통합 패턴
"""
Flink Job (PyFlink or Java):
1. Kafka에서 클릭스트림 데이터 소비
2. 윈도우 집계 (5분 Tumbling Window)
3. 집계 결과를 Redis/DynamoDB에 직접 Write
4. 또는 Feast Push API로 전송

┌──────────┐     ┌──────────┐     ┌──────────────┐     ┌──────────────┐
│  Kafka   │────▶│  Flink   │────▶│   Aggregator │────▶│ Online Store │
│ (Events) │     │  Window  │     │  (5min sum)  │     │   (Redis)    │
└──────────┘     └──────────┘     └──────────────┘     └──────────────┘
"""

# 방법 3: On-Demand Feature (요청 시점 계산)
from feast import on_demand_feature_view

@on_demand_feature_view(
    sources=[user_behavior_fv],
    schema=[Field(name="is_high_value_customer", dtype=bool)]
)
def compute_customer_tier(inputs: pd.DataFrame) -> pd.DataFrame:
    """요청 시점에 동적으로 계산되는 피처"""
    df = pd.DataFrame()
    df["is_high_value_customer"] = (
        inputs["total_amount_30d"] > 1000
    ) & (
        inputs["purchase_count_30d"] > 5
    )
    return df

# On-Demand 피처 사용
online_features = fs.get_online_features(
    features=[
        "user_behavior:total_amount_30d",
        "compute_customer_tier:is_high_value_customer",
    ],
    entity_rows=[{"user_id": 1001}]
).to_dict()

🗣️ Say It Like This in Practice

💬 In an Architecture Meeting

"The recommendation model and the churn prediction model are each computing the same user features separately. If we adopt a Feature Store, we can eliminate the duplication and also ensure consistency. Let's start with Feast and migrate to Tecton as we scale."

💬 In a Discussion with Data Engineers

"Latency matters for online serving, and with a Redis online store you get within 10ms at p99. Batch features are fast enough, and if you need real-time aggregation, you can add a Flink pipeline and integrate it through the Push API."

💬 In an Interview

"Training-Serving Skew is a phenomenon in which the feature computation logic differs between training and serving, degrading model performance. With a Feature Store, offline and online features are generated from the same feature definition, which ensures consistency. In particular, Feast's point-in-time join also automatically prevents data leakage."

💬 In a code review

"This feature definition has no version. If the feature schema changes, compatibility problems with existing models can arise. Instead of appending v2 to the feature name, it would be better to use Feast's feature versioning capability or tags."

💬 In a Cost Optimization Meeting

"The feature reuse rate is only 30% right now. If we strengthen the discovery capability in the Feature Store and share a feature catalog across teams, we can significantly reduce duplicate computation costs. Spark pipeline costs alone are expected to drop by 5 million KRW per month."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

❌

Lack of Materialization Monitoring

If online store synchronization (Materialization) fails, the serving features become stale. Be sure to set up pipeline monitoring and alerts in Airflow, Dagster, or similar tools.

❌

Insufficient Feature Version Management

If the feature schema changes, compatibility problems with existing models arise. Define breaking changes under a new feature name, and manage existing features with a deprecated tag.

❌

TTL Configuration Mistakes

If the online store TTL is too short, features expire and null is returned. Analyze feature freshness requirements, and set a TTL longer than the Materialization interval.

❌

Excessive Complexity

Adopting a Feature Store with only 2-3 models is over-engineering. Consider adopting one when you have 10 or more models and a clear need for feature reuse.

✅

The right approach

Start with a file-based offline store at first, and add a Redis online store if real-time serving is needed. It is important to first establish naming conventions and a tag system for feature reuse.

🔥 Learn from Real Cases

📌 Uber - Michelangelo Feature Store USA | Large-scale ML platform | Feature Store pioneer

In 2017, Uber developed a Feature Store as a core component of its in-house ML platform, Michelangelo. Thousands of ML models share the same features, and features are served with millisecond-level latency for real-time requests. The online/offline stores were built on Cassandra and Hive.

Result: Feature reuse rate increased substantially, ML model development time was reduced by 50%, and bugs caused by Training-Serving Skew were eliminated. Lesson: A Feature Store is core infrastructure that raises the maturity of an ML organization.
📌 Spotify - ML Feature Platform Sweden | Music streaming | Personalized recommendations

Spotify operates its own Feature Store to provide personalized music recommendations to hundreds of millions of users. It manages user listening history, playlist information, audio characteristics, and more as features, and uses GCP BigQuery and Bigtable. In particular, real-time listening context features are critical to recommendation quality.

Result: Billions of feature servings every week, with continuous improvement in recommendation click-through rate. Lesson: Real-time context features (the song currently playing, time of day, etc.) can have a greater impact than batch features.
📌 DoorDash - Fabricator Feature Store USA | Food delivery | Real-time prediction

DoorDash uses ML for delivery time prediction, price optimization, fraud detection, and more. Its in-house Fabricator Feature Store achieves p50 5ms and p99 15ms latency on an online store based on a Redis cluster. It handles millions of feature requests per second.

Result: Delivery time prediction accuracy improved, and order conversion rate increased through real-time price optimization. Lesson: In latency-sensitive domains such as food delivery, online store performance is very important.

📝 Comprehension Quiz

Q1. What is the main difference between a Feature Store's Online Store and Offline Store?

A) The Online Store stores more data
B) The Online Store is for real-time low-latency serving, and the Offline Store is for large-scale batch training
C) The Online Store is free, and the Offline Store is paid
D) Both use the same storage

✅ Answer: B) The Online Store uses a low-latency Key-Value store such as Redis/DynamoDB to provide the latest features for real-time inference (targeting p99 within 10ms). The Offline Store uses analytical storage such as Parquet/BigQuery and is used to generate large-scale training data.

Q2. What is Training-Serving Skew, and how does a Feature Store resolve it?

A) A memory problem caused by training data being too large
B) A phenomenon in which performance degrades because feature computation logic differs between training and serving - resolved with the same feature definition
C) A problem in which model training takes a long time
D) A phenomenon in which server load increases

✅ Answer: B) Training-Serving Skew is a phenomenon in which a feature computed in Python during training and a feature computed in Java during serving differ subtly, degrading model performance. A Feature Store resolves this problem by generating both offline and online features from the same feature definition.

Q3. Why is Point-in-Time Join important?

A) To improve join performance
B) To save storage space
C) To prevent data leakage (Data Leakage) and retrieve accurate features as of a past point in time
D) To increase real-time serving speed

✅ Answer: C) When generating training data, Point-in-Time Join retrieves only the features that existed at that point in time, based on each sample's timestamp. This prevents Data Leakage, in which future data is included in training. Example: preventing the use of January 16 data when predicting on January 15.

🔗 Related Terms

📚 Learn More