Here is the bug that a feature store exists to prevent. A data scientist trains a fraud model offline. One of its features is user_txn_count_7d - how many transactions this user made in the last 7 days. Offline, they compute it with a clean SQL GROUP BY over the warehouse: fast, correct, batch. The model learns that a high value means risk. It ships. In production, the online service needs that same feature at request time to score a live transaction, but nobody wired up the same computation - so an engineer reimplements it in the serving code with a slightly different definition (maybe it counts the current transaction, maybe it uses a rolling 7-day window that starts at midnight instead of now-minus-7-days). The model now sees, at serving time, a number computed differently from the one it trained on. Its predictions silently degrade. No error, no crash, no alert - just a model that is quietly worse in production than it was in evaluation. That is training-serving skew, and it is the single most common way ML systems rot.
The naive fix is “just compute features the same way in both places.” But offline and online have opposite shapes. Offline you have a warehouse, hours of batch time, and you compute features for millions of rows at once to build a training set. Online you have one request, a few milliseconds of budget, and you need one user’s feature vector right now. The same code cannot serve both: a Spark job is useless at request time, and a key-value lookup is useless for building a training table over a year of history. So a feature store is the system that lets you define a feature once and consume it two ways - batch for training, point lookup for serving - and guarantees the value is consistent across both paths. Get that right and models behave in production the way they did in evaluation. Get it wrong and every model you ship has a hidden skew bug.
The two hard parts, stated up front: (1) a dual-path store - a low-latency online store (sub-millisecond point reads) and a high-throughput offline store (full history for training), fed from one definition so values agree; and (2) point-in-time-correct retrieval - when you build a training set, each label must be joined to the feature values as they were at that label’s timestamp, never with values from the future. Let me do it properly.
Functional Requirements (FR)
In scope:
- Feature definition and registration. A user defines a feature (or a feature view - a group of features sharing an entity and a source) once: its entity (what it is keyed by -
user_id,merchant_id), its data type, its freshness, and the transformation that computes it. This definition is the single source of truth both paths consume. - Online serving (the hard latency path). Given an entity key (or a batch of keys) and a list of features, return the latest feature values with sub-millisecond to low-single-digit-millisecond latency, so an online inference service can assemble a model’s input vector at request time.
- Offline retrieval for training (the hard correctness path). Given a set of (entity, timestamp, label) rows - an “entity dataframe” - return a training table where each row is joined to the feature values as of that row’s timestamp. This is point-in-time-correct retrieval, and it is what prevents label leakage and skew.
- Feature materialization / ingestion. Compute feature values from sources (batch sources like a warehouse, streaming sources like a Kafka topic) and write them into both the offline store (full history) and the online store (latest value), from the same definition.
- Consistency between paths. The value a model sees online must equal the value it would have seen offline for the same entity and time. This is the whole point.
- Feature discovery and reuse. A registry so teams find and reuse existing features instead of re-deriving
user_txn_count_7dfor the fifth time (each re-derivation is a fresh chance to introduce skew).
Explicitly out of scope (say this to bound the problem):
- Model training and serving themselves. We supply feature vectors; the training framework and the inference server (see a model-serving platform design) are separate systems. We are the feature layer they both depend on.
- The upstream data pipelines that produce raw events. We consume from a warehouse and from streams; building those ingestion pipelines (CDC, event collection) is upstream of us. We define transformations on top of those sources.
- Labeling / ground-truth collection. The entity dataframe (keys, timestamps, labels) is an input to our offline retrieval; producing labels is the ML team’s job.
- A full transformation engine. We orchestrate transformations (push to Spark/Flink/SQL), but we are not reinventing a compute engine; we define, schedule, and track them.
The one decision that drives everything: a feature store is a dual-materialization system where one logical feature is written to two physically different stores - a latest-value online KV store tuned for sub-ms point reads, and an append-only offline history store tuned for large point-in-time joins - and the system’s core job is to keep those two in sync so that training and serving see the same value. Everything below follows from that split.
Non-Functional Requirements (NFR)
- Scale: ~500 million entities (users, merchants, devices) across ~2,000 registered features grouped into ~200 feature views. ~10 million feature value updates/sec at peak from streaming sources; ~100,000 online serving requests/sec, each fetching 50-200 features for 1 or a small batch of entities. Offline: training-set builds that join billions of label rows against years of feature history.
- Latency (the hard target): online feature retrieval p99 < 10ms for a vector of ~100 features for one entity, and the store’s own point read p99 < 1ms - because the feature store sits inside the inference request’s latency budget, and an inference service that must assemble 100 features cannot spend 50ms doing it. Batch online reads (score 1,000 entities) must stay efficient via multi-get.
- Throughput (the other hard target): the ingestion/materialization path must absorb millions of writes/sec from streams and periodic bulk loads from batch, without falling behind (stale features are wrong features).
- Freshness: configurable per feature. Some features are fine a day old (batch:
user_lifetime_spend); some must be seconds old (streaming:txn_count_last_1min). Freshness is a first-class, per-feature property, and the architecture must support both batch and streaming materialization. - Consistency (the defining NFR): online/offline consistency - the value served online must match the value materialized offline for the same entity and event time. This is not classic distributed-systems linearizability; it is definition consistency across two stores. We accept that the online store is eventually consistent with the latest event (a few seconds of lag for streaming features), but the transformation logic must be identical across paths.
- Availability: 99.95%+ for the online serving path - it is in the critical path of live inference, so if the feature store is down, models cannot score. This forces replication and graceful degradation (serve a slightly stale value rather than fail).
- Durability: the offline store is the system of record for feature history (used to rebuild training sets and to re-materialize the online store); it must be durable and immutable-append. The online store is a derived, rebuildable cache of latest values - losing it is recoverable by re-materializing from offline.
Back-of-the-Envelope Estimation (BoE)
Let me ground the two paths in numbers before drawing boxes.
Online serving load and why latency is brutal:
Online requests: 100,000 req/s peak
Features per request: ~100 (a model's input vector)
Entities per request: usually 1, sometimes a batch (e.g. 100 items
to rank) -> up to 100 entities x 100 features.
Naive: one KV read per feature = 100 reads per request
100,000 req/s x 100 = 10,000,000 online reads/sec.
At batch-ranking (100 entities): 100 x 100 = 10,000 reads for ONE
request -> fan-out explodes. This is why features are grouped and
co-located: fetch a whole feature VIEW for an entity in one read,
not 100 reads. (Deep dive 1.)
Latency budget: inference p99 might be 50ms total. Feature fetch
gets maybe 5-10ms of that. With 100 features to gather, per-read
budget is ~tens of microseconds amortized -> demands an in-memory
or NVMe KV store with multi-get, not a round-trip per feature.
Online store sizing (latest value only):
500M entities x ~2,000 features. But features are sparse per entity
type (a user has user-features, a merchant has merchant-features).
Say effective: 500M entities x avg 200 bytes of hot features each
= 500M x 200 B = ~100 GB of HOT latest-value data per entity type,
a few hundred GB total across entity types.
This FITS in a distributed in-memory / RocksDB-backed KV store
sharded across ~20-50 nodes. The online store is deliberately
SMALL - it holds only the LATEST value per (entity, feature),
never history. That is what keeps point reads sub-ms.
Offline store sizing (full history - this is the big one):
Streaming updates: 10,000,000 writes/sec at peak.
Each historical row: ~100 bytes (entity, feature, value, event_time).
Per day (assume avg 2M writes/s sustained):
2,000,000 x 86,400 s x 100 B = ~17 TB/day of feature history.
Per year: ~6 PB. This is warehouse / columnar-lake territory
(Parquet on object storage), NOT a KV store. Partitioned by
date + entity for efficient point-in-time joins. Compressed and
columnar brings it down, but the point stands: offline is PB-scale
history; online is GB-scale latest-value. Two different stores
for two different access patterns. (This asymmetry is the design.)
Write amplification (dual write):
Every materialized feature value is written TWICE:
- offline: appended to history (durable, batched, columnar)
- online: upsert latest value (if this event is newer than current)
So ingestion throughput budget = 2x the logical update rate, plus the
online store only keeps the value if event_time > stored event_time
(last-write-wins by EVENT time, not arrival time - crucial for
correctness when events arrive out of order).
Point-in-time join cost (offline training build):
Training set: 1,000,000,000 label rows, each needs ~100 features
joined AS OF its label timestamp.
Naive row-by-row lookup: 1B x 100 = 100B point-in-time lookups.
At even 1ms each that is 100B ms = ~3 years. Impossible.
So the join MUST be a BATCH operation: a single big as-of join
(sort-merge by entity+time) over partitioned columnar history,
done in Spark across a cluster in minutes-to-hours, NOT per-row
lookups. (Deep dive 2 - this is why offline is columnar, not KV.)
The takeaway: this is a two-store system with a 10,000x asymmetry - online is GB-scale latest-value optimized for sub-ms point reads at millions of QPS; offline is PB-scale full history optimized for one massive batch as-of join. They are fed from one definition and kept consistent by event-time last-write-wins on the online side. Every design choice below serves that split and the consistency guarantee across it.
High-Level Design (HLD)
A feature store is three planes: a definition/registry plane (features defined once), an ingestion/materialization plane (compute values, dual-write to both stores), and a serving plane (online point reads, offline batch retrieval). The online and offline stores are the two physical homes of one logical feature.
┌──────────────────────────────────────────────────────┐
│ REGISTRY (source of truth for DEFINITIONS) │
│ feature views, entities, transforms, data types, │
│ freshness, online/offline store bindings │
└───────────┬──────────────────────────────┬───────────┘
│ definitions read by │
▼ ▼
┌─────────────────────────────┐ ┌───────────────────────┐
│ INGESTION / MATERIALIZE │ │ SERVING PLANE │
│ │ │ │
│ BATCH path (Spark/SQL): │ │ ONLINE server: │
│ warehouse -> transform -> │ │ get_online_features( │
│ write offline + online │ │ entity_keys, │
│ │ │ feature_refs) │
│ STREAM path (Flink/Kafka): │ │ -> multi-get online │
│ events -> transform -> │ │ store, assemble │
│ write offline + online │ │ vector, <10ms │
└───────┬──────────────┬───────┘ │ │
│ append │ upsert │ OFFLINE server: │
│ (history) │ (latest, │ get_training_data( │
▼ │ event-time │ entity_df) │
┌───────────────┐ │ LWW) │ -> point-in-time │
│ OFFLINE STORE │ ▼ │ JOIN over history │
│ (columnar │ ┌──────────────┐ └──────────┬────────────┘
│ history, │ │ ONLINE STORE │ │
│ Parquet/lake,│ │ (KV, in-mem/ │◄── point reads ─┘
│ PB-scale, │ │ RocksDB, │ (sub-ms multi-get)
│ system of │ │ latest only,│
│ record) │ │ GB-scale) │
└───────┬───────┘ └──────────────┘
│ batch as-of join (sort-merge by entity+time)
▼
┌────────────────────┐ online store can be REBUILT from
│ TRAINING DATASET │ offline store (materialization replay)
│ (point-in-time │ -> offline is durable truth, online
│ correct, to S3) │ is a derived cache.
└────────────────────┘
Serving path (online) - one inference request, end to end:
- An inference service (scoring a live transaction) calls
get_online_features(entities=[{user_id: U}], features=[view:fraud_v2]). It names the entity key(s) and the feature view(s) it needs - not 100 individual features, but the view that groups them. - The online serving server resolves the feature view from the registry (cached locally) to the concrete set of features and the online store keys.
- It issues a multi-get to the online store - one batched read fetching the whole feature view for that entity (features in a view are co-located under one key, so this is one read, not 100). For a batch of entities it is one multi-get across keys.
- The store returns the latest values; the server assembles them into the ordered feature vector the model expects, applies any lightweight on-read transform (e.g. normalize), and returns in under 10ms. If a feature is missing (never materialized for this entity), it returns the registered default / null, never an error.
- The inference service feeds the vector to the model. The feature store never saw the model.
Training path (offline) - one training-set build, end to end:
- An ML pipeline calls
get_training_data(entity_df)whereentity_dfis a table of(entity_key, event_timestamp, label)rows - one row per training example, each stamped with the moment the label is “as of.” - The offline serving server reads the feature views’ offline history (columnar, partitioned by date+entity) from the lake.
- It performs a point-in-time as-of join: for each entity row, pick the feature value whose
event_timestamp <= row.event_timestampand is the latest such (no future values). This is done as a batch sort-merge join by entity and time across the cluster, not row-by-row. - The result is a training table: each label row widened with the feature values as they were at that label’s time. It is written to object storage and handed to the training framework. Because it used the same definitions that feed the online store, the features match what the model will see in production.
Ingestion path - one feature materialization, end to end:
- A source produces data: a batch source (a daily warehouse table) or a stream source (a Kafka topic of events).
- The materialization job runs the feature’s registered transformation (a SQL/Spark expression for batch, a Flink operator for streaming) to produce
(entity_key, feature_name, value, event_timestamp)records. - It dual-writes: appends every record to the offline history store (durable, columnar, the system of record), and upserts the latest value into the online store - but the online upsert is conditional on event time: write only if this record’s
event_timestampis newer than the value currently stored (last-write-wins by event time, so a late-arriving old event never overwrites a newer value).
The architectural insight: one definition in the registry, two physical stores behind it, and a materialization layer that dual-writes from the same transformation - so online and offline hold the same logical feature in the two shapes their access patterns demand, and consistency is enforced not by syncing two databases but by computing both from one source of truth.
Component Deep Dive
The hard parts: (1) the online store and the sub-ms serving path - fetching 100 features per request at 100K QPS; (2) point-in-time-correct offline retrieval - the join that prevents label leakage; (3) online/offline consistency - the mechanism that actually keeps the two stores agreeing and kills training-serving skew; and (4) streaming vs batch materialization and freshness. I walk each from naive to scalable.
1. The Online Store and the Sub-Millisecond Serving Path
The online store answers “give me the latest value of these features for this entity, now.” At 100K req/s with ~100 features each, the access pattern - not the storage engine alone - decides whether you hit the latency target.
Approach A: One row per (entity, feature), one read per feature (the naive instinct)
Model the online store as a table keyed by (entity_id, feature_name) -> value. To build a 100-feature vector, issue 100 point reads.
for feature in features:
value[feature] = store.get(entity_id, feature) # 100 round trips
Where it breaks - immediately, on fan-out and latency. 100K req/s x 100 features = 10M reads/sec, each a network round trip. Even a 0.3ms read becomes 100 sequential round trips = 30ms+ per request - already over budget before the model runs. Parallelizing the 100 reads helps latency but multiplies connection and tail-latency pressure (p99 of 100 parallel reads is worse than p99 of one). And for batch ranking (100 entities x 100 features) it is 10,000 reads for a single request. One-read-per-feature does not scale; the read pattern is the bottleneck, not the store.
Approach B: Co-locate a feature view under one key (the key move)
Store an entire feature view (the group of features sharing an entity) as one value under one key: key = (entity_id, feature_view) -> {feat1: v1, feat2: v2, ...}. One read returns the whole group.
key: user:U:fraud_v2
value: { txn_count_7d: 14, avg_amt_30d: 42.10, ..., _event_ts: ... }
get_online_features(U, view=fraud_v2) -> ONE read returns all features
in that view. 100 features in ~2-3 views = ~2-3 reads, not 100.
Batch of entities -> ONE multi-get across their keys.
- Why it works: reads collapse from per-feature to per-view. A model’s 100 features usually come from a handful of views, so a request is a handful of multi-get reads, each sub-ms. This is the difference between 100 round trips and 3. The view is the unit of read co-location because it is also the unit of materialization (a transform writes a whole view at once), so grouping is natural, not forced.
- Cost / trade: updating one feature means rewriting the whole view value (read-modify-write or a store that supports partial field updates like a hash). For features in a view that update at very different rates, you either accept the rewrite or split them into separate views by update cadence. Features that change together, and are read together, belong in the same view.
Approach C: The storage engine and sharding for sub-ms at scale
Co-location fixes fan-out; now the store itself must do sub-ms point reads at millions of QPS and hold the hot set in fast memory.
ENGINE: an in-memory-first KV store (Redis-like) or an embedded
LSM store (RocksDB) fronted by RAM, NOT a general SQL DB. We need
O(1) point get on a known key, not query planning. Values are the
serialized feature-view blobs.
SHARDING: shard by ENTITY KEY (consistent hashing on entity_id).
All of an entity's feature views land on the same shard -> a
request for one entity hits one shard, and multi-get for a batch
of entities fans to a bounded set of shards. Entity-key sharding
also spreads the 500M entities evenly (no natural hot entity for
most workloads).
REPLICATION: each shard replicated (N=3) across zones. Reads served
from any replica (reads scale with replicas); writes go to a
primary and replicate async (the online store tolerates a few
seconds of replica lag - a slightly stale feature is acceptable,
a failed read is not).
HOT KEYS: some entities ARE hot (a celebrity user, a huge merchant).
Replicate hot keys more widely and/or cache them at the serving
server's local in-process cache with a short TTL, so a viral entity
does not hammer one shard. (See Bottlenecks.)
So the online path is: group features into views and co-locate each view under one entity-sharded key so a request is a few multi-gets not a hundred, serve from an in-memory/LSM KV store replicated across zones, and absorb hot entities with wider replication plus a small local cache - turning a 10M-read-per-second fan-out into a handful of sub-ms reads per request.
2. Point-in-Time-Correct Offline Retrieval
This is the correctness heart of the system. When you build a training set, every feature value joined to a label must be the value as it was known at the label’s timestamp. Use a value from after that timestamp and you leak the future into training - the model learns from information it will not have at serving time, evaluates beautifully offline, and collapses in production.
Approach A: Join on latest feature value (the naive, and catastrophically wrong, instinct)
Build the training table by joining each label row to the feature’s current value (or the value in a simple entity_id join).
SELECT labels.*, features.*
FROM labels JOIN features USING (entity_id) -- WRONG
Where it breaks - silently and fatally, this is label leakage. Suppose a label row is “did user U default on a loan, as of Jan 1.” If you join U’s account_balance feature using its latest value (say, from June, after the default already happened), the model trains on post-outcome information. It “learns” that low balance predicts default - but it only knows the low balance because the default already occurred. In production, at the moment of scoring (Jan 1), that future value does not exist. The model’s real-world accuracy is far below its offline evaluation. There is no error; the numbers just lie. Any join that ignores time is wrong for training.
Approach B: Row-by-row as-of lookup (correct but impossibly slow)
For each label row, look up the feature value whose event_timestamp <= label.event_timestamp, taking the latest such.
for each label_row:
for each feature:
value = SELECT value FROM history
WHERE entity_id = label_row.entity_id
AND event_ts <= label_row.event_ts
ORDER BY event_ts DESC LIMIT 1
- Correct: it never uses a future value. This is the right semantics - the “as-of” join.
- Where it breaks: scale. 1B label rows x 100 features = 100B lookups (BoE: years of wall-clock). Doing it as per-row queries against any store is hopeless. The semantics are right; the execution is impossible. The fix is to keep these semantics but execute them as one batch operation.
Approach C: Batch as-of join over partitioned columnar history (the real design)
Keep offline history as an append-only, columnar, time-partitioned dataset: every feature value ever materialized is a row (entity_id, feature_name, value, event_timestamp), stored as Parquet partitioned by date and clustered by entity. Then the point-in-time join is a single distributed sort-merge as-of join.
ENTITY DF (sorted by entity, event_ts):
(U, 2026-01-01, label=1)
(U, 2026-03-01, label=0)
FEATURE HISTORY (sorted by entity, event_ts):
(U, balance=500, 2025-12-20)
(U, balance=300, 2026-01-05) <- AFTER Jan 1 label, must NOT be used
(U, balance=900, 2026-02-28)
AS-OF JOIN (per entity, merge the two sorted streams):
for label (U, 2026-01-01): take latest feature with ts <= 2026-01-01
-> balance=500 (from 2025-12-20). CORRECT, no future leak.
for label (U, 2026-03-01): latest ts <= 2026-03-01
-> balance=900 (from 2026-02-28). CORRECT.
Executed as a Spark sort-merge join: sort both sides by (entity,
event_ts) ONCE, merge in a single streaming pass per partition.
O(n log n) to sort, O(n) to merge - minutes/hours over billions
of rows across a cluster, not 100B point lookups.
- Why it works: sorting both sides by
(entity, event_timestamp)turns 100B random lookups into a few linear merge passes. Time partitioning lets the engine prune partitions (a Jan-1 label never scans Jun data). This is the only tractable way to do point-in-time correctness at training scale. - The TTL / window detail: many features have a max lookback (a 7-day-window feature is null if the latest value is older than 7 days before the label). The as-of join carries each feature’s
ttlso a stale value is treated as absent, matching exactly what the online store would serve (the online value also expires by TTL). This is where offline correctness and online behavior are deliberately aligned.
So offline retrieval is: keep full feature history append-only, columnar, and time-partitioned, and build training sets with a batch sort-merge as-of join that joins each label to the latest feature value at or before its timestamp - correct semantics (no future leakage) executed at the only scale that works (one big sorted merge, not a billion lookups).
3. Online/Offline Consistency: Actually Killing Training-Serving Skew
Deep dives 1 and 2 built two stores. This one is why they agree. Skew sneaks in at three seams: the transformation logic differing between paths, the values diverging between stores, and the timing (TTL/window) differing. We close all three.
The skew sources and the naive non-fix
SKEW SOURCE A (logic): offline computes txn_count_7d in Spark SQL;
online recomputes it in Java serving code. Two implementations ->
guaranteed drift over time (one gets a bug fix, the other doesn't).
SKEW SOURCE B (values): even with identical logic, if offline and
online are materialized independently from different snapshots,
their values differ at the boundary.
SKEW SOURCE C (timing): offline uses a feature even if 10 days stale;
online expires it at 7 days (or vice versa). Same logic, different
effective value because the freshness rule differs.
Naive non-fix: “have two careful teams keep the two implementations in sync by code review.” This fails the way all two-source-of-truth schemes fail - the moment they can drift, they will.
The fix: one transformation, dual-write, shared TTL, and consistency checks
1. ONE TRANSFORMATION DEFINITION (kills source A). The feature's
transform is defined ONCE in the registry. Both materialization
paths EXECUTE THE SAME definition:
- batch: the transform compiled to Spark/SQL
- streaming: the SAME transform compiled to Flink
There is no hand-written serving-side feature code. The online
value is produced by the materialization job, not recomputed at
read time. Serving just LOOKS UP a pre-computed value.
(On-demand features that MUST compute at request time - e.g. using
a request-only input like "distance between request lat/long and
stored home" - run a SHARED transform function invoked identically
in training and serving, so even those use one code path.)
2. DUAL-WRITE FROM ONE JOB (kills source B). The materialization job
writes BOTH stores from the SAME computed record:
- append (entity, feature, value, event_ts) to offline history
- upsert latest to online IFF event_ts > stored event_ts (LWW
by EVENT time, so out-of-order arrivals never corrupt latest)
Online is a projection of offline: online[entity,feature] ==
the offline row with the max event_ts for that key. By
construction they cannot disagree on the latest value.
3. SHARED TTL / WINDOW (kills source C). The feature's freshness TTL
lives in the registry and is applied in BOTH paths: the online
store expires a value past its TTL (serve default/null), and the
offline as-of join treats a value older than TTL as absent. Same
effective value at the same logical time.
4. CONSISTENCY AUDIT (catches the rest). A background job samples
entities, reads the online value, recomputes the expected value
from offline history at "now", and alerts on mismatch beyond a
tolerance. Skew becomes a monitored, alertable metric, not a
silent model-rot.
- Why this is the whole ballgame: the guarantee is not “two databases are kept in sync by replication” - it is “both stores are deterministic projections of one definition and one computed record, so there is only ever one source of truth.” Online is literally the latest slice of the offline history, produced by the same job. Skew is designed out, then audited to catch bugs in the design’s own implementation.
- The one honest gap: streaming lag. The online store may be a few seconds behind the true latest event (materialization is not instantaneous). So at the exact moment of serving, online can be seconds staler than a hypothetical perfect offline value. We accept this (freshness NFR) and make the training data reflect it where it matters - if a feature is served with seconds of lag online, the training-time as-of join can be configured with the same effective-timestamp semantics so the model trains on data of the same freshness it will serve on. Matching freshness, not just value, is the subtle final step.
So consistency is enforced by collapsing the two paths to one source of truth - one transform definition, one computed record dual-written, one shared TTL - with online as a deterministic latest-value projection of the offline history, plus a sampling audit that turns any residual skew into an alert instead of silent model decay.
4. Streaming vs Batch Materialization and Freshness
Different features need different freshness, and that dictates how they are materialized. The system must support both without two separate consistency models.
The naive single-mode trap
“Materialize everything in a nightly batch job” is simple but makes every feature up to 24 hours stale - useless for txn_count_last_1min in fraud, where the signal is recency. “Materialize everything from streams” is fresh but wasteful for user_lifetime_spend, a slow feature that a nightly batch computes far more cheaply than a never-sleeping stream operator.
The design: per-feature source and cadence, one write contract
BATCH features (freshness = hours/days): a scheduled Spark/SQL job
reads the warehouse, computes the transform over all entities,
dual-writes. Cheap, high-throughput, good for aggregates over long
windows. Backfill = just run it over historical partitions.
STREAMING features (freshness = seconds): a Flink job consumes the
event stream, maintains windowed aggregates (e.g. count over a
sliding 1-min window per entity), and dual-writes on each update.
Expensive but fresh; used only where recency is the signal.
BOTH use the IDENTICAL write contract: append to offline history +
event-time-LWW upsert to online. So a feature can even be MIGRATED
from batch to streaming without changing how it is consumed - the
registry just changes its source and cadence; readers never know.
BACKFILL / BOOTSTRAP: a new streaming feature has no history. Seed
the offline store with a one-time batch backfill over past events,
then let the stream take over from a watermark -> full history for
training AND fresh updates for serving, with no gap or double-count
(the batch backfill and stream hand off at a precise event-time
watermark).
So materialization is per-feature choice of batch (cheap, slow-moving aggregates) or streaming (expensive, recency-critical), both emitting the same append-plus-event-time-LWW write contract - so freshness is a per-feature property, migration between modes is invisible to readers, and a precise watermark hand-off lets a streaming feature still have the full history training needs.
API Design & Data Schema
A feature store exposes a definition/registry API, an online serving API (the latency-critical one), and an offline retrieval API. The durable truth is the offline history + the registry; the online store is a derived cache.
Definition / Registry API
POST /v1/entities # define an entity (join key)
{ "name": "user", "join_key": "user_id", "value_type": "int64" }
POST /v1/feature-views # define a group of features
{ "name": "fraud_v2",
"entity": "user",
"features": [
{ "name": "txn_count_7d", "dtype": "int32" },
{ "name": "avg_amt_30d", "dtype": "float" } ],
"source": { "type": "stream", "topic": "txn-events" },
"transform": "SELECT user_id, COUNT(*) OVER w7 AS txn_count_7d, ...",
"ttl_seconds": 604800, # 7d freshness/window
"online": true, "offline": true }
-> { "feature_view": "fraud_v2", "version": 3 }
GET /v1/feature-views/{name} # resolve features, keys, ttl
GET /v1/features/search?q=txn # discovery / reuse
Online serving API (p99 < 10ms - the hot path)
POST /v1/online/get-features # latest values for serving
{ "features": ["fraud_v2:txn_count_7d", "fraud_v2:avg_amt_30d",
"user_profile:age"],
"entities": { "user_id": [ "U123" ] } } # or a batch of keys
-> { "results": [
{ "user_id": "U123",
"txn_count_7d": 14, "avg_amt_30d": 42.10, "age": 31,
"statuses": { "txn_count_7d": "PRESENT",
"age": "DEFAULT" } } ], # missing -> default
"metadata": { "latency_ms": 4 } }
# Internally: resolve views from registry (cached) -> entity-sharded
# multi-get of co-located view blobs -> assemble ordered vector ->
# apply TTL (expired -> default) -> return. Never errors on missing
# feature; returns registered default with a status flag.
Offline retrieval API (point-in-time, batch)
POST /v1/offline/get-training-data # point-in-time correct join
{ "entity_df_uri": "s3://jobs/labels.parquet", # (key,event_ts,label)
"features": ["fraud_v2:txn_count_7d", "user_profile:age"],
"output_uri": "s3://jobs/trainset.parquet" }
-> { "job_id": "ptj_88", "status": "RUNNING" } # async batch job
GET /v1/offline/jobs/{job_id} # poll; -> COMPLETE + output_uri
POST /v1/materialize # (re)materialize a view's
{ "feature_view": "fraud_v2", # history window into online
"start": "2026-11-01", "end": "2026-11-29" } # e.g. rebuild online
Data model - two stores, one registry
The registry and offline history are the durable sources of truth; the online store is a rebuildable projection. SQL vs NoSQL is answered per store by access pattern, not globally.
1. Registry (small, relational, strongly consistent -> SQL):
feature_view
name STRING PRIMARY KEY (with version)
version INT # bump on definition change
entity STRING # -> entity.name
features JSON # [{name, dtype, default}, ...]
source JSON # {type: batch|stream, ...}
transform TEXT # the ONE definition both paths run
ttl_seconds INT # freshness/window, shared by paths
online BOOL
offline BOOL
created_at TIMESTAMP
- SQL/relational: it is small, highly relational (views -> entities
-> sources), read on every serving request (cached), and must be
consistent so both paths run the SAME transform + ttl. A changed
definition is a NEW version -> reproducible training sets.
2. Online store (KV, latest value only, GB-scale -> NoSQL/KV):
key = {entity_join_key_value} : {feature_view_name} # co-located
value = { # one blob per (entity, view)
"txn_count_7d": 14,
"avg_amt_30d": 42.10,
"_event_ts": 1764345600, # event-time of this value (for LWW)
"_write_ts": 1764345603 # for TTL/freshness checks
}
- KV / NoSQL: pure O(1) point get on a known key is all we need; no
joins, no scans at read time. Sharded by ENTITY KEY (consistent
hash), replicated N=3 across zones. In-memory / RocksDB engine.
Upsert is event-time LWW: write iff new _event_ts > stored.
DERIVED + rebuildable from the offline store.
3. Offline store (columnar history, PB-scale, system of record -> lake):
feature_history (Parquet on object storage)
entity_key STRING
feature_name STRING # or one column per feature in a view
value <typed>
event_ts TIMESTAMP # when this value became true
ingest_ts TIMESTAMP # when we wrote it (for audit/lag)
PARTITION BY date(event_ts) # prune by time
CLUSTER/SORT BY (entity_key, event_ts) # for as-of merge join
- Columnar lake: append-only, immutable history; optimized for the
big batch sort-merge as-of join, NOT point reads. Durable system
of record from which the online store can be fully re-materialized.
Years of history, PB-scale, compressed columnar.
4. Materialization checkpoint (per view, for watermark hand-off):
materialization_state
feature_view STRING PRIMARY KEY
mode ENUM # batch | stream
watermark_ts TIMESTAMP # event-time up to which materialized
last_run TIMESTAMP
- lets batch backfill and stream processing hand off at a precise
event-time watermark with no gap and no double-count.
Why these choices: the registry is small, relational, and consistency-critical (both paths must run one transform and one TTL), so it is SQL. The online store needs only O(1) point gets at millions of QPS, so it is an entity-sharded KV store holding co-located view blobs and nothing but latest values - which is exactly what keeps reads sub-ms, and it is fine that it is a rebuildable projection. The offline store needs cheap append and one giant time-ordered as-of join, so it is a columnar, time-partitioned lake, and it is the durable truth. Three storage decisions, each dictated by one access pattern, unified by one registry.
Bottlenecks & Scaling
Where it breaks first, in order, and the fix for each:
1. Online read fan-out (breaks before anything else). 100 features x 100K req/s = 10M reads/sec if you read per feature; batch ranking makes it worse. The serving path collapses on round trips. Fix: co-locate features into views under one entity-keyed blob so a request is a few multi-gets, not 100 reads. Shard the online store by entity key (consistent hashing) so one entity’s data is one shard and a batch of entities fans to a bounded set. In-memory/LSM engine for O(1) sub-ms gets.
2. Point-in-time join at training scale. A billion labels x 100 features as per-row as-of lookups is years of compute. Fix: keep offline history columnar and time-partitioned, and execute the as-of join as a distributed sort-merge (sort both sides by entity+event_ts once, merge in a linear pass), with partition pruning by time. Turns 100B lookups into a few big sorted passes.
3. Training-serving skew (the defining failure, silent). Two implementations of a feature, or two independent materializations, drift and quietly degrade the model. Fix: one transform definition in the registry executed by both paths; dual-write one computed record (append offline + event-time-LWW upsert online) so online is a deterministic projection of offline; shared TTL so freshness matches; and a sampling consistency audit that alerts on any residual mismatch. Skew is designed out, then monitored.
4. Out-of-order and late events corrupting latest value. A delayed old event arriving after a newer one would overwrite the correct latest value if you wrote by arrival time.
Fix: event-time last-write-wins - the online upsert stores _event_ts and writes only if the incoming event’s time is newer. Offline keeps all versions (append-only), so history is complete regardless of arrival order; the as-of join sorts by event time anyway.
5. Hot entities (hot keys). A viral user or a mega-merchant concentrates reads on one shard. Fix: wider replication for hot keys (more read replicas for their shard), a small per-serving-node local cache with a short TTL for the hottest entities (a few seconds stale is fine), and detection of hot keys to replicate them proactively. For hot write keys (a merchant with huge txn volume), pre-aggregate in the stream operator before the online upsert.
6. Materialization falling behind (freshness breach). If streaming materialization lags, the online store serves stale features - wrong, silently. Fix: scale the stream processors (partition the Flink job by entity key to match the online shards), monitor materialization lag (ingest_ts - event_ts) as a first-class SLO, alert when a feature’s freshness exceeds its TTL, and backpressure/shed gracefully. Batch features get the same treatment via job-completion SLAs.
7. Online store node loss. A lost shard takes its latest values with it. Fix: N=3 cross-zone replication so reads continue from replicas; and because the online store is a projection of the durable offline history, a lost shard is fully re-materializable by replaying the latest slice from offline - the online store is a cache you can always rebuild, never the system of record.
8. Registry as a single point of failure / per-request dependency. Every serving request resolves views from the registry. Fix: the registry is small and slow-changing, so cache the full registry at every serving node with watch-based invalidation; reads are local and the registry being briefly unavailable does not stop serving (serve on the cached definitions). Writes (new definitions) go through a consistent SQL store with versioning.
9. Offline join cost and cost blowout. PB-scale as-of joins and never-sleeping stream operators are expensive. Fix: partition pruning and column pruning (read only the features and time ranges a job needs); choose streaming only where recency is the signal and batch everything else (far cheaper); compact offline history (roll up old fine-grained values); and TTL the online store so it holds only live hot values, not history.
10. Schema / definition evolution. Changing a feature’s transform could silently change values and break reproducibility of old training sets. Fix: version feature-view definitions in the registry; a transform change is a new version, old versions remain so an old training set is reproducible; and re-materialize deliberately when a definition changes, with the consistency audit confirming online matches the new offline.
Wrap-Up
The trade-offs that define this design:
- Two physical stores for one logical feature, on purpose. The 10,000x asymmetry between “latest value, sub-ms, millions of QPS” and “full history, one giant batch join” cannot be served by one store, so we run a GB-scale entity-sharded KV online store and a PB-scale columnar time-partitioned offline lake - and accept the write amplification of materializing to both.
- One source of truth behind the two stores. We do not keep two databases in sync; we compute both from one transform definition and dual-write one record, making online a deterministic latest-value projection of the offline history. That is what actually kills training-serving skew, rather than hoping two implementations stay aligned.
- Correctness over convenience in the offline join. Point-in-time as-of joins are more work than a plain
JOIN USING(entity_id), but a time-blind join leaks the future into training and produces models that lie about their own accuracy - so the as-of sort-merge join is non-negotiable, and we make it tractable with sorting and partition pruning rather than per-row lookups. - Event-time, not arrival-time, everywhere. Last-write-wins by event time on the online upsert and sort-by-event-time in the offline join mean out-of-order and late data never corrupt the latest value or leak across a label boundary - the whole system reasons about when a fact was true, not when we happened to receive it.
- Freshness is a per-feature dial, with a matching training story. Streaming for recency-critical features, batch for slow aggregates, the same write contract for both, and training built with the same freshness/TTL semantics it will serve under - so a feature is consistent not just in value but in how stale it is allowed to be.
- The online store is a rebuildable cache, the offline store is the truth. Durability lives in the append-only history; losing an online shard costs a re-materialization, never data - which lets us optimize the online store purely for speed and the offline store purely for completeness.
One-line summary: a dual-store feature platform where one registered transform is dual-written - event-time last-write-wins to a GB-scale entity-sharded KV online store for sub-ms serving, and appended to a PB-scale columnar history for a point-in-time-correct sort-merge join at training time - so that training and serving consume the same logical feature in the two shapes their access patterns demand, and training-serving skew is designed out rather than debugged after the model has already rotted.
Comments