← Building blocks

Compute over events as they arrive

Real-time & streamingsenior

Counts, windows and joins over a never-ending stream, with results in seconds.

Say it like this

Counts have to be fresh within seconds, so I run a stream processor over the event log with tumbling windows and checkpointed state, and write the aggregates to a store the API reads.

Basic solution

Run a stream processor on the event log with windowed aggregations and checkpointed state.

Kafka StreamsFlinkSpark Structured StreamingksqlDB

Event-time windows over a partitioned log

The job runs one task per partition, and each task keeps windowed counters in local state. The watermark closes windows; final counts are upserted into the analytics store and late events go to a side output.

How it works

  1. Producers append events (a click, a view, a location update) to a partitioned log such as Kafka. The partition key is chosen so related events land on the same partition, for example all clicks for one alias, which keeps them in order and on one task.
  2. The stream job runs one task per partition. Each task reads its partition in order and keeps per-key state (such as a counter per alias) in a local store on its own disk, usually RocksDB. Every change to that state is also written to a changelog topic so the state can be rebuilt if the task moves to another machine.
  3. Each event is placed into a window by its event time, the timestamp inside the event showing when it happened, not by when the job received it. A tumbling window of one minute means events timestamped 12:00:00 to 12:00:59 are counted together, and the next window starts at 12:01:00 with a fresh count.
  4. The job tracks a watermark, its estimate of how far event time has advanced, computed as the newest timestamp seen minus an allowed lateness. When the watermark passes the end of a window, the job treats the window as complete: it emits the count and releases the state for that window.
  5. Emitted results go to a sink the API can read: an OLAP table, a Redis counter, or another topic. The job periodically checkpoints its consumer offsets and its state together, so after a crash it resumes from the checkpoint and recomputes only what came after it.
  6. To scale, add partitions and tasks: each task owns a slice of the keys and never needs to see another task's state.

Event time versus processing time

  • A phone that was offline sends its events an hour late. Processing time would count them in the minute they arrived, which is the wrong minute; event time puts them in the minute they happened, at the cost of waiting for stragglers before closing a window.

Worked example

Per-minute click counts for the URL shortener

  • 4,000 redirects per second average, 40K at peak, each publishing one click event of about 200 bytes to a topic partitioned by alias.
  • Throughput: 40K events per second at peak is 8 MB per second; 12 partitions handle it with headroom, one task per partition.
  • Window state: 100M aliases exist but only about 2M see traffic in any minute; one counter per active alias per open window, so 2M x 2 windows (current plus one minute of lateness) x 50 bytes = 200 MB of state across the 12 tasks.
  • Output: one row per active alias per minute, 2M rows per minute, 33K upserts per second into ClickHouse, which it absorbs as batched inserts.
  • Lateness budget: allow 2 minutes. A window for 12:00 is emitted at 12:03 event time; anything later goes to a late-events topic and is added by a nightly batch correction.
  • Compare with batch: a daily job would give counts 24 hours stale; a request-time COUNT over raw clicks would scan millions of rows per popular alias.

Variants and when each wins

Stream processor with state (Flink, Kafka Streams)

  • A framework that keeps per-key state, assigns events to event-time windows, and checkpoints state with offsets so counts are exactly-once. It wins as soon as you need windows, joins between streams, or state that must survive a restart.

Micro-batch (Spark Structured Streaming)

  • The engine collects events for a few seconds and processes them as a small batch. It wins when the team already runs Spark and latency of seconds is fine; it loses on per-event latency and on fine-grained state.

Consumer with Redis counters

  • A plain consumer reads each event and runs INCR on a Redis key named for the alias and minute. It wins for simple totals because there is nothing to operate beyond Redis; it has no notion of event time or lateness, so late events land in the wrong minute or are ignored.

Lambda architecture

  • A stream job produces fresh approximate numbers, and a nightly batch job recomputes exact numbers from the raw archive and overwrites them. It wins when the product needs both seconds of freshness and eventual exactness, at the cost of maintaining two code paths.

Recommendation: a consumer with Redis counters for simple totals; a real stream processor once you need event-time windows, joins or exactly-once state; add the batch correction when exactness matters.

Failure modes

Late events counted in the wrong window or dropped

  • Yesterday's totals keep changing, or events from users who were offline never appear at all. It happens because windows were closed based on arrival time, or because the job allowed no lateness and discarded anything that arrived after its window closed. Use event-time windows with a watermark, set an explicit lateness allowance, and send events that still arrive too late to a side output that a batch job reconciles.

State grows without bound

  • Each task's memory and disk climb steadily until the job dies. It happens because the job keeps state per key, such as a counter per alias, and never discards it; windows that closed long ago are still held. Put a TTL on state and a retention limit on windows, and discard a window's state as soon as its result has been emitted.

Rebalance storms

  • A deploy or a single task failure stalls output for minutes. It happens because every partition is reassigned at once and each task must rebuild its state by replaying the changelog from the beginning. Keep standby replicas of state on other machines, enable incremental rebalancing so only the affected partitions move, and prefer fewer, larger tasks.

Duplicate output on restart

  • Counts jump upward after a crash. It happens because the job wrote results to the sink and then crashed before the checkpoint that recorded those results as done, so after restart it recomputed and wrote them again. Write through a transactional sink that commits with the checkpoint, or make the sink an idempotent upsert keyed by (alias, window) so a replay overwrites the same row instead of adding to it.

A hot partition

  • One task lags by minutes while the others sit idle. It happens because a viral alias sends every one of its events to one partition, and one task cannot keep up. Pre-aggregate in the producer so fewer events are sent, or append a random suffix to the hot key so its events spread across partitions and merge the partial counts downstream.

Interviewer follow-ups

Answer out loud before you open each one.

What is a watermark and why does it matter?

A watermark is the job declaring that no events older than time T are expected any more. Windows close when the watermark passes their end, so it decides the trade-off between latency and completeness: a watermark that trails by two minutes gives complete counts two minutes late, one that trails by zero gives instant but wrong counts.

How do you get exactly-once counts?

Checkpoint input offsets and operator state atomically, and write output either through a transactional sink that commits with the checkpoint or as idempotent upserts keyed by window and alias. Then a replay after a crash reproduces the same results instead of adding to them.

When is a stream processor overkill?

When you only need simple totals and can tolerate ignoring late events: a consumer doing INCR on Redis or a batched insert into ClickHouse is a tenth of the operational weight. Reach for windows and watermarks when event time, joins or stateful logic actually matter.

How would you join clicks with link metadata in the stream?

Load the metadata as a changelog-backed table keyed by alias (a KTable or a broadcast state) and do a stream-table join, so each click is enriched locally without a database call. Metadata updates flow through the same log, so the join stays current.

Connections

Built on
HyperLogLog · Count-Min sketch
Pairs with
Keep events as a replayable log · Process large data offline · Count big things with small memory · Drop duplicate events · Analytics without hurting production
Pulls against
Do read-modify-write atomically
Used in
URL Shortener (TinyURL / bit.ly) · Video Streaming Platform (YouTube / Netflix)

The same parts on other clouds

The diagrams above name AWS services as one concrete example. Every part has a close equivalent elsewhere. In an interview, name the role first, such as “a managed Redis cache”, then the product you would pick.

AWSUsed here asGoogle CloudMicrosoft AzureOpen source and others
Amazon EC2 Auto ScalingRedirect serviceCompute Engine managed instance groupsVirtual Machine Scale SetsKubernetes Deployment with a HorizontalPodAutoscaler, Nomad
Amazon MSK (Kafka)clicks topicManaged Service for Apache KafkaEvent Hubs (Kafka API)Confluent Cloud, Redpanda
Amazon Managed Service for Apache FlinkStream taskDataflow (Apache Beam)Stream AnalyticsApache Flink, Kafka Streams, Spark Structured Streaming
Amazon RedshiftAnalytics storeBigQuerySynapse Analytics, Microsoft FabricClickHouse, Snowflake, Apache Druid