Real-Time ML Feature Platform for Ranking
Medium · ML System Design · Machine Learning Engineer · Technical Screen
Prompt
Architect a centralized feature platform that powers real-time ranking models in large-scale advertising auctions or personalized recommendation feeds.
The platform must serve two distinct execution paths from unified feature specifications:
- Live ranking reads: sub-10-millisecond vector assembly for hundreds of candidate items per user request.
- Time-consistent training generation: reconstructing historical training tables where every feature reflects strictly what was known at each past event's timestamp, with zero future data leakage.
Scope & Expectations
- Developer abstractions and contracts: Specify how engineers register entities, transformations, and versioned feature bundles, as well as the client APIs for live batch retrieval and historical dataset construction.
- Ingestion, storage, and online/offline parity: Detail how streaming events and scheduled batch snapshots are processed, persisted, and served without introducing logic or timing discrepancies between training and production.
- Windowed state, delayed arrivals, and backfills: Explain how rolling aggregations decay cleanly, how late or out-of-order mobile events are incorporated safely, and how brand-new features are backfilled over historical logs.
- Scale, resilience, and observability: Address high-fan-out read throughput, graceful fallback under storage tail latency, and automated checks for freshness, schema health, and distribution shift.
Step-by-step walkthrough
Clarify requirements, ML framing, and labels
A feature store is the shared data layer that computes, stores, and serves input signals ("features") to machine learning models. Because every architectural choice depends on the model consuming those features, let's anchor our design in a concrete workload: an ads click-through-rate (CTR) and conversion ranking system (commonly used in programmatic advertising platforms and recommendation feeds).
On every ad request, a ranking model scores
~500candidate ads in real time using four feature families: user features, ad features, user x merchant cross features, and request-context features.Functional requirements
- Write once, use twice: ML engineers declare a feature's source and transformation once; the platform compiles both the online pipeline (fresh values for live traffic) and the offline pipeline (historical values for model training).
- Live ranking reads: Given
(user_id, 500 ad_ids, request_context), assemble a500 x Ffeature matrix in the model's exact column order within single-digit milliseconds. - Time-consistent training datasets: Given historical labeled impressions
(user_id, ad_id, request_ts, label), reconstruct the exact feature values that were readable online atrequest_ts— never leaking events from the future (label leakage) and never computing numbers differently between training and production (training-serving skew). - Streaming + batch + backfills: Support real-time windowed features (e.g., "user clicks in the last 5 minutes"), daily batch features (e.g., "90-day category affinity"), historical backfills for brand-new features, and late-arriving mobile events.
- Observability: Track feature freshness, missing-value rates, distribution drift, and online/offline mismatches.
Non-functional requirements
- Latency: Online feature fetch
p99 <= 10 ms(inside a~100 msend-to-end ad auction budget). - Throughput:
100,000ranking requests/s at global peak across3active serving regions. - Freshness: Streaming events reflected in online reads within
<= 30 satp99. - Graceful degradation: A feature-store slowdown must fall back to safe default values rather than failing ad requests.
Labels and delayed attribution (why timestamps are tricky)
Each shown ad impression produces one training example anchored at
request_ts. A click label arrives within a30-minuteattribution window; a conversion (purchase) label can arrive up to7 dayslater. Even when a conversion happens on Friday for an ad shown on Monday, every feature on that training row must reflect Monday'srequest_ts, never Friday!Back-of-the-envelope numbers
Assume
1Btotal users (200Mdaily active,400M90-day active),10Mactive ads across1Mmerchants,5shown impressions per request, and a1%average CTR:1. Streaming event volume Impressions 100,000 req/s * 5 shown = 500,000 events/s (~300 B -> 150 MB/s) Clicks (1% CTR) ~5,000 clicks/s; Conversions ~500/s Daily raw event lake 500,000 * 86,400 = 43.2B events/day (~13 TB/day before compression) 2. Why naive per-ad KV lookups break online serving (the fan-out trap!) Naive remote multi-get 100,000 req/s * 500 ads = 50,000,000 KV key reads/s! Ad table total RAM size 10M active ads * 100 float32s (4 B) = 4.0 GB (+ ~1.5 GB map keys) Solution: replicate the ~5.5 GB ad feature table into RAM on every ranking server! Remaining remote KV read 1 partition read per request (keyed by user_id) -> 100,000 reads/s globally (~33,000/s per region; size each region for 50,000/s failover) 3. Online KV write rate & storage (per region) Write throttling emit at most 1 streaming update per active entity per 5 s -> ~60,000 user streaming writes/s + ~60,000 user*merchant writes/s + ~28,000/s daily batch load = ~150,000 row writes/s per region User profile rows 400M users * ~2 KB = ~0.8 TB User streaming buckets 200M users * ~1 KB = ~0.2 TB User * merchant maps up to 400M * 200 pairs * 16 B = ~1.3 TB upper bound Total per region ~2.3 TB logical * 3 replicas = ~7 TB -> SSD-backed KV (not pure RAM) 4. Offline history & sampled served-feature log Offline history sink ~150,000 updates/s -> ~2 TB/day compressed Parquet per region 10% Served-feature log 10,000 req/s * ~3.5 KB (user/context once + 5 shown ads by version ID) = ~35 MB/s (~3 TB/day raw) -> yields ~260M training rows/day after keeping 100% of ~43M clicks + 5% sample of ~4.3B non-clicksKey takeaways from the math: - Fan-out, not QPS, dictates the architecture: Pushing the shared
~5.5 GBad feature table into ranking-host memory eliminates50M/snetwork reads, leaving one SSD KV partition read per request (user_id). - Write throughput matches read throughput (~150k writes/svs.~50k partition reads/s): Choose a write-optimized LSM-tree (Log-Structured Merge-tree, a storage engine that buffers writes sequentially in memory before flushing sorted files to SSD, such as ScyllaDB, Cassandra, or Bigtable) or Aerospike on NVMe SSDs rather than an expensive all-RAM cache.Core abstractions and APIs
Expose three clean abstractions in a central Feature Registry: 1.
Entity: The primary key a feature describes (user_id,ad_id, oruser_id + merchant_id). 2.FeatureView: One declarative definition specifying the raw data source, filter, aggregation windows, TTL (Time-To-Live, how long a value stays valid without updates), and freshness target. 3.FeatureService: An immutable, versioned bundle of features consumed by one specific model version (e.g.,rank_ctr_v8), ensuring training and serving always request the exact same columns.# Declarative registration compiled into BOTH streaming (Flink) and batch (Spark) jobs user_click_stats = FeatureView( name="user_click_stats", entity="user_id", source=StreamSource(topic="ad_events", event_time_col="event_ts"), filter_expr="event_type == 'click'", # Aggregations share one set of tiered time buckets in state aggregations=[ Aggregation(op="count", windows=["5m", "1h", "1d", "7d"], default=0), ], allowed_lateness="10m", online_ttl="8d", freshness_slo="30s", owner="ads-ranking", ) rank_ctr_v8 = FeatureService( name="rank_ctr_v8", features=[ "user_click_stats:count_5m", "user_click_stats:count_1h", "user_profile:category_affinity_90d", "ad_realtime:ctr_smoothed_1h", "user_merchant:clicks_decayed_3d", "on_demand:seconds_since_last_merchant_click", ], )Serving, Training, and Ingestion APIs:
1. Online Retrieval (thin C++/Rust/Go client library linked inside the ranking service) get_online_features( feature_service = "rank_ctr_v8", user_id = "usr_409", ad_ids = [500 candidate ad IDs], request_context = {"request_ts": 1764528000.25, "device": "ios", "country": "US"}, timeout_ms = 6, ) -> FeatureBatch(matrix_500xF, is_defaulted_bitmask, max_staleness_ms) 2. Offline Training Dataset Generation get_historical_features( feature_service = "rank_ctr_v8", spine_df = table(request_id, user_id, ad_id, merchant_id, request_ts, label), mode = "served_log" | "point_in_time", ) -> TrainingTable 3. Pipeline Operations backfill(feature_view, start_date, end_date) # Recompute history from raw Parquet lake materialize_batch(feature_view, snapshot_uri) # Validate & publish daily batch snapshotReturning
is_defaulted_bitmaskalongsidematrix_500xFlets both the neural network and monitoring distinguish "user genuinely has 0 clicks" from "KV timed out so default 0 was substituted."Data model: online KV, local ad replica, and offline history
To fetch all user and cross features in one single KV network round-trip, co-locate a user's feature groups under the same partition key
user_idwith separate clustering keys (group_name) so streaming and batch writers never overwrite each other:1. Online SSD KV Store (partition_key = user_id, clustering_key = group_name) (usr_409, "streaming") -> protobuf {schema_v, version_seq, min_buckets[60], hr_buckets[24], day_buckets[7]} (usr_409, "profile") -> protobuf {schema_v, version_seq, snapshot_date, 300 dense/sparse vals} (usr_409, "merchants") -> protobuf {schema_v, version_seq, top_200_map: merch_id -> (decayed_imps, decayed_clicks, last_ts)} 2. Ranking-Host Local Ad Table (in-process RAM hash table, ~5.5 GB) ad_id -> {version_seq, merchant_id, static_embeddings, smoothed_1h_imps, smoothed_1h_clicks} (Fed continuously via a Kafka compacted change-stream topic `ad_feature_updates`) 3. Offline Feature History Lake (Apache Iceberg / Parquet, partitioned by feature_view + dt) entity_key | feature_view | serialized_payload | event_time_end | available_at | serving_region | version_seq | is_backfill | job_git_sha 4. Sampled 10% Served-Feature Log (Parquet, partitioned by dt + hr) request_id | request_ts | serving_region | feature_service | user_and_context_features | shown_ads: list[(ad_id, ad_version_seq, cross_features)]Why store two timestamps (
event_time_endandavailable_at) on every offline row?event_time_endrecords when the raw click happened on the user's phone;available_atrecords the exact timestamp when the online KV write succeeded and became readable by live ranking servers. Joining training data onavailable_ateliminates pipeline-delay leakage!High-level architecture
Ad Impressions & Click/Conversion Trackers | v Kafka: ad_events (mirrored across 3 regions) | | v v +-------------------------+ Raw Event Lake (Parquet by day) | Stream Engine (Flink) | | | keyed by entity_id; | v | event-time buckets, | +-----------------------------+ | watermarks, 5s emit | | Batch / Backfill (Spark) | +------------+------------+ | compiled from SAME | | | FeatureView registry spec | | +--------------+--------------+ v | (passes DQ validation gate) Kafka: feature_updates <--------------------+ | \ | +--------> Ad Updates Compacted Topic v | +-------------------------+ | push to all ranking hosts | Online KV Writer | v | conditional upsert: | +-----------------------------------+ | if new.ver > old.ver | | Ranking Service Host | +------------+------------+ | - Local RAM Ad Replica (~5.5 GB) | | \ | - Feature Client Library: | v \ stamped with | 1 KV read(user) + 500 RAM ads | +-------------------+ \ available_at | + on-demand features -> Model | | Online SSD KV |<---+ +---------+-----------------+-------+ | (Scylla/Bigtable) | \ | 1 read/req | 10% sample +-------------------+ v | v +-------------------------+ | +----------------------+ | Offline History Table | +----->| Served-Feature Log | | (payload + available_at)| +----------+-----------+ +------------+------------+ | | v +-------------->+------------------------------+ | Training Dataset Builder | | PIT join OR served log | | + delayed click/conv labels | +------------------------------+Notice the critical symmetry: both Flink streaming updates and validated Spark daily snapshots flow through
feature_updates -> Online KV Writer -> Offline History Sink. Because the Online KV Writer stamps each row with the exactavailable_atinstant its KV upsert succeeded before forwarding those identical bytes to Offline History, the online and offline stores can never drift in serialization or visibility timing.Deep dive 1: point-in-time correctness and eliminating skew
Why naive joins leak the future ("time travel"): Suppose an ad impression happens at
14:00:03, and the user clicks a previous ad at14:00:01whose streaming update takes4 secondsto travel through Kafka and Flink, landing in the online KV atavailable_at = 14:00:05:Timeline for user usr_409: 13:59:50 Previous value (count_5m = 2) written to Online KV (available_at = 13:59:50) 14:00:01 User clicks an ad (event_time = 14:00:01, still in flight in Kafka/Flink!) 14:00:03 NEW AD REQUEST arrives -> Online KV still holds count_5m = 2! 14:00:05 Flink write lands in Online KV: count_5m = 3 (available_at = 14:00:05) If offline training joins on `event_time <= 14:00:03`: Training gets count_5m = 3 (WRONG — live serving at 14:00:03 only saw 2!) If offline training joins on `available_at < 14:00:03`: Training gets count_5m = 2 (EXACT match with live serving!)Here is the core point-in-time ("as-of") join logic in Python (executed at scale in Spark via a partitioned sort-merge walk over
entity_keysorted byavailable_at):from bisect import bisect_left def point_in_time_join( examples: list[tuple[str, float]], history: dict[str, tuple[list[float], list[object]]], ttl_seconds: float, ) -> list[object | None]: """Look up each (entity_key, request_ts) as of strictly before request_ts. history maps entity_key -> (sorted_available_times, payloads). Returns None when no prior value exists or the latest prior value expired past ttl_seconds. """ joined_values: list[object | None] = [] for entity_key, request_ts in examples: avail_times, payloads = history.get(entity_key, ([], [])) # bisect_left finds the first index >= request_ts, so idx - 1 is strictly < request_ts idx = bisect_left(avail_times, request_ts) if idx == 0: joined_values.append(None) continue latest_avail_ts = avail_times[idx - 1] # Respect online TTL: if the online KV would have expired this row, return None if request_ts - latest_avail_ts > ttl_seconds: joined_values.append(None) else: joined_values.append(payloads[idx - 1]) return joined_valuesCombining both training-dataset modes: - Mode 1 — Served-Feature Log ("Log-and-Wait", used for production retraining): Log the exact feature vectors returned on
10%of live requests, then wait30 min(clicks) or7 days(conversions) to attach labels. Zero training-serving skew by construction — even timeouts and defaults are faithfully captured! Its only downside is cold start: a brand-new feature takes weeks to accumulate logged history. - Mode 2 — Point-in-Time History Join (used for rapid feature experimentation): Backfill a candidate feature over the past 30 days of raw logs, runpoint_in_time_joinagainst historical impressions, and train immediately today. Once offline AUC improves, promote the feature to live shadow logging and retrain on the Served-Feature Log.Correcting negative downsampling calibration: In our
10%served log, keeping100%of clicks (1%base rate) and onlyw = 5%(0.05) of non-clicks shrinks dataset size~17x, but inflates the model's raw predicted probabilityqto~0.168instead of0.01. Because we threw away19out of every20non-clicks, we multiply the predicted non-click probability(1 - q)by1 / 0.05 = 20before passing calibrated CTRpinto the ad auction:Calibrated CTR: p = q / (q + (1 - q) / 0.05) = q / (q + 20 * (1 - q)) Quick check: if q = 1 / 5.95 (~0.1681), p = (1/5.95) / (1/5.95 + 20 * 4.95/5.95) = 1 / 100 = 0.01!Deep dive 2: streaming windows, late events, and backfills
Solving the "idle user stale window" bug with read-time bucketed counters: Suppose user
usr_409clicks 3 ads at14:00, socount_5m = 3, and then closes the app. If the online KV simply stored the number3, then whenusr_409returns at14:45(with zero new click events in between to trigger a Flink write!), the online KV would still readcount_5m = 3!Instead of firing millions of expiration timers in Flink, store fixed-width time buckets inside the row (
60one-minute buckets +24one-hour buckets +7one-day buckets =91tiny integers,~364 B), and sum the active buckets at read time using the exact same pure function online (now = request_ts) and offline (now = example.request_ts):def sum_window_buckets( tier_buckets: dict[int, int], now_ts: float, window_seconds: int, ) -> int: """Sum counters in one resolution tier (e.g. 1-minute buckets) falling in [now - window, now). Naturally decays to 0 as `now_ts` advances, even when no new events arrive! """ cutoff_ts = now_ts - window_seconds total = 0 for bucket_start_ts, count in tier_buckets.items(): if cutoff_ts <= bucket_start_ts < now_ts: total += count return totalAnd for high-cardinality
user x merchantmaps (up to200merchants per user, where91buckets per pair would bloat each user row45x), store exponentially decayed counters(decayed_count, last_update_ts)(16 Bper pair) with a 3-day half-life (259,200 s), decayed lazily at read time viadecayed_count * (0.5 ** ((now_ts - last_update_ts) / 259200.0)).Handling late events, Flink replays, and backfills: - Watermarks & allowed lateness: A watermark is Flink's moving timestamp tracking event-time progress (
max_event_ts_seen - 2m), tolerating up to10 minutesof mobile offline delay (allowed_lateness = 10m). Late events within10mupdate their historical minute bucket and emit a new KV row stamped with now asavailable_at(never overwriting past offline rows, which would leak late corrections into earlier requests!). Events arriving> 10mlate route to the raw lake and are folded into the next daily correction snapshot. - Idempotent online writes: After a worker crash, Flink rewinds to its last checkpoint (a periodic durable snapshot of operator state) and replays a few seconds of updates. Every update carries a monotonic per-entityversion_seq; the Online KV Writer executes a conditional upsert (UPDATE ... WHERE new_version_seq > stored_version_seq), making duplicate or reordered writes completely harmless. - Backfilling + state bootstrapping: When launching a new7-dayrolling feature, run the shared aggregation over the past37 daysof Parquet logs (30 daysof training history withis_backfill = trueandavailable_at = bucket_end + median_stream_lag, plus7 daysto build an initial Flink savepoint so live serving starts warm on day 1 instead of reading near-zero counts for a week).Deep dive 3: sub-10 ms online serving and multi-region layout
Here is how a single ranking request stays comfortably inside
p99 <= 10 ms:End-to-end 10 ms p99 latency budget (inside Ranking Host): 1. Single-partition SSD KV read for `user_id` (fetches profile + streaming + merchants rows together; fire a HEDGED READ to a second KV replica if replica 1 hasn't answered within 3 ms p95) <= 5.0 ms 2. Lookup 500 candidate ads in local in-process RAM hash table <= 0.5 ms 3. Compute on-demand features (e.g., request_ts - last_merch_click_ts, sum_window_buckets, half-life decay) in compiled C++/Rust <= 0.5 ms 4. Assemble contiguous 500 x F float32 tensor + fill registered defaults for missing/timed-out fields <= 1.0 ms -------------------------------------------------------------------------------- Total p99 feature retrieval <= 7.0 ms (3 ms slack)(A hedged read sends a backup read request to a second replica if the first replica hits a minor SSD garbage-collection pause past
3 ms, slashingp99tail latency at the cost of only~5%extra KV reads.)Timeout resilience: If the KV store still exceeds the
6 msclient deadline, the library immediately substitutes each missing feature's registered default value and setsis_defaulted = 1— the exact indicator bit the model saw on occasional timeouts in the Served-Feature Log — so ad serving degrades smoothly instead of dropping revenue.Active-active multi-region: Raw
ad_eventsare mirrored to all3regions (< 2 scross-region lag, well inside our30 sfreshness SLO), and each region runs its own Flink job and SSD KV containing all active users. That triples streaming compute, but eliminates cross-continent WAN calls on the10 msserving path and lets any surviving regions absorb traffic seamlessly if an entire region fails.Offline evaluation, data-quality monitoring, and A/B testing
1. Offline validation before training or serving: - Leakage sanity check: Compare offline AUC (Area Under the ROC Curve, measuring ranking order quality from
0.5random to1.0perfect) and Normalized Log Loss (measuring probability accuracy) betweenpoint_in_timejoin and a naivelatest_valuejoin — any feature whose offline gain vanishes underpoint_in_timewas pure leakage. - Online/offline parity audit: Sample1%of rows from the Served-Feature Log, recompute them viapoint_in_time_joinon Offline History, and require< 0.1%discrepancy per feature before promoting a newFeatureView.2. Production data-quality gates and live alerts:
Layer Signal monitored Automated action / alert Batch publish gate Row count ( +/- 10%), null rate, min/max/mean vs. 7-day baselineBlock snapshot materialization; keep yesterday's valid row online Streaming health now - latest_available_at, Kafka lag, watermark delay, late-drop %Page on-call if freshness exceeds 2x SLO(> 60 s) for5 minOnline serving KV p99latency, timeout %, per-featureis_defaultedrate (< 1%)Auto-shed non-critical cross features or switch to lightweight fallback model Feature drift PSI (Population Stability Index — a single score measuring how far today's live feature distribution shifted from training) Alert model owners when PSI > 0.2on top-importance featuresModel output Live calibration ( mean(predicted_CTR) / observed_CTRper region)Alert if outside [0.95, 1.05]3. Safe A/B testing for a new real-time feature: 1. Shadow phase (1 week): Materialize and log the feature online without feeding it to the live model; verify
p99 <= 10 msand< 0.1%online/offline skew. 2. Online budget-split A/B test: Randomize users (5%control vs.5%treatment) and split shared merchant daily ad budgets proportionally between arms (otherwise an aggressive treatment model can spend a merchant's shared budget early in the day and artificially starve the control arm!). Measure revenue per 1,000 requests (RPM), CTR, and merchant return on ad spend, guarded by latency and calibration SLOs.Scaling, failure handling, and trade-off summary
- Sizing the regional SSD KV: At failover peak (
50,000partition reads/s =150,000row reads/s, plus150,000row writes/s *3replicas =450,000replica writes/s), total cluster load is~600,000row ops/s across~7 TB. At~40,000-50,000NVMe ops/s per node,~20ScyllaDB/Bigtable nodes per region (~350 GB/node) handle peak traffic plus background LSM compaction comfortably. - Hot-key protection: Bot crawlers generating
1,000impressions/s for a singleuser_idare capped at the Flink key operator (max 20 events/scounted per user) and write-throttled (1 KV write / 5 s), while popular viral ads never create KV hot spots because ad features live in every ranking host's local RAM. - Zero-downtime schema evolution: Never mutate an existing feature's formula in place (which silently breaks live models trained on the old meaning). Register
count_5m_v2, backfill it, trainrank_ctr_v9bound to a newFeatureService, and garbage-collectv1oncev8retires.
Core trade-offs at a glance
Decision Chosen approach Why the trade-off pays off Point-in-time timestamp Join on available_at < request_tsPrevents pipeline-lag label leakage, at the cost of recording per-region write timestamps Training source 10%Served Log (prod) + PIT Backfill (experiments)Zero skew on production models + day-1 agility for testing new features Rolling windows Tiered buckets / half-life decay evaluated at read time Idle users' counts decay to 0 with zero timer writes, accepting <= 1 bucketboundary roundingServing topology Push 5.5 GBad table to RAM + Pull2.3 TBuser KVEliminates 50M/sad fan-out reads so requests finish in<= 7 ms p99Multi-region state Replicate raw events and compute in all 3 regions 3xstreaming compute in exchange for zero cross-region serving hops and instant regional failover- Sizing the regional SSD KV: At failover peak (
Intuition & how it works
Think of a real-time feature store as a restaurant's live prep station paired with a time-stamped kitchen diary. During the dinner rush (online inference), when a customer walks in and the chef has 10 milliseconds to rank 500 dishes (candidate ads), all chopped ingredients ("user's clicks in the last 5 minutes", "this ad's hourly click rate") must already sit prepped in fast containers ready to grab in one reach. Weeks later, when developing a better recipe from past orders (offline training), the chef flips open the diary to see the exact ingredients that were actually sitting on the counter at the millisecond each historical dish was served — never accidentally peeking at events that arrived five minutes later.
Without a unified feature store, teams hit two classic failures. First, data scientists write SQL scripts over warehouse tables for offline training while backend engineers rewrite those same formulas in Java or C++ for live serving, causing subtle rounding, window-boundary, or missing-value mismatches known as training-serving skew (feeding the live model different feature distributions than it learned on). Second, if offline training joins Monday's ad impressions against today's latest user counters — or even joins on raw event_time without accounting for the few seconds a streaming pipeline took to write the counter online — future clicks leak backward into past training rows (label leakage), producing inflated offline scores that collapse in production.
Here is a tiny 4-step trace for user usr_409 and feature user_click_stats:count_5m showing how single-source definitions, read-time buckets, and available_at timestamps keep online and offline 100% aligned:
14:00:01(click happens on phone):usr_409clicks a sneaker ad (event_ts = 14:00:01). Flink incrementsusr_409's14:00one-minute bucket ({14:00 -> 1}), taking 4 seconds end-to-end before the online KV upsert finishes atavailable_at = 14:00:05.14:00:03(ranking request A arrives while update is still in flight): Live serving readsusr_409's KV row, sees empty buckets{}(count =0), and ranks candidates. Weeks later, offline point-in-time join checksavailable_at < 14:00:03: because14:00:05is not before14:00:03, offline training also gets0— zero future leakage!14:00:12(ranking request B arrives): Live serving reads{14:00 -> 1}, sums buckets inside[13:55:12, 14:00:12)->1, and logs the vector to the10%Served-Feature Log. Offline training at14:00:12seesavailable_at = 14:00:05 < 14:00:12and runs the exact same bucket-sum function ->1.14:06:00(ranking request C after 6 idle minutes): Even thoughusr_409triggered zero new writes since14:00:05, summing{14:00 -> 1}inside[14:01:00, 14:06:00)automatically evaluates to0both online and offline!
Key trade-offs
- One declarative
FeatureViewcompiled to stream + batch vs. separate pipelines. Compiling Flink streaming jobs, Spark backfill jobs, and schemas from one registry spec eliminates logic-driven training-serving skew. The trade-off is a constrained DSL: custom Python/SQL transformations outside built-in windowed aggregations require shared, unit-tested libraries. - Point-in-time joins on
available_atvs.event_time. Joining historical impressions againstavailable_at < request_tsfaithfully models real streaming lag so training never sees data that hadn't reached the KV store yet, at the minor cost of stamping per-region write-completion times onto every offline history row. - Sampled
10%Served-Feature Log vs. Point-in-Time History Backfills. Logging live served vectors guarantees exact parity (including timeouts and defaults) for production retraining, but costs~3 TB/dayand forces new features to wait weeks to accumulate logs. Point-in-time backfills let engineers evaluate new features on 30 days of history on day 1, at the cost of slightly idealized past pipeline latency; mature systems use backfills to iterate and the Served Log for production retraining. - Read-time time buckets / exponential decay vs. pre-summed rolling counters. Storing
91tiered minute/hour/day buckets (or 16-byte half-life decayed counters for high-cardinalityuser x merchantmaps) lets idle users' rolling counts decay toward zero with zero timer-driven database writes, trading~1 KBof row width and<= 1 bucketboundary rounding for massive write savings. - Pushing
~5.5 GBad features to host RAM vs. remote per-ad multi-gets. Replicating10Mads' features to every ranking server via a change stream eliminates50,000,000remote reads/s and multi-shard tail latency, leaving just one user-keyed SSD KV read per request (<= 5 mswith hedged reads). If the item catalog grows to1Bitems (500 GB), ad features move onto the sharded candidate-retrieval leaf nodes instead of ranking-host RAM. - SSD-backed LSM-tree KV + 5-second write throttling vs. all-RAM per-event writes. Coalescing updates per active user over
5 scaps regional writes near~150,000/s(comfortably inside our30 sfreshness SLO) and lets~7 TBof replicated state live economically on~20NVMe SSD nodes per region instead of terabytes of expensive DRAM.
Common mistakes
- Joining offline training features on "latest value" or raw
event_time. Both leak clicks that had not yet materialized in the online KV atrequest_ts, inflating offline AUC (Area Under the ROC Curve) and causing severe online regressions. - Attaching features as of
label_tsinstead ofrequest_tsfor delayed conversions. If a user converts 4 days after seeing an ad, computing features as of day 4 feeds the model post-impression behavior (like repeated site visits caused by the ad itself!). - Storing finished rolling sums (
clicks_last_1h = 4) without buckets or decay. When a user goes inactive, no new event arrives to decrement the sum, leaving stale non-zero counts stuck online until the row's multi-day TTL (Time-To-Live) expires. - Overwriting historical offline rows in place when late events or backfills run. Mutating old rows erases what live serving actually saw before the correction arrived; always append a new immutable history row stamped with the correction's
available_at. - Fetching 500 candidate ads per request over the network from a distributed KV. Even if median single-key latency is
0.8 ms, thep99of the slowest shard across a500-keyfan-out routinely breaches10 msand generates50Mkey reads/s. - Applying non-idempotent increments (
count += 1) to the online KV. When Flink restarts from a checkpoint (a saved state snapshot) and replays a few seconds of events, blind increments double-count clicks; use full-bucket state writes guarded by monotonicversion_seqconditional upserts instead. - Forgetting probability recalibration after negative downsampling. Training on
100%of clicks plus5%of non-clicks skews predicted probabilities upward by nearly17x, causing massive overbidding in second-price/first-price ad auctions unless corrected viap = q / (q + 20 * (1 - q)). - Cold-starting a new 7-day streaming feature from empty state. Without bootstrapping Flink's initial savepoint from a 7-day historical backfill, live serving feeds artificially tiny counts into the model for an entire week.
Follow-up questions
- How should the platform compute request-time features that combine live context with stored state, such as elapsed time since a user last interacted with a merchant? Register them as pure, deterministic transformation functions bundled inside the versioned
FeatureService(compiled to WebAssembly, C++, or Rust with Python bindings so one binary runs in both environments). At serving time, the ranking client executes the function in< 0.5 msusingrequest_context["request_ts"]and thelast_tsalready fetched inside the user'smerchantsmap; during offline dataset generation, the training builder invokes the exact same compiled function over historicalrequest_tsand the point-in-time-joinedmerchantsrow (or reads the logged output straight from the10%Served-Feature Log). - How do you store and roll out dense entity embeddings that retrain daily without breaking compatibility with live ranking models? Quantizing
128float32 dimensions (512 B) down toint8orfloat16(128-256 B) keeps200Mactive user vectors around~25-50 GBin the regional SSD KV and10Mitem vectors around~1.3-2.5 GBinside ranking-host RAM. Because an embedding space rotates on every daily retrain, feeding Tuesday's vectors into Monday's ranking weights silently corrupts predictions—so strict version coupling is mandatory: encode the producer version in the feature name (e.g.,user_two_tower_emb_v42), pin eachFeatureServiceto one immutable embedding version, and materialize bothv41andv42concurrently until all models consumingv41are retired. - What changes if a small subset of in-session signals needs sub-second freshness instead of a 30-second streaming target? Isolate an explicit fast-lane tier strictly for those compact, short-horizon features (
last_5_clicked_categories,session_impressions_2m) instead of paying 30x higher write amplification across all 300 user features. Either disable the5-secondFlink write throttle on that singleFeatureView(emitting immediately on each click at~5,000 clicks/s, far smaller than500,000 impressions/s), or let the edge serving tier append in-session interactions directly into a30-minuteTTL in-memory session record keyed byuser_idwhile capturing the exact served values in the Served-Feature Log so training reflects identical sub-second behavior.
Follow-up questions
- How should the platform compute request-time features that combine live context with stored state, such as elapsed time since a user last interacted with a merchant?
- How do you store and roll out dense entity embeddings that retrain daily without breaking compatibility with live ranking models?
- What changes if a small subset of in-session signals needs sub-second freshness instead of a 30-second streaming target?
Similar questions
- Running Median of an Integer Stream
- High-Throughput Spark Streaming Deduplication at Scale
- RAG-Based Product Recommendation API Design
- Integrating Vision-Language Models Safely into Autonomous Driving
- Asynchronous RL Alignment Architecture for Live Chat Models
- Hybrid Talent Search and Ranking Architecture