🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Real-Time Feature Computation

AI System DesignFeature ComputationđŸŸĸ Free Lesson

Real-Time Feature Computation

What You'll Learn

  • 1Choose tumbling, sliding, session or global windows for a given feature definition
  • 2Size stream state and parallelism from event rate, key cardinality and window length
  • 3Meet a feature freshness SLA with a tiered L1, L2 and store cache design
  • 4Handle watermarks and late events without corrupting aggregates

Why This Matters

In production ML systems, models need features computed in real-time - click-streams, user interactions, sensor data. Batch-only pipelines cannot support sub-100ms latency requirements. Real-time feature computation bridges stream processing with ML serving, enabling fresh, low-latency features for online predictions.


Architecture Overview

Real-Time Feature Computation ArchitectureEvent SourcesClick StreamUser EventsIoT SensorsTransactionsAPI CallsLogsMobile EventsApache Kafka / Kinesis / Pub/SubStream Processing EngineWindowed AggregationsTumbling: Fixed intervalsSliding: Overlapping windowsSession: Activity-basedGlobal: All-time accumulationsCount, Sum, Avg, PercentileStateful OperationsRunning aggregationsDeduplicationWatermark handlingLate event processingState snapshotsFeature ComputationsUser-level aggregationsItem-level statisticsCross-entity featuresTime-decay featuresAnomaly scoresProcessing EnginesApache Flink (low latency)Apache Spark Structured StreamingApache Kafka StreamsApache Beam (portable)Cloud Dataflow / ksqlDBFeature Serving LayerOnline Feature StoreRedis / DynamoDB CacheFeature Vector DBMaterialized ViewsEdge CacheML Model Serving (Real-Time Inference)Latency: <50ms p99 | Throughput: 10K+ QPSMonitoring & AlertingFeature Drift | Latency | Throughput | Error Rate | Freshness

Windowed Aggregations

Window Types and Processing

Real-time feature computation relies on windowed aggregations over event streams. The key window types are:

  • Tumbling windows: Fixed-size, non-overlapping time intervals (e.g., every 5 minutes). Each event belongs to exactly one window.
  • Sliding windows: Fixed-size windows that slide by a smaller interval, creating overlapping windows. An event can belong to multiple windows simultaneously.
  • Session windows: Dynamically sized windows based on activity gaps. Windows close when no events arrive within a configured timeout (e.g., 30 minutes of inactivity).
  • Global windows: Unbounded windows that accumulate all events for a key, useful for lifetime statistics.

Each window maintains state (values, count, sum, min, max, timestamps) and supports aggregation functions (count, mean, variance, percentiles). Watermarks track event-time progress to handle late-arriving data - events arriving within an allowed lateness window update window state, while those arriving later are dropped.

Streaming Feature Engine

A streaming feature engine registers features with their window configurations and aggregation functions. For example:

  • User click count: Sliding window of 1 hour with 5-minute slide interval, computing count and clicks-per-minute.
  • User purchase sum: Tumbling window of 24 hours, computing total, average, and maximum purchase amounts.

The engine processes events by key (e.g., user_id), updates the appropriate window state, and returns computed features on demand.


Online Feature Store

An online feature store provides low-latency feature retrieval for real-time inference. Key capabilities include:

  • Key-based retrieval: Features are stored as JSON blobs keyed by entity ID, feature group, and version (e.g., features:user_profile:v1:user_123).
  • TTL management: Features expire after a configurable time-to-live to prevent serving stale data.
  • Batch retrieval: Pipeline-based batch gets for multiple entities reduce round-trips (Redis pipeline pattern).
  • Versioning: Feature versions allow A/B testing and rollback of feature logic changes.

Latency Optimization

Low-latency feature serving requires a tiered caching strategy:

  • L1 cache: In-memory per-server cache with 1-5 second TTL for the hottest features.
  • L2 cache: Distributed cache (Redis cluster) with 30-60 second TTL.
  • L3 store: Feature store with minute-level freshness.

The optimizer checks the local cache first, falls back to the distributed cache, and finally queries the feature store. Batch retrieval patterns minimize network round-trips by grouping uncached entity IDs and fetching them in a single pipeline operation.


Sizing the Stream Pipeline

Every streaming feature system is bounded by three quantities: state size, partition parallelism and feature age. State size follows from key cardinality times retained windows times bytes per window:

Take 2,000,000 active users, a 1 hour sliding window with a 5 minute slide so 12 windows are retained, and 200 bytes of accumulated state per window: GB of keyed state. Spread over 8 partitions that is 600 MB per TaskManager, which fits an 8 GB slot with room for timers and watermark bookkeeping.

Parallelism follows the ingest rate:

A peak of 200,000 events per second against a budget of 50,000 events per second per slot needs 4 partitions, and running 8 means a single TaskManager restart does not halve throughput.

Freshness is an age budget rather than a request latency budget:

With 5 ms of Kafka ingest, a 200 ms micro-batch, 10 ms to write the online store and a 2,000 ms L1 TTL, the p99 feature age is about 2.2 seconds. If the serving SLA demands features no older than 500 ms, cut the L1 TTL to 250 ms and read through to the store on a miss, paying 3 to 5 ms of extra lookup.

Failure Modes

Late events beyond the allowed lateness are dropped or sent to a side output, so a watermark of 30 seconds tolerates normal mobile sync delay while bounding timer state. State bloat happens when keys are never expired: put a TTL on every keyed window and close session windows on a configured inactivity gap. Backpressure appears when the sink is slower than the source, so watch consumer lag and add partitions before the queue drains and end-to-end age breaches the SLA.

Common Mistakes

Setting a watermark of zero so no event is ever dropped

Fix: Bound timer state with a 10 to 60 second watermark and route later events to a side output you can replay.

Reading features one key at a time from the online store

Fix: Batch uncached keys into one pipeline get so a 20-key request costs one round trip instead of 20.

Tuning throughput while ignoring feature age

Fix: Track p99 feature age as the SLA, because a fast pipeline writing stale windows still fails the model.

Best Practices

  • Version each feature with its window definition so a window change is a new feature version
  • Persist operator state to a checkpoint backend so a restart replays rather than resets
  • Alert on consumer lag, watermark skew and state size alongside the usual latency metrics

Key Takeaways

  • State costs M = K x W x s: 2M users x 12 windows x 200 bytes is 4.8 GB of keyed state
  • Size parallelism at P = ceil(event rate / slot rate); 200,000 events per second at 50,000 per slot is 4 partitions
  • Freshness is additive: ingest plus processing plus write plus cache TTL, so a 2 second TTL dominates a 215 ms pipeline
  • A tiered L1, L2 and store read path keeps p99 feature serving under 50 ms while the stream stays near real time

Frequently Asked Questions

How do I choose between a tumbling and a sliding window?

A tumbling window is right when each event should be counted once, such as a 24 hour purchase total, and it keeps state at one window per key. A sliding window is right for a rolling rate such as clicks in the last hour with a 5 minute slide, but it multiplies state by the number of overlapping windows, which is 12 in that example. If the windows are only used occasionally, compute the sliding value on read from a tumbling base to cut state by an order of magnitude.

What freshness can I actually promise to the model?

Add up the path: ingest, processing, online write and cache TTL. A stream with a 200 ms micro-batch and a 2 second L1 TTL promises roughly 2.2 seconds at p99, not the 200 ms the streaming vendor quotes. For fraud scoring you usually need under 500 ms, which means a continuous mode engine such as Flink with a 250 ms cache TTL and a direct store read on miss.

Does a streaming feature always beat a batch feature?

No. Streaming is worth the cost only when the feature changes fast enough that a batch value would be wrong at prediction time, such as a session counter or a velocity check. Daily aggregates, profile attributes and graph features are cheaper and more reproducible in batch. A healthy platform runs both and marks each feature with the SLA it is held to.

Interview Questions

Q1: How do you handle late-arriving events in stream processing?

Use event time with watermarks. Set allowed lateness to the observed sync delay, for example 30 seconds, so in-window updates are applied and anything later goes to a side output for replay. Flink exposes this as allowedLateness plus a side output, and the late path is monitored so drops never happen silently.

Q2: How do you ensure feature freshness while maintaining low latency?

Use three tiers: a 1 to 5 second in-process L1, a 30 to 60 second Redis L2, and the feature store behind it. Measure p99 feature age, not read latency, and alert when age exceeds the SLA. At 10,000 QPS with 3 reads each a single Redis node at 100,000 ops per second covers the load, so the tiering is for freshness control rather than raw throughput.

Q3: Compare Flink and Spark Structured Streaming for feature computation.

Flink gives event-time processing with millisecond latency and native exactly-once state, so it fits a sub-100 ms serving path. Spark Structured Streaming runs micro-batches of 100 ms or more and is easier if the team already lives in Spark SQL. Choose Flink when feature age is the SLA, Spark when SQL ergonomics matter more than the last 100 ms.

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-07

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert AI System Design Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement