How it works
Start with a continuous event source: clicks, metric samples, price changes, or location updates. Producers usually write to a durable, partitioned log. Processors read from the log independently. For example, a click event can contain an event ID, ad ID, event timestamp, and ingestion timestamp.
Partition events by the key whose state must change together. To count clicks per ad, usually group events by ad ID so one logical owner updates each ad's count. Order generally applies only within a partition. This does not guarantee timestamp order when producers send events late or in a different order.
Apply transformations such as filters, enrichment, aggregation, or joins. Stateless filters can process each event independently. A five-minute click count needs state indexed by ad and time window. Stream joins also need rules that limit how long they keep unmatched events. Without these rules, their state can grow without limits.
Choose event time, when the event occurred, or processing time, when a worker processed it, for calculations. For event-time windows, a watermark estimates event time progress. It does not prove that all earlier events arrived. Define whether late events update earlier results, follow a correction path, or have no effect under an explicit policy.
Recover state and source progress together. A processor can checkpoint its aggregation state and consumed offsets, then restore them and replay events after a crash. Replayed output can still duplicate external writes. Use idempotent upserts, deduplication, or a compatible transactional sink. Do not assume checkpoints make every side effect occur exactly once.
Send results to a database for queries, another stream, or an alert service. Track consumer lag, event-to-result latency, state size, and sink failures. If processors cannot maintain the input rate, backpressure limits work in progress while the log holds a limited backlog. Processors need spare capacity and enough retention to clear the backlog.
A worked example
Live click counts with late-event corrections
Suppose an ad analytics service receives 60,000 click events per second. It needs counts by ad for one-minute event-time windows, visible within five seconds. Write events to a durable log. Partition the work by ad ID. Processors deduplicate click IDs within a defined retention period and update window state. They upsert provisional counts with (ad_id, window_start) as the output key. Send revisions every five seconds. Retain windows until the watermark passes their end by two minutes. Later events go to reconciliation; the system does not silently discard them. Checkpoint state with source offsets. Add versions to output updates so replay cannot overwrite newer counts. The billing system uses reconciled totals, not the provisional dashboard.
Trade-offs to say out loud
- Freshness versus efficiency
- Immediate work on each event reduces delay. Small batches can improve throughput but reduce freshness.
- Timely results versus complete results
- Early window results give fast answers. Late events require revisions or a clear difference between provisional and final results.
- Stateful computation versus operational cost
- Windows, deduplication, and joins need limits on retained state and durable recovery. They also need care when workers or partition owners change.
- Parallelism versus per-key coordination
- More partitions distribute independent keys across workers. A hot key may need partial aggregation and a second merge stage, if the computation permits this.
- Stronger guarantees versus coordination
- Atomic commits of state, offsets, and output reduce duplicate effects within supported limits. They add coordination and do not automatically cover external APIs.
- Replay support versus retention cost
- Source event retention permits recovery and repeat calculations but uses storage. It also requires a plan to prevent replayed outputs from corrupting live results.
When to reach for it
- The problem requires continuous aggregate updates, such as clicks per minute, popular items, or metric rollups.
- Alerts or decisions must react to new events within seconds, not wait for a scheduled batch.
- You need to join or relate events over time, such as page views with sessions or outcomes with exposures.
- High-volume updates must produce derived state that supports queries without repeated scans of raw data.
- Late events, duplicate delivery, and replay are central requirements for correct results, not rare exceptions.
How to use it in the interview
- Start with the output contract: the result to maintain, its permitted age, and whether published values can change. Interviewers will ask what 'real time' and 'correct' mean.
- Draw the source log, partition key, stateful operators, and output sink for queries. Explain which operations need repartitioning and where one popular key could limit throughput.
- State the time model explicitly: event time or processing time, window type, watermark behavior, and late-event policy. Expect questions about idle partitions, incorrect timestamps, and events that arrive after window cleanup.
- Describe a crash between a state update and an output write. Explain how checkpoints, replay, and sink idempotency work together. Include the limits of any exactly-once claim.
- Estimate input rate, work per event, retained state, and capacity to clear a backlog. Discuss lag, backpressure, and what happens when an outage lasts longer than source retention.
Common mistakes
- The design treats any asynchronous queue worker as a complete stream processing design. It does not explain continuous computation, state, or time rules.
- The design uses processing-time windows for business events. It assumes late or replayed events will enter their original windows.
- The design claims a watermark proves completeness. Or, it keeps window and deduplication state forever to avoid a late-data policy.
- The design claims exactly-once behavior because the broker or processor offers it. It does not check the output database or external side effect.
- The design assumes more workers solve every throughput problem. It ignores hot keys, state transfers, and a slow output sink.
Where it is used
In these interview questions, a strong answer uses stream processing. Each line tells you why.
- Design an ad click aggregatorThe core pipeline maintains windowed click counts that remain correct under replay. It also handles late events, hot ads, and billing reconciliation.
- Design a metrics monitoring system like DatadogContinuous ingestion, rollups, and alert evaluation depend on stateful processing. The design must explicitly handle late samples and backlog.
- Design a top K trending systemA system that maintains ranks as they change needs continuous aggregation, window expiration, and correct distributed updates under replay.
- Design Google AnalyticsSessionization, funnel calculations, and distinct-user metrics require processors to handle event streams with duplicates and late events.
- Design Uber surge pricingCurrent regional estimates of demand and supply require continuous aggregation. The system must handle event time and control when it publishes price updates.
- Design a price alert systemThe system must compare new price events with registered thresholds. It needs the correct event order and durable triggers that remain correct under replay.
- Design Facebook likes at scaleHigh-volume like and unlike changes need incremental aggregation that remains correct under replay before the system publishes current totals.
- Design an ETA and live location sharing serviceThe system must filter, order, and combine continuous location updates with route information to maintain reliable trip progress and ETAs.
Common questions
What is the difference between stream processing and batch processing?
Batch processing uses a bounded dataset, such as yesterday's events, and completes a run. Stream processing updates results as continuous input arrives. This input may have no bound. A stream processor may use small internal batches. The main difference is continuous computation and incremental results, not necessarily execution for one event at a time.
Is Kafka a stream processing system?
Kafka's brokers mainly provide a durable, partitioned event log. They store and deliver events, but these actions differ from computation of windowed results. Kafka Streams is a processing library. Engines such as Apache Flink can also consume Kafka topics to maintain state and compute results. In an interview, distinguish the transport layer from the processing layer.
How does stream processing handle duplicate and late events?
A system can handle duplicates with stable event IDs and bounded deduplication state. It can also use operations that have the same effect with each repetition. Late events require event-time windows and an explicit policy to revise or reconcile earlier outputs. Checkpointing supports recovery. But correct output still requires coordinated writes or writes that remain safe when the system repeats them.