System Design · Concept Library · Free article
Stream Aggregation: Turning a Firehose of Events into Numbers
To count an endless stream of events, keep running totals per time window instead of storing every event, and use event time with watermarks to decide when a window is finished. That answers "clicks per link, last 24 hours" with no nightly batch job and no melted database.
A stream is an unbounded, never-ending sequence of events; stream aggregation is how you compute running answers over it — continuously, as the events arrive, instead of storing every event and querying later. You can’t "sum an infinite stream", so you chop it into windows (every minute, the last 5 minutes, a burst of activity) and keep a running total per window in memory — a small, stateful program that reads the log and emits one aggregated number per window instead of touching the database once per event. The hard parts are all about time and truth: events arrive late and out of order, so you bucket them by event-time (when they happened) and use a watermark to decide when a window is "done"; and a crash mid-count must not double-count, which is what exactly-once processing (checkpointing + replay) buys you. Do it well and 150 million raw events a day collapse into a handful of dashboard rows that are only seconds behind reality.
The clicks are flowing — now make them a dashboard
Hatch fixed the redirect: every click now emits an event onto a durable Kafka log instead of blocking on a database write. The redirect is fast again, and a firehose of click events — around 150 million a day at peak — is pouring into the log. Then Marketing shows up with the ask that started all this: "We want a dashboard. Clicks per link. Top links. The last 24 hours, updating live." You have all the raw events. How hard can turning them into numbers be?
Harder than it looks, and for two reasons that fight you at once. First, the obvious approach — have a worker read each event and write it to a Postgres table so you can GROUP BY link later — collapses under its own weight: 150 million individual inserts a day saturates the database’s disk, and the very write-amplification problem you just escaped on the redirect reappears downstream. Second, "the last 24 hours" is a moving target over an endless stream. There is no "all the data" to query — the events never stop coming, and the answer changes every second. You can’t run a query over infinity. You need a fundamentally different shape of computation: one that reads the stream as it flows and keeps the answers continuously, never storing the raw flood and never running a single giant query. That shape is stream aggregation.
Keep a running total, don’t store the flood
Here’s the core idea, and it’s one you already use every time you keep a tally instead of a list. If a thousand people walk through a door and you want to know how many came, you don’t write down a thousand names and count them at the end of the day — you hold a counter and click it once per person. Stream aggregation is that, at scale: a small program reads the click events off the log one by one and keeps a running total per link in memory, incrementing as it goes. It never stores the individual clicks. When it’s time to update the dashboard, it writes the total — one row per link — not the millions of events behind it.
Two properties make this its own discipline rather than "a loop with a counter." First, the program is stateful: the running totals are its state, held in memory and updated continuously, and that state has to survive the program restarting (more on that when we reach exactly-once). Second, it is unbounded and long-lived — it isn’t a job that starts, processes a fixed input, and finishes; it’s a process that runs forever, because the stream never ends. A batch job asks "what’s the answer for this pile of data?" A stream processor answers "what’s the answer right now?" and keeps answering, second after second, indefinitely.
You can’t sum infinity — so you cut it into windows
A running total per link is a start, but Marketing didn’t ask for "all clicks ever" — they asked for "clicks in the last 24 hours," "the trend per minute," "today’s top links." Every one of those is bounded in time. And that’s the fundamental move of stream processing: since you can’t aggregate an infinite stream as a whole, you slice it into finite chunks of time called windows, and aggregate each window on its own. The only real question is how you cut — and there are three shapes worth knowing, each answering a different kind of question.
- Tumbling windows — fixed-size, back-to-back, never overlapping: every minute is its own bucket, each event lands in exactly one. This is the workhorse — "clicks per minute," "hourly totals."
- Sliding (hopping) windows — a fixed size that slides forward in smaller steps, so windows overlap and each event can fall into several: "clicks in the last 5 minutes, recomputed every minute." Use it for smooth rolling metrics and moving averages.
- Session windows — no fixed size at all; a window grows to cover a burst of activity and closes after a gap of quiet. "Everything one visitor did before they went idle for 30 minutes." Use it to group activity by natural bouts rather than by the clock.
The difference is easiest to feel in motion. Press play below and watch click events stream in along the timeline: windows fill as events arrive and emit their total the moment they close — exactly what the aggregator is doing in real life. Switch the window type and watch the same stream get cut differently — tumbling drops each event into one tidy bucket, sliding lets them count in several overlapping ones, and session lets the windows form themselves around the bursts:
The interactive version of this example is available when JavaScript loads.
Which clock counts — when it happened, or when you saw it?
Every event actually has two timestamps, and confusing them is the deepest trap in stream processing. There’s event-time — when the thing really happened, stamped on the click at the moment the user tapped — and processing-time — when your aggregator happened to read it off the log. In a perfect world they’re a hair apart. In the real world they diverge wildly: a fan on the subway taps a link with no signal, and the click event sits on their phone until they surface ten minutes later, at which point it finally reaches you. It happened at 9:05. You saw it at 9:15.
Now the choice bites. If you bucket by processing-time — "whatever I saw in the 9:15 minute goes in the 9:15 window" — that subway click lands in the wrong window, and your "clicks per minute" chart is quietly wrong, with a spike at 9:15 that never really happened. The honest answer is almost always to bucket by event-time: put the click in the 9:05 window where it belongs. But event-time has its own hard problem, and it’s the whole reason this section exists: if events can always arrive late, how do you ever know a window is complete? You could wait forever for one more straggler. You need a rule for when to stop waiting.
Sit with the problem for a second, because it’s genuinely hard. Clicks for the 9:00 window can keep trickling in for minutes after 9:00 has passed — that subway phone is proof. If you wait for every straggler before you publish the number, you wait forever, because there’s always the chance of one more. But if you stop waiting too early, you publish a total that’s missing a few clicks. There is no perfect moment to close the window. So instead of chasing a perfect answer, you make a practical bet.
The bet is refreshingly simple: "in our system, a click almost never shows up more than, say, 30 seconds late." That one assumption is the whole strategy — it’s what finally gives you permission to stop waiting. Once 30 seconds of event-time have ticked past a given moment, you declare that moment finished and move on, accepting that the rare event later than 30 seconds will be missed. The tool that keeps track of this is called a watermark, and the easiest way to picture it is as a second clock that deliberately runs a little behind. It watches the newest event-time you’ve seen and subtracts your 30-second cushion. So if the latest click you’ve received happened at 9:01:00, your watermark reads 9:00:30 — its way of announcing, "I’m now confident I’ve got everything up to 9:00:30; anything from back then should have reached me by now."
That lagging clock is what actually fires a window. The instant the watermark slides past a window’s end — say it reaches 9:01:00, just past the end of the 9:00–9:01 window — the processor says "that one’s done," adds up its clicks, and publishes the total. Before that instant, the window is just a bucket quietly filling; after it, it’s a finished number on the dashboard. So hold onto this one line: the watermark is the thing that turns a filling bucket into a published number — nothing else gets to decide "done."
Now the part that makes it interesting: how big should that cushion be? It’s a dial, and both directions cost you something. Make it small — two seconds — and the watermark hugs the newest event, so windows close almost the moment they end and your dashboard is wonderfully fresh… but anyone more than two seconds late (hello again, subway phone) arrives after their window has already published, and gets dropped. Make it big — five minutes — and you now catch nearly every straggler, because you patiently wait five quiet minutes before closing each window… but every number on your dashboard is now five minutes stale. There’s the whole tension in a sentence: a fresher answer or a more complete one — you pick, with a single number. Most teams choose a smallish cushion that catches the common case and simply drop the rare very-late event.
This is far easier to feel than to read. Below, step a stream of out-of-order clicks through the aggregator — and, most importantly, drag the cushion up and down and watch it change everything: a tight cushion closes windows fast but throws late clicks away, while a generous one keeps them but makes every number wait. Watch the watermark advance, windows flip from open to emitted, and a late click get caught red-handed:
The interactive version of this example is available when JavaScript loads.
A click that shows up after its window’s watermark has passed is a late event, and you get to decide its fate. The cheapest option is to drop it — one missed click barely moves a total, and simplicity wins. If accuracy matters, you can configure allowed lateness: keep the window’s state around a little longer after it fires and update the already-emitted total when a straggler arrives. Or you can side-output late events to a separate stream and reconcile them elsewhere. The right choice is about how much a lost event costs you — nothing for a rough click count, plenty for billing.
The processor crashes mid-count — now what?
Remember that the aggregator’s running totals live in memory — that’s what makes it fast, and it’s also what makes a crash dangerous. Picture the processor part-way through the 9:00 window, having counted six MegaDrop clicks, when its machine dies. It restarts with an empty memory. The events themselves are safe — they’re still sitting in the Kafka log, which retains them — so the processor can re-read them. But here’s the knife-edge: if it re-reads and re-adds events it had already counted before the crash, it double-counts; if it skips them, it under-counts. For a metric whose entire job is to be a correct number, either one is a failure.
The fix is checkpointing. Every so often the processor takes an atomic snapshot of two things together: its aggregation state (the running totals) and its exact position in the log (the offsets it has consumed up to). That pair is saved durably. When it crashes, it doesn’t start from zero and it doesn’t guess — it restores the last checkpoint’s totals and rewinds the log to exactly the offset in that same checkpoint, then resumes. Because the saved state and the saved position always agree, every event is folded into the totals exactly once, no matter how many times the processor dies and recovers. Pair that with writing the output and the offset in one transaction and you have exactly-once processing end to end.
Contrast it with the cheaper guarantee. At-least-once processing also replays from the log after a crash — so it never loses an event — but if it had already updated the totals before the crash, the replay adds those events again: the count comes out too high. That’s fine for something where a small over-count is harmless, and fatal for a sum you’ll bill against. Crash the aggregator below and pick a recovery to see the difference between a double-counted total and a correct one:
The interactive version of this example is available when JavaScript loads.
Batch, streaming — and why mature systems run both
We opened by contrasting the two philosophies: batch (collect everything, run a big job, get an accurate but hours-old answer) and streaming (compute continuously, get a seconds-fresh answer that’s approximate at the tail because of late events). It’s tempting to treat them as rivals where streaming simply wins. In practice, the accuracy of batch and the freshness of streaming are both valuable, and two well-known architectures exist precisely to get both at once.
- Lambda architecture — run both layers side by side: a batch layer that periodically reprocesses the entire history into a slow-but-exact source of truth, and a speed (streaming) layer that covers just the recent slice the batch hasn’t caught up to yet. A query merges the two. You get exactness and freshness — but you pay a steep price: the same aggregation logic is written and maintained twice (once for batch, once for stream), and the two implementations inevitably drift apart.
- Kappa architecture — delete the batch layer entirely. Do everything as a stream, with one codebase. When you need to "reprocess history" (fix a bug, add a new metric), you don’t run a separate batch job — you simply replay the log from the beginning through the same streaming code. This only works if your log durably retains history… which, with Kafka, it does. One codebase, reprocessing is just replay — which is why Kappa is increasingly the default.
The through-line: *a durable, replayable log doesn’t just feed your stream — it lets the stream be your batch, too.* Reprocessing becomes "start a fresh consumer at offset zero." Compare the four shapes below and see where each one wins:
The interactive version of this example is available when JavaScript loads.
Aggregating first is what saves your database
Circle back to the first problem from the stake — the one that isn’t about time at all. Writing every one of 150 million raw click events straight to Postgres melts it, the same write-amplification that took down the redirect, now downstream. Windowed aggregation fixes it head-on. Instead of one database write per event, the processor writes one aggregated row per link per window: a hot link that took four thousand clicks this minute becomes a single row — "link mega-drop: 4,000 clicks, 09:14" — not four thousand inserts. The database stores summaries, not the flood, and its write load drops by three or four orders of magnitude.
Notice this is the same lesson as async event emission, one layer deeper. There, you got the slow write off the redirect — the user’s hot path. Here, you get the write volume off the database — the analytics hot path. Both are the same move: don’t hammer a shared resource with one operation per event; batch the work up and touch the resource far less often. Drag a hot link’s click rate and watch the write reduction:
The interactive version of this example is available when JavaScript loads.
The whole Chapter 7 pipeline, in one moving picture
You’ve now met every piece on its own — the redirect emitting a click event, Kafka holding the firehose, the windowed aggregator keeping running counts, and the single write per window that spares the database. Here they are wired together and running. Press play and watch click events for four links stream from the producer into the Kafka log, Flink pull them off and tick up a running count per link for the current window, and — the moment the window closes — one row per link land in the dashboard database. This is the entire analytics pipeline in a single frame:
The interactive version of this example is available when JavaScript loads.
Failure modes & gotchas
- State that outgrows memory. The running totals are state, and it can balloon — millions of distinct keys, or huge sliding windows kept in memory — until the processor runs out of RAM. Bound it: put a TTL on idle keys, keep window sizes sane, and use a spill-to-disk state backend (e.g. RocksDB) for large state.
- A hot key / skew. Aggregation is partitioned by key, so one wildly popular link routes all its events to a single processing task and overwhelms it while others idle — the same hot-partition problem, now on the compute side. It’s the Hot Keys & Partition Skew pattern.
- Watermark mis-tuned. Too tight and you silently drop legitimate late data; too loose and every number is stale. It’s a real dial, not a default to ignore.
- Reprocessing re-emits. Replaying the log (Kappa-style, or after a bug) re-runs every aggregation and re-writes every result — so the sink downstream must be idempotent, or reprocessing double-writes.
- Backpressure. A slow sink (the database can’t keep up with the aggregated writes) stalls the whole pipeline back to the source; the buffer only buys time (the backpressure story again).
Is the dashboard stale — and why?
When the dashboard looks behind, you need to know which kind of behind, because the fixes are opposite. Two different lags tell the two stories apart:
- Processing lag (a.k.a. consumer lag) — how far the processor trails the live end of the log. Climbing processing lag means the pipeline can’t keep up with the event rate: the same consumer lag signal from Kafka, and the fix is to scale the processor (more parallelism / partitions) or lighten the per-event work.
- Watermark lag — how far the watermark trails real time. High watermark lag with low processing lag means the pipeline is keeping up fine, but your watermark is conservative (a big cushion) or events genuinely arrive late — the staleness is by design, not a bottleneck.
- State size — memory held by the running aggregates; a steady climb warns of unbounded state before it OOMs.
- Late-event / dropped rate — how many events arrive after their window closed; a rising rate says your watermark cushion is too tight for reality.
- Checkpoint duration & failures — long or failing checkpoints mean slow recovery and risk to your exactly-once guarantee.
The engines that do this
Everything on this page — windows, event-time, watermarks, exactly-once — is a concept, true of every serious stream processor, which is exactly why we didn’t tie it to one tool. The main ones you’ll hear named:
- Apache Flink — the gold standard for stateful, event-time stream processing: true windows, watermarks, exactly-once, and very large managed state. When someone says "real streaming," they usually mean something Flink-shaped. (It’s the term Chapter 7 uses.)
- Spark Structured Streaming — streaming as micro-batches (tiny batches every second or so) behind a streaming API. Slightly higher latency than true streaming, but a natural fit if you already live in the Spark ecosystem.
- Kafka Streams — a library, not a cluster: it runs inside your own application and reads/writes Kafka topics. The simplest option when you’re already all-in on Kafka and don’t want a separate processing system to operate.
- ksqlDB / Flink SQL — write the aggregation as SQL over streams (
SELECT count(*) … GROUP BY link, TUMBLE(…)), no application code. Apache Beam goes the other way: one API you can run on Flink, Spark, or Google Dataflow.
The whole pipeline is surprisingly little code
What’s striking the first time you see a stream job is how small it is — the engine handles the windows, watermarks, state, and exactly-once; you just declare the shape of the aggregation. In Kafka Streams / Flink-flavoured pseudocode, the entire Hatch clicks pipeline is about this:
- Read the stream.
clicks = stream("clicks")— consume the click-event topic. - Bucket by event-time with a watermark.
.withTimestamps(e => e.eventTime).withWatermark(lateness = 30s)— tell the engine which field is event-time and how late events can be. - Key by what you’re counting.
.groupByKey(e => e.linkId)— all of a link’s events aggregate together (this is also the partition, so mind hot keys). - Window it.
.window(Tumbling(1 minute))— the shape from §3; swap forSlidingorSessionas needed. - Aggregate.
.count()(or.aggregate(sum, avg, …)) — the running total the engine maintains as state. - Write the result, not the raw events.
.to("link-counts")— one row per link per window into your serving store. Make this sink idempotent so a replay doesn’t double-write.
Pitfalls
- Aggregating on processing-time when you meant event-time. The subtle one: charts look fine until delayed events pile spikes into the wrong minute. Use event-time for anything that must be correct by when it happened.
- Unbounded state. No TTL on keys, or ever-growing windows, and the processor OOMs. Bound the state; use a disk-backed state backend for big state.
- Assuming exactly-once for free. It’s a deliberate choice (checkpointing + a transactional/idempotent sink) with a latency cost — not a default. Decide when the count must be exact.
- Silently dropping late events. A watermark that’s too tight throws away real data with no error. Measure the late-event rate; widen the cushion or side-output if it matters.
- Sliding windows exploding cost. Overlapping windows multiply the work and the output volume; use them only when you actually need a smooth rolling metric.
- A non-idempotent sink. Reprocessing (Kappa replay, or crash recovery) re-emits results — if the sink can’t absorb a repeat, you double-write. Upsert by key.
Best practices
- Aggregate on event-time with a watermark sized to real lateness — measure how late events actually are, and set the cushion there.
- Keep state bounded — TTL idle keys, sane window sizes, a disk-backed state backend for large state.
- Choose the delivery guarantee deliberately — exactly-once (checkpointing) for counts that must be exact; at-least-once + an idempotent sink when a tiny error is fine.
- Write aggregates, not raw events, to your serving store — one row per key per window; it’s the whole reason the database survives.
- Monitor the two lags plus state size and late-event rate — so you can tell "the pipeline is behind" from "the watermark is conservative."
- Make reprocessing safe — idempotent, upserting sinks so replaying the log (Kappa-style) is painless.
- Pick the engine by your ecosystem — Kafka Streams if you’re all-in on Kafka, Flink for heavy stateful/event-time work, Spark if you already run Spark; and prefer managed.
Rapid-fire cheat-sheet (intern → principal)
- "What is stream aggregation?"
- Computing running answers over an unbounded stream of events continuously, as they arrive, instead of storing every event and querying later. You chop the stream into windows and keep a running aggregate per window in memory.
- "What are the window types?"
- Tumbling (fixed, non-overlapping — per-minute totals), sliding/hopping (fixed size that overlaps — a rolling "last 5 minutes"), and session (variable, grouped by a gap of inactivity — a user’s burst). Match each to the question asked.
- "Event-time vs processing-time, and what’s a watermark?"
- Event-time = when it happened; processing-time = when you saw it. Aggregate on event-time so delayed events land in the right window. A watermark is the estimate "I’ve seen everything up to time T" that decides when to close and emit a window — a latency-vs-completeness trade set by an assumed max lateness.
- "How do you avoid double-counting when the processor crashes?" (senior)
- Checkpointing: atomically snapshot the aggregation state and the consumed offsets together, so on recovery you restore both and replay from a consistent point — every event counted exactly once. At-least-once, by contrast, replays onto already-updated totals and over-counts.
- "Batch vs stream — Lambda and Kappa?" (staff)
- Batch is exact but stale; streaming is fresh but approximate at the tail. Lambda runs both layers and merges (accuracy + freshness, but two codebases that drift). Kappa is stream-only and reprocesses by replaying the durable log through the same code — one codebase, increasingly the default.
- "How does this keep the database alive, and how do you scale it?"
- It writes one aggregated row per key per window instead of one per event — orders-of-magnitude fewer writes. You scale by partitioning on the aggregation key (mind hot keys), adding processor parallelism, and bounding state; watch processing lag vs watermark lag to know which knob to turn.
The takeaway
By GOAT Engineer. Back to Concept Library. Privacy Policy · Contact.