Library

Volume 1 · Additional Advanced System Design Scenarios

Notebook
Sign in

Section 67

Distributed Feature Store for ML/AI Systems

2,898 words · about 13 min

Problem Statement

Design a feature store that serves both real-time (low-latency online serving for live model inference) and batch (offline training-time) feature access consistently, guarantees point-in-time correctness (a feature value used to train a model for a past event must reflect what was actually known at that point in time — not future information, which would be leakage), and supports many teams/models sharing common feature definitions without duplicating pipelines.

Requirements Clarification

  • Assume ~50 ML teams/models across the organization, sharing a common pool of ~2,000 defined features (some shared across teams, e.g., “user_7day_purchase_count,” some team-specific).
  • Online serving requirement: p99 read latency <10ms for real-time inference use cases (e.g., fraud scoring, recommendation ranking) at up to 50,000 reads/sec aggregate.
  • Offline/training requirement: ability to generate a point-in-time-correct training dataset joining arbitrary feature sets against a set of labeled (entity, timestamp) pairs, at batch scale (millions to billions of rows), without introducing train/serve skew or label leakage.
  • Feature freshness varies by feature type: some features update in real time (streaming aggregates, e.g., “transactions in last 10 min”), some update daily/hourly via batch ETL (e.g., “user lifetime value,” computed from a nightly warehouse job).
  • Assume feature definitions are declared once (a transformation + source) and materialized to both an online store and an offline store from the same definition, to guarantee consistency between what’s used at training time and what’s served at inference time.
  • Governance requirement: feature discovery/catalog so teams don’t redundantly redefine the same feature slightly differently (a real, common organizational failure mode).

Architecture Diagram

                              ┌─────────────────────────────────┐
                              │      Feature Definition Registry   │
                              │  (declarative: name, entity key,    │
                              │   transformation logic, source,      │
                              │   TTL/freshness SLA, owner team)      │
                              │  - versioned, searchable catalog       │
                              └───────────────┬─────────────────┘
                                               │  compiles to
                       ┌────────────────────────┼─────────────────────────┐
                       ▼                                                    ▼
        ┌───────────────────────────┐                        ┌───────────────────────────┐
        │  Streaming Feature Pipeline │                        │  Batch Feature Pipeline     │
        │  (Flink/Kafka Streams-style) │                        │  (Spark/warehouse-scheduled) │
        │  - real-time aggregates       │                        │  - nightly/hourly jobs        │
        │  - windowed computations       │                        │  - historical backfill        │
        │    (e.g. rolling counts)        │                        │    computation                 │
        └───────────────┬───────────────┘                        └────────────────┬───────────────┘
                          │  writes                                                  │  writes
                          ▼                                                          ▼
        ┌─────────────────────────────────────────────────────────────────────────────────────┐
        │                                                                                          │
        │   ┌──────────────────────────────┐              ┌──────────────────────────────────┐   │
        │   │   Online Store                  │              │   Offline Store                     │   │
        │   │   (low-latency KV: Redis/        │              │   (columnar, time-partitioned:       │   │
        │   │    DynamoDB/Cassandra-class)      │              │    data lake / warehouse — Parquet/  │   │
        │   │   - latest value per               │              │    Iceberg/Delta-style tables)       │   │
        │   │     (entity, feature)               │              │   - full history, timestamped        │   │
        │   │   - p99 <10ms read                   │              │     every write (event-time +        │   │
        │   │   - TTL-based eviction/refresh        │              │     ingestion-time)                   │   │
        │   └──────────────┬─────────────────┘              └──────────────────┬─────────────────┘   │
        └───────────────────┼────────────────────────────────────────────────────┼─────────────────────┘
                              │                                                      │
              ┌────────────────▼─────────────────┐                  ┌────────────────▼──────────────────┐
              │   Online Serving API                │                  │   Point-in-Time Join Engine          │
              │   (used by live inference services)  │                  │   (used by training pipelines)        │
              │   - fetch(entity_id, feature_list)    │                  │   - given (entity, label_timestamp)   │
              │   - feature vector assembled from      │                  │     rows, join each feature as-of      │
              │     multiple online store lookups       │                  │     that exact timestamp (no future    │
              │     in parallel, sub-10ms p99            │                  │     leakage), producing a training     │
              │                                          │                  │     dataset                              │
              └──────────────────────────────────────┘                  └────────────────────────────────────┘

  Consistency guarantee: streaming pipeline writes to BOTH online store (latest value) AND offline store
  (append-only, timestamped history) from the same computation — same transformation logic, same code path,
  compiled from the same Feature Definition Registry entry. This shared-definition-dual-write is the core
  mechanism preventing training/serving skew.

  ┌────────────────────────┐
  │  Feature Monitoring     │
  │  - freshness/staleness   │
  │  - null-rate/drift         │
  │  - online/offline value     │
  │    consistency spot-checks   │
  └────────────────────────┘

Key Design Decisions

  1. Shared feature definitions compiled to both online and offline pipelines vs. independently maintained online and offline feature computation.

    • Chosen: a single declarative feature definition (transformation logic + source) is compiled/executed to produce writes into both the online store (for serving) and the offline store (for training), from the same underlying computation.
    • Alternative: teams write separate code for online feature computation (optimized for low latency, often a simplified/approximate version) and offline feature computation (optimized for batch throughput, often the “full correct” version).
    • Trade-off: separate implementations are a extremely common and extremely damaging real-world failure mode — subtle differences between the online-serving approximation and the offline-training “ground truth” computation cause silent training/serving skew, where a model trained on one feature distribution is served a subtly different distribution in production, degrading accuracy in ways that are very hard to debug. Shared-definition dual-write costs more upfront engineering (building a system that can compile one definition to both a streaming and a batch execution path) but eliminates this entire class of bugs structurally rather than relying on process/discipline to keep two implementations in sync.
  2. Point-in-time correct joins for training data generation vs. simply joining against “current” feature values.

    • Chosen: the offline store retains full timestamped history of every feature value change; generating a training dataset requires an explicit “as-of” join — for each (entity, label_timestamp) row, the join engine retrieves the feature value that was actually valid at that exact historical timestamp, not the latest/current value.
    • Alternative: join training labels against the current snapshot of feature values in a simpler feature table.
    • Trade-off: joining against current values is far simpler to implement but causes label leakage — e.g., training a fraud model on transactions from 6 months ago using a “user’s total lifetime fraud flags” feature that has since been updated with information from events after the training example’s timestamp, teaching the model to “cheat” using future information it will never have access to at real inference time. This is one of the most common and insidious sources of inflated offline model performance that fails to materialize in production; point-in-time correctness is non-negotiable for a credible feature store, even though it substantially complicates the offline store’s storage model (must retain history, not just latest state) and the join engine’s implementation (as-of joins are computationally more expensive than simple equi-joins).
  3. Streaming pipeline for real-time features vs. exclusively batch computation with periodic refresh.

    • Chosen: features with tight freshness SLAs (e.g., “transactions in last 10 minutes” for fraud) are computed via a streaming pipeline (Flink/Kafka Streams-class) maintaining incrementally-updated windowed aggregates; features that tolerate hours/day-old staleness (e.g., “lifetime purchase count”) use cheaper batch ETL.
    • Alternative: compute everything via frequent batch refresh (e.g., every 5 minutes) rather than true streaming.
    • Trade-off: frequent micro-batching is operationally simpler (one pipeline paradigm instead of two) but cannot meet sub-minute freshness needs for genuinely real-time signals (a 5-minute-old velocity counter is useless for detecting a fraud burst happening right now) and wastes compute recomputing largely-unchanged aggregates on a fixed schedule rather than incrementally on actual events. Running both a streaming and a batch pipeline paradigm is more operationally complex (two systems to run, monitor, and keep the shared-definition-compilation story consistent across) but is necessary to serve the full range of freshness requirements efficiently.
  4. Centralized feature catalog/registry with governance vs. decentralized, per-team feature pipelines.

    • Chosen: all features are declared in a searchable, versioned central registry with ownership, documentation, and lineage metadata; new feature requests are checked against existing definitions before a team is allowed to create a near-duplicate.
    • Alternative: let each ML team build and own their own feature pipelines independently, feature store is just shared infrastructure/tooling, not a shared catalog of definitions.
    • Trade-off: decentralized ownership is faster for any individual team initially (no cross-team coordination/discovery overhead) but at 50 teams and 2,000+ features, this reliably produces massive redundant computation (the same “user_30day_spend” feature recomputed slightly differently by 5 different teams, wasting compute and creating inconsistent numbers used in different models/dashboards) and makes cross-team feature reuse practically impossible since nobody can discover what already exists. Centralized catalog/governance adds process overhead (definition review, potential bottleneck if the review process isn’t well-resourced) but is what actually delivers the “shared infrastructure for cost efficiency and consistency” value proposition of a feature store — without governance, a feature store is just a database, not a platform.
  5. Online store technology choice: key-value store (Redis/DynamoDB/Cassandra-class) vs. a general-purpose relational database for online serving.

    • Chosen: a low-latency key-value store, sharded by entity ID, storing the latest materialized value per (entity, feature) pair, optimized purely for point-lookup read latency.
    • Alternative: serve online reads directly from a relational database (e.g., Postgres) that also might back other application logic.
    • Trade-off: relational databases offer richer query flexibility but do not reliably hit sub-10ms p99 at 50,000 reads/sec against a shared, possibly-contended database also serving other application traffic; a dedicated KV store purpose-built for this access pattern (simple key lookup, no complex joins needed at serve time — joins/complexity live in the offline/batch computation, not the online read path) gives predictable low latency and can be scaled/sharded independently of other systems, at the cost of needing a separate dual-write pipeline (decision #1) to keep it populated rather than reading live from a transactional system of record.
  6. Feature vector assembly via parallel fan-out reads vs. a single wide denormalized row per entity.

    • Chosen: the online serving API fetches the requested feature list for an entity via parallel lookups (potentially across multiple underlying store shards/tables if features are logically grouped by domain), assembling the final feature vector at request time.
    • Alternative: precompute and store one wide denormalized row containing all features for an entity, updated as any constituent feature changes.
    • Trade-off: a single wide row gives the fastest possible read (one lookup) but creates a write-amplification problem — updating any single feature (and with 2,000 features, many change independently and frequently) requires rewriting the entire wide row, and different models need different subsets of the 2,000 features, so most reads would fetch far more data than needed. Parallel fan-out reads add a small amount of read-path latency (multiple parallel round trips, mitigated by keeping them parallel not sequential, and by co-locating related features in the same shard where access patterns are known) but decouple write frequency/cost per feature from read cost, which matters greatly at this feature-count scale.

Scale Math

  • 50,000 online reads/sec aggregate, p99 <10ms. Assume average inference request needs ~20-50 features per entity, fetched as parallel KV lookups — that’s 1M-2.5M underlying KV operations/sec at peak, which requires a well-sharded KV cluster (entity-ID hash partitioning) sized accordingly; a single well-tuned KV store node might handle 50K-100K ops/sec, implying on the order of 10-50 shards/nodes for the online store cluster (with replication for HA on top of that).
  • Feature freshness tiers: assume of the 2,000 features, ~200 (10%) are true streaming/real-time (sub-minute freshness), remaining ~1,800 (90%) are batch-refreshed (hourly to daily) — informs that the streaming infrastructure, while more operationally complex, serves a minority of feature volume, sized accordingly (smaller, more specialized cluster) versus the batch pipeline handling the bulk.
  • Offline store scale: point-in-time history retention for 2,000 features across, say, 500M distinct entities (e.g., all users), with daily-granularity history retained for 2 years for batch features and higher-granularity (minute-level) retained for a shorter window (e.g., 90 days) for streaming features given their much higher write volume — back-of-envelope: 500M entities × 1,800 batch features × 730 days is far too large to store naively as dense history; in practice offline stores use columnar, compressed, partitioned storage (Parquet/Iceberg-style) and most features are sparse/slowly-changing, so actual storage is a small fraction of the dense upper bound, but this needs explicit capacity planning and compaction/retention policy per feature freshness tier, not a single blanket retention policy.
  • Training dataset generation: point-in-time join for a training set of, say, 100M labeled rows against ~50 requested features each = 5B feature-value lookups against historical, timestamped data; this is inherently a batch/Spark-class distributed join problem (hours of compute, not interactive), which is why it’s architected as a distinct offline batch path rather than trying to reuse the low-latency online serving path for training data generation.

Failure Modes & How They’re Handled

  • Online/offline value divergence despite shared definitions (implementation bug, deployment lag between streaming and batch compiled artifacts): Mitigated with continuous automated consistency monitoring — sampling entities, comparing the online store’s current value against what the offline store’s most recent timestamped record says it should be, alerting on divergence beyond expected staleness windows.
  • Streaming pipeline backpressure/lag under load spike: online features go stale beyond their freshness SLA. Mitigated with lag monitoring per streaming feature pipeline (Kafka consumer lag as the primary signal), auto-scaling of stream processing workers, and serving-side staleness flags (the online serving API can return a feature’s actual last-updated timestamp alongside its value, letting the calling model/service decide whether to trust a stale value or fall back to a default).
  • Point-in-time join engine producing subtly wrong results (off-by-one timestamp boundary bugs are notoriously easy to introduce): Mitigated with a mandatory validation suite of known-answer test cases (synthetic entities with hand-verified expected point-in-time values at specific timestamps) run against every change to the join engine, plus statistical leakage detection (unexpectedly high offline-eval model performance vs. realistic online performance is a strong signal of leakage and should trigger investigation as a standard part of model validation, not just a feature-store concern).
  • Feature definition change breaks downstream models silently (a team updates a shared feature’s transformation logic): Mitigated by treating feature definitions as versioned, immutable artifacts — a “change” to a widely-used feature creates a new version, existing models continue reading the version they were trained/validated against until they explicitly migrate, with the catalog tracking which models depend on which feature versions (dependency graph) so the blast radius of a proposed breaking change is knowable before it ships.
  • Hot entity skew (a small number of entities, e.g., a viral account or major merchant, receive disproportionate read/write traffic): Mitigated with cache-aside layering in front of the online KV store for hot keys, and monitoring for shard hotspotting with the ability to further sub-shard or explicitly replicate hot entity data across the cluster.
  • Feature catalog governance bottleneck slows down teams needing new features quickly: Mitigated with a tiered review process — low-risk, team-scoped features (not shared/reused) get lightweight/self-service registration, while features proposed for shared/cross-team reuse or that touch sensitive data get fuller review, avoiding a single heavyweight process applied uniformly regardless of actual risk/impact.

Interviewer Follow-Up Q&A

Q: Why can’t you just always read from the offline store for both training and serving, avoiding the dual-store consistency problem entirely? A: The offline store’s storage format and access pattern (columnar, timestamped-history, optimized for large batch scans/joins) is fundamentally unsuited to sub-10ms single-entity point lookups at 50,000 QPS — the data layout and query engine are optimized for opposite goals. You need a genuinely different storage engine for the online path; the dual-store-with-shared-definition approach is specifically designed to get the latency benefits of a purpose-built KV store while structurally preventing the definition-divergence risk that naive dual-implementation would introduce.

Q: How do you handle a feature whose correct value depends on very recent data that hasn’t made it through the batch pipeline yet, but the model still needs a point-in-time-correct training value for it? A: This is exactly why the offline store needs full timestamped history rather than only daily snapshots — even for a “batch” feature, if the underlying pipeline records event-time-stamped changes, the point-in-time join can reconstruct what was known at any past instant. For genuinely streaming features, the offline store also receives writes from the streaming pipeline (decision #1’s dual-write), preserving the fine-grained history needed for accurate point-in-time joins even for fast-changing features.

Q: With 2,000 shared features across 50 teams, how do you prevent one team’s feature computation bug or cost overrun from affecting everyone else? A: Resource isolation at the pipeline level — each feature’s (or feature group’s) streaming/batch computation runs in its own resource-quota’d job/pipeline (not one monolithic job computing all 2,000 features), so a runaway or buggy computation for one feature doesn’t starve compute for others. On the serving side, per-team/per-model read quotas and rate limiting at the online serving API protect against one heavy consumer degrading p99 latency for others sharing the KV cluster — the same fairness/QoS problem as the multi-tenant serving scenario, applied to a feature-store context.

Q: How would you support online features that require a very recent, complex real-time computation the streaming pipeline can’t easily precompute (e.g., something depending on the specific inference request’s context, not just historical entity data)? A: That’s typically explicitly out of scope for a feature store proper and handled as a “request-time feature” computed inline by the calling inference service itself (as seen in the fraud-detection scenario’s Stage 2 feature assembly), combined with feature-store-served historical features at serving time. The feature store’s job is consistent, reusable, point-in-time-correct historical/aggregate features; request-context-only computation belongs to the calling application, and conflating the two would overload the feature store’s scope and reintroduce per-model bespoke logic the store is meant to eliminate.

Q: What’s your strategy for backfilling a brand-new feature’s history so it can be used to train on historical labeled data, given it wasn’t being computed in the past? A: A backfill job re-runs the feature’s declared transformation logic against historical raw source data (the same source the streaming/batch pipeline would have read from at the time), writing timestamped historical values into the offline store as if the feature had been computed then — this only works if the underlying raw source data (e.g., raw event logs) was retained with sufficient history and fidelity; features depending on already-decayed/deleted raw sources cannot be perfectly backfilled, which is a real limitation to flag explicitly to a team requesting a new feature for a historical training use case, ideally caught at feature-definition-review time rather than discovered mid-training-job.