Feature store

From j4flmao/agent-skills · View interactive version

Feature store is an AI agent skill from the GitHub repository j4flmao/agent-skills. Use when the user asks about a feature store: Feast, Tecton, Databricks or SageMaker Feature Store, online vs offline features, point-in-time joins, materialization or feature registry. Produces feature repo layout, feature views, PIT-correct training retrieval and online serving config. Not for com

How to use this skill

Skill file

Feature Store Agent

Purpose

Design feature store architecture with Feast or Tecton for consistent feature computation, serving, and validation across training and inference.

Architecture/Decision Trees

Tool Selection

Feature requirements
  ├── Open-source, self-hosted, batch features
  │   └── Feast (Redis/DynamoDB online store, Parquet/ BigQuery offline)
  ├── Managed, streaming + batch, built-in monitoring
  │   └── Tecton (higher cost, less operational overhead)
  └── Cloud-native feature platform
      ├── AWS → SageMaker Feature Store (integrated with SageMaker)
      ├── GCP → Vertex AI Feature Store (integrated with Vertex AI)
      └── Databricks → Feature Store (Delta Lake-backed)

Online Store Selection

Latency SLA requirement
  ├── <5ms p99, high throughput → Redis (in-memory)
  ├── <10ms p99, moderate throughput → ElastiCache / Memorystore
  ├── <50ms p99, large feature size >1MB → DynamoDB / Firestore
  └── <100ms, read-heavy workloads → Cassandra / ScyllaDB

Feature Computation Pattern

Data freshness requirement
  ├── Batch (daily/hourly) → Scheduled Spark/Dataflow job
  │   Output: Parquet (offline) + push to online store
  ├── Streaming (near real-time, <1min)
  │   ├── Kafka → Flink → Online Store
  │   └── Kafka → Bytewax/RisingWave → Online Store
  └── Real-time (request-time computation)
      └── Feature transformations in serving code (on-the-fly)

Agent Protocol

Trigger

User request includes: Feast, Tecton, feature store, online features, offline features, point-in-time join, feature serving, feature registry, feature transformation.

Protocol

  1. Identify feature sources: batch, streaming, or real-time data.
  2. Choose feature store tool based on infra and scale requirements.
  3. Design feature repository with data sources, feature views, and entities.
  4. Configure point-in-time joins for historical feature retrieval.
  5. Set up online serving with low-latency materialization.
  6. Define feature validation rules: freshness, distribution, null checks.
  7. Plan feature registry and sharing across teams.

Output

Feature store architecture with tool selection, feature definition, serving config, validation.

Response Format

## Feature Store Configuration
### Tool
Engine: {Feast / Tecton}
Deployment: {self-hosted / managed}

### Data Sources
| Source | Type | Format | Update Frequency |

### Feature Views
| Name | Entities | Features | TTL |

### Point-in-Time Join
- Entity Key: {column}
- Timestamp Column: {event_timestamp}

### Online Serving
- Store: {Redis/DynamoDB/Firestore}
- Latency SLA: {ms}
- Throughput: {QPS}

No preamble. No postamble. No explanations. No filler. Compress output.

Completion Criteria

Workflow

Step 1: Choose Feature Store

Step 2: Define Feature Repository

feature_repo/
├── data_sources.py      # Source definitions
├── entities.py           # Entity definitions  
├── feature_views.py      # Feature view definitions
├── feature_service.py    # Serving definitions
└── config.py             # Feast config

Step 3: Configure Entities and Sources

# entities.py
from feast import Entity, ValueType

driver = Entity(
    name="driver",
    join_keys=["driver_id"],
    description="Driver identifier",
    value_type=ValueType.INT64,
)

# data_sources.py
from feast import FileSource, PushSource

driver_stats_source = FileSource(
    path="/data/features/driver_stats.parquet",
    timestamp_field="event_timestamp",
    created_timestamp_column="created",
)

# Push source: streaming pipelines (Flink/Spark/Kafka consumers) push fresh rows
driver_trips_push = PushSource(name="driver_trips_push", batch_source=driver_stats_source)

Step 4: Define Feature Views

# feature_views.py
from datetime import timedelta

from feast import FeatureView, Field
from feast.types import Float32, Int32, Int64

driver_stats_fv = FeatureView(
    name="driver_stats",
    entities=[driver],
    ttl=timedelta(days=7),
    schema=[
        Field(name="avg_daily_trips", dtype=Float32),
        Field(name="avg_rating", dtype=Float32),
        Field(name="lifetime_trips", dtype=Int64),
    ],
    online=True,
    source=driver_stats_source,
)

# Near-real-time feature view fed by the push source
driver_recent_fv = FeatureView(
    name="driver_recent_trips",
    entities=[driver],
    ttl=timedelta(hours=1),
    schema=[Field(name="trips_last_hour", dtype=Int32)],
    online=True,
    source=driver_trips_push,
)
# producer side: store.push("driver_trips_push", df_with_driver_id_and_event_timestamp)

Step 5: Point-in-Time Join

from feast import FeatureStore

store = FeatureStore(repo_path='.')
training_df = store.get_historical_features(
    entity_df=entity_df,  # contains driver_id + event_timestamp
    features=[
        'driver_stats:avg_daily_trips',
        'driver_stats:avg_rating',
    ],
).to_df()

Step 6: Online Serving

# Online feature retrieval
feature_vector = store.get_online_features(
    features=['driver_stats:avg_daily_trips', 'driver_stats:avg_rating'],
    entity_rows=[{'driver_id': 1001}],
).to_dict()

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

# Scheduled materialization
# feast materialize-incremental $(date +"%Y-%m-%dT%H:%M:%S")

Step 7: Feature Validation

import pandas as pd
from feast import FeatureStore

def define_validation_rules():
    return {
        "avg_daily_trips": {
            "freshness": "1h",  # must be < 1 hour old
            "null_ratio": 0.05,  # max 5% null
            "min": 0,
            "max": 1000,
            "distribution": "exponential",
        },
        "avg_rating": {
            "freshness": "24h",
            "null_ratio": 0.01,
            "min": 1.0,
            "max": 5.0,
        },
    }

def validate_features(store: FeatureStore, feature_view_name: str, entity_df: pd.DataFrame) -> None:
    """Run validation rules against a sample of historical features."""
    fv = store.get_feature_view(feature_view_name)
    refs = [f"{feature_view_name}:{f.name}" for f in fv.features]
    df = store.get_historical_features(entity_df=entity_df, features=refs).to_df()
    failures = []
    for feature_name, rule in define_validation_rules().items():
        if feature_name not in df.columns:
            continue
        null_pct = df[feature_name].isnull().mean()
        if null_pct > rule["null_ratio"]:
            failures.append(f"{feature_name}: null ratio {null_pct:.2%} > {rule['null_ratio']:.0%}")
        col = df[feature_name].dropna()
        if len(col) and (col.min() < rule["min"] or col.max() > rule["max"]):
            failures.append(f"{feature_name}: values outside [{rule['min']}, {rule['max']}]")
    if failures:
        raise ValueError(f"Feature validation failed for {feature_view_name}: {failures}")

Anti-Patterns

Production Considerations

Monitoring

Scaling

Deployment

Point-in-Time Join Patterns

Problem

Training data must use feature values as they existed at the label time, not future values. Without point-in-time (PIT) joins, label leakage occurs — the model learns patterns that don't exist at prediction time.

Pattern: Standard PIT Join

-- Goal: join features $feature with label at event time
-- Table: labels (user_id, event_timestamp, label)
-- Table: features (user_id, feature_timestamp, feature_value)

SELECT
  l.user_id,
  l.event_timestamp,
  l.label,
  f.feature_value
FROM labels l
LEFT JOIN features f
  ON l.user_id = f.user_id
  AND f.feature_timestamp <= l.event_timestamp  -- strict: <= not <
  AND f.feature_timestamp > l.event_timestamp - INTERVAL '30 days'  -- TTL window

Pattern: Window-Based PIT Join

-- For features computed in windows (e.g., "7-day avg purchase")
-- The window must be computed BEFORE the event timestamp

SELECT
  l.user_id,
  l.event_timestamp,
  l.label,
  AVG(f.value) AS avg_7day_purchase
FROM labels l
LEFT JOIN features f
  ON l.user_id = f.user_id
  AND f.event_timestamp >= l.event_timestamp - INTERVAL '7 days'
  AND f.event_timestamp < l.event_timestamp  -- strict before
GROUP BY l.user_id, l.event_timestamp, l.label

Pattern: Sequential PIT (Multiple Feature Versions)

# When feature computation changed (e.g., feature v2 deployed on date D)
# Use feature v1 for events before D, feature v2 for events after D

def get_feature_at_time(user_id: str, event_time: datetime):
    deploy_cutoff = datetime(2026, 1, 15)  # feature v2 deployed
    if event_time < deploy_cutoff:
        return feature_v1_store.get(user_id, event_time)
    else:
        return feature_v2_store.get(user_id, event_time)

Pattern: Streaming PIT Join

# For real-time features (e.g., current session activity)
# Use Kafka + Flink: join label event with latest feature state

stream_env = StreamExecutionEnvironment.get_execution_environment()
label_stream = stream_env.add_source(kafka_consumer("labels"))
feature_stream = stream_env.add_source(kafka_consumer("features"))

# Temporal join: feature stream is keyed by user_id
joined = label_stream.join(feature_stream)
    .where(lambda l: l.user_id)
    .equal_to(lambda f: f.user_id)
    .window(TumblingEventTimeWindows.of(Time.seconds(5)))
    .apply(PITJoinFunction())

Feature Validation Templates

Basic Validation — Batch Feature Pipeline

import pandera as pa
from datetime import datetime, timedelta

class FeatureValidationSchema(pa.DataFrameModel):
    user_id: str = pa.Field(nullable=False)
    feature_timestamp: datetime = pa.Field(nullable=False)
    feature_1: float = pa.Field(nullable=True, ge=0, le=1)
    feature_2: int = pa.Field(nullable=True, ge=0)
    category_feature: str = pa.Field(nullable=True, isin=["A", "B", "C"])

@pa.check_types(lazy=True)
def validate_features(df: pd.DataFrame) -> pd.DataFrame:
    schema = FeatureValidationSchema
    # Check no future dates
    assert (df["feature_timestamp"] <= datetime.utcnow()).all(), \
        "Future timestamps detected"
    # Check no stale features
    stale = (datetime.utcnow() - df["feature_timestamp"]) > timedelta(days=31)
    if stale.any():
        logging.warning(f"Found {stale.sum()} stale feature rows")
    return df

Distribution Shift Detection

from scipy.stats import ks_2samp
import numpy as np

def detect_feature_drift(
    production_values: np.ndarray,
    reference_values: np.ndarray,
    feature_name: str,
    p_threshold: float = 0.05,
    ks_threshold: float = 0.1,
):
    stat, p_value = ks_2samp(production_values, reference_values)
    drift_detected = (p_value < p_threshold) and (stat > ks_threshold)
    if drift_detected:
        alert(f"Feature {feature_name} drifted: KS={stat:.3f}, p={p_value:.3f}")
    return {
        "feature": feature_name,
        "ks_statistic": stat,
        "p_value": p_value,
        "drift_detected": drift_detected,
    }

Feature Quality Dashboard

Feature            | Null Rate | Cardinality | Mean | Std | Min | Max | Drift Flag
feature_1          | 2.3%     | NA          | 0.45 | 0.12| 0.0 | 1.0 | No
feature_2          | 0.0%     | 18          | 3.2  | 1.1 | 1   | 18  | No
feature_3          | 15.0%    | NA          | -0.1 | 0.8 | -3  | 4   | YES - KS=0.15

Validation Alert Severity

| Severity | Condition | Action |

|----------|-----------|--------|

| Info | Null rate > 5% | Log warning |

| Warning | Null rate > 20% or drift detected | Alert team |

| Error | Null rate > 50% or schema violation | Block pipeline |

| Critical | Feature store unreachable | Page on-call |

Feature Store Anti-Patterns

  1. Training/Serving Skew: Different feature computation logic in training vs. serving

Fix: Serve features through the same feature store, use identical transformation code

  1. No TTL on Features: Accumulating stale features in online store

Fix: Set explicit TTL per feature view; purge expired entries

  1. Leaky Point-in-Time Joins: Using future feature values in training

Fix: Always join with feature_timestamp <= label_timestamp

  1. Over-materialization: Materializing all features to online store

Fix: Only materialize features used in production serving

  1. Feature Sprawl: Thousands of undocumented features

Fix: Feature registry with owner, description, and usage tracking

Feature Store Comparison

| Capability | Feast | Tecton | Vertex AI Feature Store | Custom |

|-----------|-------|--------|------------------------|--------|

| Open source | Yes | No | No | N/A |

| PIT joins | Manual SQL | Automatic | Manual SQL | Custom |

| Online serving | Redis, DynamoDB | Managed | Managed | Any |

| Streaming | Kafka + Flink | Native | No | Custom |

| Cost | Free (self-managed) | $$$ | $$ | $$ (dev cost) |

| Complexity | High (must operate) | Low (managed) | Medium | Very high |

| Best for | Teams wanting control | Teams with budget | GCP-native teams | Specialized needs |

Rules

References

Merged Material

Content folded in from overlapping skills and notes.

Handoff

For model training with feature store integration, hand off to ml-ml-pipeline. For serving infrastructure, hand off to ml-model-serving.

Architecture Decision Trees

Feature Store Architecture

| Decision Point | Option A | Option B | Decision Criteria |

|---|---|---|---|

| Deployment | Self-hosted Feast (open source) | Managed Tecton/Hopsworks | Team size, operational overhead budget |

| Storage backend | Offline: Parquet on S3 (batch) + Online: Redis (real-time) | Offline: BigQuery + Online: Datastore | Existing data infra, latency requirements |

| Feature computation | Batch (Airflow scheduled) | Streaming (Kafka + Flink) | Freshness needs, data source velocity |

Feature Engineering Paradigm

Implementation Patterns

Feast Feature Definition

from datetime import timedelta
from feast import Entity, FeatureView, Field, FileSource, ValueType
from feast.types import Float32, Int64, String

customer = Entity(
    name="customer_id",
    value_type=ValueType.INT64,
    description="Customer identifier",
)

customer_transactions = FileSource(
    path="s3://feature-bucket/transactions/*.parquet",
    timestamp_field="event_timestamp",
    created_timestamp_column="created",
)

transaction_features = FeatureView(
    name="customer_transaction_features",
    entities=[customer],
    ttl=timedelta(days=7),
    schema=[
        Field(name="total_spend_7d", dtype=Float32),
        Field(name="transaction_count_7d", dtype=Int64),
        Field(name="avg_ticket_size_7d", dtype=Float32),
        Field(name="top_category", dtype=String),
    ],
    source=customer_transactions,
)

Feature Serving API

from feast import FeatureStore
import pandas as pd

store = FeatureStore(repo_path="./feature_repo")

# Online serving for real-time inference
features = store.get_online_features(
    features=[
        "customer_transaction_features:total_spend_7d",
        "customer_transaction_features:transaction_count_7d",
    ],
    entity_rows=[{"customer_id": 1234}, {"customer_id": 5678}]
).to_dict()

# Offline retrieval for training
training_df = store.get_historical_features(
    entity_df=entity_df,
    features=[
        "customer_transaction_features:*",
        "customer_profile_features:age",
        "customer_profile_features:segment",
    ],
).to_df()

Performance Optimization

Query Performance

Storage Optimization

Security Considerations

Access Control

Data Governance

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.