ML Feature Pipelines and Feature Stores Questions
Data infrastructure for machine learning: feature pipelines, feature stores, online/offline consistency, training-serving skew, and data preparation for models. Covers building reliable feature platforms and preventing leakage in the data path feeding models. The data-engineering-for-ML topic.
Design online feature storage for extremely high-cardinality entities (billions of keys) requiring low-latency lookups under 10ms, with constrained memory (for example under 64GB per node). Discuss storage engines (LSM-based stores, RocksDB), sharding, compression and serialization formats, caching, TTLs, and strategies to reduce read amplification and cost.
Sample Answer
Direct answer: At billions of keys with a strict memory ceiling, you cannot keep everything in RAM, so the design centers on an LSM (log-structured merge)-tree-based storage engine (RocksDB is the standard choice) that keeps most data on fast local SSD or NVMe and uses memory only for a bounded block cache, write buffer, and bloom filters.
Structured elaboration:
- Storage engine. RocksDB (or a similar LSM engine) organizes writes into an in-memory memtable that flushes to sorted SSTables on disk, then compacts them in the background. This gives fast writes (append to memtable) and bounded memory use, unlike a pure hash-map-in-RAM design.
- Sharding. Partition the billions of keys across many RocksDB instances (one or a few per host), hashed by entity ID, so each instance holds a manageable slice (for example, tens of millions of keys per shard rather than billions on one node).
- Compression and serialization. Use a compact binary serialization (e.g. a fixed-width struct or a lightweight schema like FlatBuffers/Cap'n Proto rather than JSON) to minimize both the on-disk footprint and deserialization CPU; pair with block compression (Snappy or Zstd) in RocksDB, which typically cuts storage 2-4x at low CPU cost.
- Caching within the memory budget. Give RocksDB's block cache the majority of the memory budget (say, 70-80% of the 64GB ceiling) so recently-and-frequently-read blocks stay hot; bloom filters (a few bits per key) let a lookup for a nonexistent key skip disk reads almost entirely, which matters when many lookups miss.
- Reducing read amplification. LSM trees can require checking multiple SSTable levels per read. Tune compaction (leveled vs. tiered) to bound the number of levels a read touches, and size bloom filters generously since they are cheap relative to the disk-read cost they avoid.
- TTL (time-to-live) and cost. Attach TTLs so cold, unused keys are compacted away instead of accumulating forever; this both bounds disk growth and improves compaction efficiency since there is less live data to carry through each compaction pass.
Worked example: With a 64GB memory ceiling per node and roughly 200 bytes per serialized feature record (a handful of numeric and short categorical features plus overhead), a single node's on-disk capacity at, say, 2TB of local NVMe holds on the order of 10 billion records; sharding 5-10 billion total keys across 4-8 such nodes is realistic. Reserving roughly 45GB of the 64GB for RocksDB's block cache and bloom filters, with the rest for the OS page cache and process overhead, is a reasonable starting split, then you tune based on measured hit rate.
Trade-offs & pitfalls: The most common mistake is under-sizing bloom filters to save memory, which causes every miss to hit disk and blows the latency budget; bloom filters are one of the cheapest levers for read latency at this scale and are usually worth the memory. A second pitfall is choosing tiered compaction for write-heavy workloads without realizing it trades read amplification for lower write amplification, which can silently worsen the read-latency SLA (service-level agreement) if the workload is actually read-heavy. Compression trades CPU for storage and I/O; on CPU-constrained nodes, Zstd at a lower compression level or Snappy may beat a higher Zstd level even though it uses more disk, because the CPU cost of decompression is on the read hot path.
Explain how you would implement and test idempotent writes from a stream-processing job into an external key-value online store that does not support transactions. Provide at least two robust design patterns and describe the test cases you would use to validate correctness under retries and duplicate delivery.
Sample Answer
Direct answer: Without native transaction support, idempotency has to be engineered into the write itself: either a deterministic upsert keyed by a stable identifier so retries produce the identical end state, or a versioned write with a monotonic check so an out-of-order or duplicate write cannot regress a newer value.
Structured elaboration:
- Pattern 1: Deterministic upsert keyed by a stable ID. Every write includes a stable key (the entity ID plus, if relevant, a window or event identifier) and the write operation is a
SET key = computed_valuerather than an increment or append. Because the computed value is a pure function of the input event(s), applying the same write twice (due to retry) produces the exact same end state; no accumulation error occurs. This works well when the feature value at a point in time is fully determined by the inputs, not by "add to whatever is currently there." - Pattern 2: Versioned write with a monotonic guard. Each write carries a version or timestamp, and the store only applies the write if the incoming version is newer than what is currently stored (a conditional/compare-and-set write, which most KV (key-value) stores support even without full transactions). This handles the case where writes might arrive out of order (not just duplicated), since a stale retried write with an old version is correctly rejected rather than overwriting a newer value that already landed.
- Test cases to validate correctness:
- Simple retry: apply the same write twice in a row; assert the store's final value matches what a single application would produce.
- Out-of-order retry: apply write version 5, then a retried (duplicate) write version 4; assert the store still shows the effect of version 5, not version 4 overwriting it.
- Concurrent writers: two processes attempt the conditional write for the same key with different versions at nearly the same time; assert only the higher version's write ultimately wins, regardless of which one physically executes last (this specifically exercises the compare-and-set logic under a race, not just sequential retries).
- Crash mid-write: simulate a crash after the write is sent but before the acknowledgment is received by the writer, then have the writer retry; assert the retried write is correctly either a no-op (if the first write actually succeeded) or successfully applies (if it did not), with no partial or corrupted state either way.
Worked example: For pattern 2 in a Redis-like store, the write is implemented as a Lua script (executed atomically by Redis) that reads the current stored version, compares it to the incoming version, and only performs the SET if the incoming version is greater; this gives compare-and-set semantics without needing a full multi-key transaction, since Redis executes the whole script atomically per key.
Trade-offs & pitfalls: Pattern 1 (deterministic upsert) does not work for features that are genuinely incremental in nature (a running count computed as current + delta rather than a full recomputation); forcing such a feature into a deterministic-upsert shape often means recomputing the full value from source data on every write, which can be significantly more expensive than a true increment. Pattern 2's monotonic guard requires every writer to correctly generate a version that reflects true ordering (a wall-clock timestamp is vulnerable to clock skew across producers; a logical/vector clock is more robust but adds complexity), and a bug that assigns a lower version to a genuinely newer write silently and permanently loses that write's effect with no error raised, since the store's compare-and-set logic is working exactly as designed.
Design a low-latency online feature retrieval API for model inference. Specify the API contract (request and response shape), authentication and authorization approach, caching strategy, timeout and retry semantics, and how you would include feature versioning and metadata in the response so a client can detect staleness.
Sample Answer
Direct answer: The API contract for online feature retrieval needs to specify entity IDs and requested feature names in, values and per-feature staleness metadata out, with authentication scoped per caller, a short client-side timeout with a defined retry policy, and response-embedded versioning so a caller can detect when it received a stale or mismatched feature definition.
Structured elaboration:
- Request/response contract. Request: entity ID(s) (support batch lookups since most inference paths need many features at once), a list of feature names or a named feature group/vector, and an optional as-of timestamp for offline/backtesting parity. Response: a map of feature name to value, plus per-feature metadata (last-computed timestamp, feature definition version) so the caller can decide whether a feature is too stale to use.
- Authentication and authorization. Service-to-service auth via short-lived tokens (mTLS or a token issued by a service-identity system) rather than static API keys; authorization scoped per feature group so a caller only sees features it is entitled to (relevant for PII (personally identifiable information)-sensitive features).
- Caching strategy. The API itself should be cache-friendly: deterministic request shape, and response headers or fields that state a TTL (time-to-live) so a client-side cache (or CDN-style edge cache for less dynamic features) knows how long it may reuse a value.
- Timeout and retry semantics. A tight client-side timeout (a few milliseconds under the overall inference budget) with at most one retry to a different replica, not a retry storm; on timeout, the client contract should specify a documented fallback (return a default/null feature with a flag, rather than blocking the whole inference request).
- Feature versioning and metadata in the response. Include the feature definition's version or hash in the response so a caller doing an online/offline consistency check can confirm the online value was produced by the same transformation logic as the training data.
Worked example: A request for {"entity_id": "u_123", "features": ["f_recency_7d", "f_avg_spend_30d"]} returns {"f_recency_7d": {"value": 3.2, "computed_at": "2026-07-23T10:15:02Z", "version": "v3"}, "f_avg_spend_30d": {"value": null, "computed_at": null, "version": "v3", "status": "missing"}}; the caller's contract with the platform says a missing feature is returned explicitly as null with a status field rather than the whole request failing, so a single missing feature does not take down inference for the entity.
Trade-offs & pitfalls: Returning rich per-feature metadata on every response adds payload size and marshaling cost at high QPS (queries per second); a common mitigation is to make metadata optional via a request flag, so hot-path inference can skip it and only debugging/monitoring calls request it. A retry policy that is too aggressive (multiple retries with no backoff) can turn a single slow shard into a cascading overload; the contract should specify a hard retry budget and prefer failing fast with a fallback over retrying into an already-struggling backend. Embedding a feature-definition version in every response is easy to forget to check on the consumer side, so the value it provides (catching a schema mismatch) only materializes if the platform also builds tooling that actively surfaces version mismatches rather than leaving it to each consumer to remember to compare.
Design an incremental feature generator (pseudocode is acceptable) that consumes a stream of events and maintains per-user online features: a running count, an approximate unique-item count, last-seen timestamp, and time-since-last-event. Explain how you would persist and checkpoint the running state between runs, how you would handle exactly-once versus at-least-once ingestion semantics, and how you would recover from a crash without double-counting.
Sample Answer
Direct answer: An incremental online feature generator maintains a small piece of running state per user (count, an approximate distinct-count sketch, last-seen timestamp) that updates with each new event, persists that state periodically so a crash does not lose it, and uses an idempotent update rule keyed by event ID so replayed events under at-least-once delivery do not double-count.
Structured elaboration:
- State design. Per user:
count(a plain integer),unique_count(a HyperLogLog or similar sketch for approximate distinct counting, since exact distinct counts do not update incrementally without unbounded memory),last_seen(a timestamp, simply overwritten by the newest event), andtime_since_last_event(derived at read time asnow - last_seen, not stored directly). - Update logic. For each incoming event: increment
count, add the relevant field to theunique_countsketch, and setlast_seento the event's timestamp if it is newer than the current value (to correctly handle slightly out-of-order arrival without regressinglast_seen). - Persistence and checkpointing. Periodically (e.g. every N events or every few seconds) snapshot the in-memory state to a durable store (a local state backend like RocksDB, checkpointed to object storage, which is exactly how Flink and Spark Structured Streaming manage state); on restart, load the last checkpoint and resume rather than starting from zero.
- Exactly-once vs. at-least-once handling. Under at-least-once delivery, the same event can be redelivered after a crash-and-restart even if it was already applied. To avoid double-counting, track the last-processed event ID (or offset) per user as part of the checkpointed state, and skip any incoming event whose ID/offset is not newer than what was already applied for that user, making the update idempotent with respect to redelivery.
- Crash recovery without double-counting. On restart, resume from the last checkpoint, resume consuming from the source at the last committed offset, and apply the idempotency check above so any events reprocessed between the checkpoint and the crash point are correctly skipped rather than re-applied.
class IncrementalUserFeatures:
def __init__(self):
self.count = 0
self.unique_ids = set() # stand-in for a HyperLogLog sketch in this simplified version
self.last_seen = None
self.last_processed_offset = -1
def apply_event(self, offset, event_id, timestamp, unique_field):
if offset <= self.last_processed_offset:
return # idempotent skip: already applied (redelivery)
self.count += 1
self.unique_ids.add(unique_field)
if self.last_seen is None or timestamp > self.last_seen:
self.last_seen = timestamp
self.last_processed_offset = offset
def snapshot(self):
return {
"count": self.count,
"unique_count": len(self.unique_ids),
"last_seen": self.last_seen,
"last_processed_offset": self.last_processed_offset,
}
Worked example (verified by execution): Applying events at offsets 0, 1, 2 updates count to 3; if the process crashes after offset 2 but before the next checkpoint, and the source redelivers offsets 1 and 2 on restart, the idempotency check (offset <= last_processed_offset) correctly skips both, leaving count at 3, not 5. Running this against a small scripted sequence (apply 0,1,2; simulate crash; reapply 1,2) confirms count == 3 and last_processed_offset == 2 after recovery, exactly as intended.
Trade-offs & pitfalls: Using a plain set() for unique counting is exact but unbounded in memory, which does not scale to millions of users with high-cardinality fields; a real implementation needs a probabilistic sketch (HyperLogLog) that trades a small, bounded error (typically under 2%) for constant memory per user. The offset-based idempotency check assumes offsets are strictly increasing per user's event stream and that the source guarantees at-least-once (not out-of-order arbitrary) delivery; if events can arrive wildly out of order (not just redelivered), a simple "skip if not newer" rule can incorrectly skip a legitimately new event that happens to have a lower offset due to multi-partition interleaving, which needs a per-partition or per-event-ID (not per-offset) deduplication key instead.
Explain watermarking and windowing in stream processing for feature computation. Define tumbling, sliding, and session windows and give a short example of each (for example: tumbling for hourly aggregates, sliding for rolling counts, session for bursts of user activity).
Sample Answer
Direct answer: Watermarking is a stream processor's mechanism for deciding when it is safe to say "no more events for this window will arrive," and windowing is how it groups events by time into aggregation buckets. A watermark is a heuristic timestamp (typically max-observed-event-time minus an allowed-lateness slack) below which the engine assumes all events have been seen.
Structured elaboration:
- Tumbling windows: fixed-size, non-overlapping windows (e.g. every 60 seconds). Example: computing hourly click counts per user, where each event belongs to exactly one hour bucket.
- Sliding windows: fixed-size windows that overlap, advancing by a slide interval smaller than the window length (e.g. a 10-minute window sliding every 1 minute). Example: a rolling "clicks in the last 10 minutes" feature that updates every minute rather than jumping discretely every 10 minutes.
- Session windows: dynamic-length windows defined by a gap of inactivity (e.g. close the session after 30 minutes with no events). Example: grouping a user's browsing activity into "sessions" for a feature like "number of pages viewed this session," where the window boundary is data-driven, not fixed.
- Watermarking's role: without a watermark, the engine would have to wait forever before emitting a window's result, since a late event could theoretically still arrive. The watermark trades a small amount of completeness (events later than the watermark are dropped or handled specially) for the ability to emit timely results.
Worked example: For an hourly tumbling window with a 5-minute allowed lateness, the watermark at wall-clock time 10:07 (assuming events have been arriving roughly on time) is approximately 10:02; the 9:00-10:00 window closes and emits once the watermark passes 10:00, which happens once the engine has seen an event timestamped 10:05 or later.
Trade-offs & pitfalls: A too-tight allowed-lateness closes windows quickly (good for freshness) but drops more genuinely late data, understating aggregates; a too-loose allowed-lateness keeps more state in memory for longer and delays results. Session windows are the trickiest of the three to reason about because the window boundary itself depends on the data, so a single very-delayed event can retroactively extend a session that had appeared to close, which downstream consumers need to be able to handle (either by accepting a late correction or by explicitly closing sessions eagerly and accepting the resulting inaccuracy for outlier cases).
Unlock Full Question Bank
Get access to all 39 ML Feature Pipelines and Feature Stores interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.