ealeng

Episode 32 of 55 · Stream processing

Watermarks and checkpoints: a processor that read every message lost 97% of its clicks, and checkpoints lost none

A stream processor that counted ad clicks per minute got only 12.5% of its counts right when it counted by arrival time. Killed 20 times without checkpoints, it counted 8,456 of 300,594 clicks while reading every message. How a watermark decides when a minute is final, why waiting 60 s instead of 10 s dropped only 16% fewer late clicks, what corrections cost, and why saving the counts together with the read position gave 1,000 of 1,000 exact counts through the same 20 kills.

Lab 14 · Stream Processing11 min read
Video transcript9:07

0:00Cold open

0:01

I counted ad clicks per minute, from a stream of three hundred thousand clicks.

0:07

Counting each click in the minute it arrived, the results were ready in under a second. And only twelve and a half percent of the counts were right.

0:17

Then I killed the counting process twenty times. Without saving its work, it counted eight and a half thousand clicks, out of three hundred thousand. While reading every single message.

0:30

Saving its work every two real seconds, every count came out exactly right.

0:37

So how does a stream get the same answer a batch job would, with late clicks and crashes?

0:44Intro

0:46

Hands-on system design, part thirty-two.

0:49

Today: counting a stream by when things happened, waiting for late events, and surviving a crash.

0:56Meet Lucía

0:58

I’m Lucía, a platform engineer.

1:01

The stream is generated: three hundred thousand five hundred ninety-four clicks on a hundred ads, over ten minutes. A replay script sends it into Kafka, a message log, ten times faster than real life. So the times you’ll hear are the stream’s own clock, unless I say real seconds.

1:20

Three thousand one hundred seventy clicks arrive twice; the processor remembers each click’s id, so they count once. And a batch job, which sees the whole finished dataset, gives the right answer: a thousand counts, a hundred ads times ten minutes.

1:37

Think of counting letters by week. The postmark says when a letter was sent: that’s event time. The day it reaches you is processing time. And some letters sit in a drawer for a while: those are late clicks.

1:5201 · What you need

1:53

To run it yourself: Docker for Kafka, Postgres and the processors. The quick tests run in a couple of seconds, without Docker.

2:03

No cloud, and nothing to pay for.

2:0702 · How late?

2:09

First, how late do the clicks arrive? That’s the time from the click until it reaches Kafka.

2:16

Ninety-seven percent arrive within five seconds. But nine thousand and thirty-six, three percent, arrive one to ten minutes late: a phone that was offline.

2:28

The generator makes them that way, so there’s almost nothing in between: fifteen clicks between five seconds and a minute. Remember that gap.

2:3803 · By arrival

2:40

The simplest way: count each click in the minute it arrives. That’s counting by processing time, the day the letter reached you.

2:49

Only twelve and a half percent of the thousand counts were exactly right, though on average a count was off by about seven clicks. Every late click, and every click that crossed a minute’s end on its way, was counted in the minute it arrived: missing from its own minute, and extra in a later one. And the clicks that arrived after the tenth minute weren’t in these ten minutes at all.

3:12

It was fast: each minute’s result, typically, under a second after the minute ended. And a rerun could give different numbers, because the processor’s own clock decides the minute.

3:2504 · A watermark

3:27

The better way: count each click in the minute it happened, its postmark. But a stream never sees the end. So when is a minute finished?

3:36

The answer is a watermark. Kafka splits the stream into six partitions: lanes, each read in order. For each lane, take the newest click time seen so far, minus an allowed delay.

3:50

For the whole stream, take the lane that’s furthest behind. It means: I’ve probably seen everything before this time. In the letters picture: I’ve probably got everything postmarked before Tuesday.

4:04

When the watermark passes the end of a minute, that minute’s counts are written out.

4:10

A click that arrives for a minute already written out is late. You can drop it. Or you can add it, and write a correction.

4:1905 · How long to wait?

4:21

Six copies of the processor read the same replay at the same time, each with different settings. Every click now lands in its own minute. So the only error left is the clicks dropped as late. They’re spread over most of the thousand counts, so few counts are exact.

4:38

With a ten-second delay: eight thousand one hundred eighteen clicks dropped. And each minute’s result typically came eleven seconds after the minute: the delay, plus about a second.

4:51

So wait longer? With a sixty-second delay, how many fewer clicks would be dropped?

4:58

Six thousand seven hundred eighty-four. Only sixteen percent fewer. And results now typically wait sixty-one seconds.

5:07

Remember the gap. Ten seconds already catches the fast ones. The late three percent are minutes late, so only a delay near ten minutes would catch them all. Choose the delay from the lateness you measured, not by feel.

5:2306 · Corrections

5:25

Or don’t drop late clicks. Add them, and write the minute again.

5:30

With corrections, every one of the thousand counts was exactly right, like the batch job. It wrote eight thousand one hundred eighteen corrections, one for each click that arrived after its minute was written out. The last minute stayed open until the stream ended, so its late clicks were in time.

5:49

With the same eleven-second wait for the first result. The price: a minute’s count can change almost ten minutes after it was first written, so everything that reads the counts has to handle updates.

6:0407 · In code

6:05

In code, it’s a few lines. For each click, remember the newest click time seen in its partition.

6:12

Asked for the watermark, it returns the smallest of those, minus the delay.

6:19

The smallest, so a lane that’s behind keeps the minute open, and its clicks aren’t thrown away as late.

6:2708 · Killed 20 times

6:29

Now crashes. The counts live in the processor’s memory. I killed it at the same twenty random moments, and restarted it at once. Both versions of ours use corrections, so without crashes they match the batch job exactly.

6:44

Saving its work every two real seconds, a checkpoint: a thousand of a thousand counts exactly right. Twenty crashes changed nothing.

6:55

Without saving: eight thousand four hundred fifty-six clicks counted, out of three hundred thousand. Ninety-seven percent lost. And zero messages left unread. It read every message, and kept almost none of the clicks.

7:10

For comparison, Quix Streams, a stream processing library, in exactly-once mode: it saves its counts, its position and its output together. Killed the same twenty times, it matched its own uncrashed run exactly. Why that run differs from the batch job is next time.

7:3109 · Why it worked

7:32

Why? Every two real seconds, the processor saves its counts and its position in each partition, in one file, together. That’s a checkpoint.

7:43

And it replaces the old checkpoint in one step, so a crash never leaves half of one.

7:50

After a crash, it reloads the checkpoint and rereads from that position. The minutes it writes again overwrite the same rows with the same values, so writing them twice is harmless.

8:02

The broken version let Kafka save only its position, every real second. After each crash, it started from that position with empty counts, and wrote those partial counts over the full ones. In the letters picture: you remember which letters you’ve opened, but lost the tally.

8:22Back to Lucía

8:23

So, three lessons.

8:26

Count by when it happened, not when it arrived.

8:31

Pick the watermark delay from the lateness you measured. Or keep the late events, and correct.

8:38

And save the counts and the read position together. Reading every message isn’t the same as counting it.

8:46

Next time: two processors that disagree on the same job, and counting in kilobytes.

8:53

For today: trust the postmark.Lucía: Trust the postmark.

8:56Summary

8:58

Count by event time, choose the delay from data or correct, and checkpoint the counts with their position.

Key takeaways

  • ✓Counting by arrival time got only 12.5% of the 1,000 minute-by-ad counts exactly right, with 6.7 clicks off per count on average, because a click that arrives late lands in the minute it reached the processor, not the minute it happened.
  • ✓A watermark is the processor's claim that a minute is probably complete: the newest click time in the slowest of the stream's six partitions (lanes read in order), minus an allowed delay. A minute's count is written once the watermark passes its end.
  • ✓With a 10 s delay, 8,118 of 300,594 clicks arrived too late and were dropped. With 60 s, 6,784 were dropped: six times the wait cut the drops by only 16%, because 3% of the clicks in this stream arrive 1 to 10 minutes late.
  • ✓Corrections gave every one of the 1,000 counts exactly, by writing a minute again for each of the 8,118 late clicks, at the cost that a count can change up to about ten minutes after it was first written.
  • ✓Killed 20 times, the processor that saved its counts and its read position together every 2 real seconds matched batch in all 1,000 counts. The one that saved only its read position every real second, with its counts in memory, counted 8,456 of 300,594 clicks: 97% lost, while leaving 0 messages unread.

Ad clicks, counted per minute, are a question about when each click happened, not when the processor saw it. This chapter takes one generated stream of 300,594 clicks and counts it several ways: by arrival, by event time with a watermark (a moving claim about how complete a minute is), and with corrections. Then it kills the processor 20 times to see what a crash does to the counts.

The examples come from Lab 14 (Stream Processing) of the system design labs. Two scripts matter here: 01_windows_late.py (six processors read the same replay with different settings, each graded against a batch answer) and 02_checkpoints.py (the processor killed 20 times, with and without checkpoints). The setup is the earlier chapters' laptop, an Apple M4 Max with Docker Desktop and 16 virtual CPUs. Kafka (a log of messages, split into named streams called topics) ran as one node, with Postgres holding the results, and the stream was replayed at 10 times real speed. The lab's README puts scripts 01 to 04 at about ten minutes in all. Each job is one recorded run, so read the shapes more than the last digit.

Event time and processing time

Think of counting letters by the week they were sent. The postmark says when a letter was posted: that is event time. The day it reaches you is processing time. Some letters sit in a drawer for a while, and those are the late ones.

For a click, event time is the moment it happened, written into the event. Processing time is when the processor sees it. The two differ by network delay, retries, and, for a phone that was offline, minutes.

The stream was generated so the difference matters. Of its 300,594 clicks, 97% reach Kafka within 5 seconds. The other 9,036 (3%) arrive one to ten minutes late, like a phone that was offline. There were also 3,170 duplicate messages, which the processor recognises by each click's id and counts once.

Counting by processing time is the simplest design: each click goes into the minute it arrives. Its results were ready about 0.6 seconds after each minute ended. But only 125 of the 1,000 counts (12.5%) were exactly right, and a count was off by 6.7 clicks on average. A click that crossed a minute's end on its way landed in the wrong minute: missing from its own, and extra in a later one. The clicks that arrived after the tenth minute were not in the ten minutes at all. A rerun could also give different numbers, because the processor's own clock decides which minute a click falls in.

Tumbling windows, and when a minute is final

The counts are tumbling windows: fixed, non-overlapping spans of time. Here each window is one minute, [0, 60), [60, 120) and so on, and each click belongs to exactly one window. (The lab also has sliding and session windows; this chapter does not cover them.)

Event time puts each click in the right window. The hard part is deciding when a window is final, because a stream never sees its own end. That is what a watermark is for.

Watermarks: how long to wait

A watermark is a claim: "I have probably seen everything up to this time." The lab computes it this way. For each partition, take the newest click time seen so far and subtract an allowed delay. The stream's watermark is the slowest partition's value, because a lane that is behind may still hold clicks from earlier.

When the watermark passes the end of a minute, that minute's count is written out. In the letters picture: "I have probably got everything postmarked before Tuesday." Any click that arrives for a minute already written out is late. The processor can drop it, or add it and write the minute again.

The code is a few lines. For each click, the processor remembers the newest click time in its partition. Asked for the watermark, it returns the smallest of those, minus the delay. The smallest is the point: one partition that is behind keeps every minute open, so its clicks are not thrown away.

With event time and a 0-second delay, the processor placed every counted click in its right minute and dropped 9,520 clicks as late. Its error was exactly the clicks it dropped: missing, never misplaced. The delay is the only knob, and it moves two costs against each other. A longer wait drops fewer clicks, and every result arrives later.

What happens to late clicks

The lab ran three answers to late clicks, and all three were graded against batch:

  • Delay 0 s: 9,520 clicks dropped, 15.9% of the counts exact, the result about 0.8 s after each minute ended.
  • Delay 10 s: 8,118 dropped, 17.5% exact, the result about 10.8 s after the minute (the delay, plus about a second of polling and writing).
  • Delay 60 s: 6,784 dropped, 27.6% exact, the result about 60.9 s after the minute.

Waiting 60 s instead of 10 cut the drops by only 16%, and made every result 50 s later. The lateness here was designed to have two groups. 10 s catches the 97% that arrive within 5 s, and nothing short of about ten minutes catches the 3% that arrive one to ten minutes late. Real systems will have a different shape, so the lesson is to measure the lateness and choose the delay from it, not by feel.

The other choice is to keep late clicks. With corrections, a late click that arrives after its minute was written adds to that minute, and the minute is written again. The run wrote 8,118 corrections, one for each late click, and all 1,000 counts came out exact, the same as batch. The last minute stayed open until the stream ended, so its late clicks were still in time. The price is that a minute's count can change up to about ten minutes after it was first written, so everything that reads the counts must handle updates.

Try it · When is a minute final?Lab 14 · 01_windows_late.py · recorded run, 10× replay

Share of the 1,000 (minute, ad) counts exactly right, by job

Waiting 10 s catches the fast 97%. The late 3% are 1 to 10 minutes late, so no short delay catches them.

Clicks counted
292,476 / 300,594
Clicks off, per cell
8.1
Result after minute ends, median
10.8 s
Corrections written
0

Times are the stream's clock. The slowest result in each job waited about 600 s for the stream to end, because the watermark stops once the clicks stop.

Checkpoints, and what replays after a crash

So far the processor never crashed. Its counts live in memory, and a process that dies loses them. A checkpoint saves the counts and the read position of each partition, in one file, every 2 real seconds. The save replaces the previous checkpoint in one step, so a crash never leaves half of one.

After a crash, the processor reloads the checkpoint and reads from the saved position again. The minutes it writes again overwrite the same rows with the same values, so writing a result twice does no harm. The lab calls this an upsert: insert the row, or replace it if its key is already there.

The lab compared three runs. The same stream was replayed four ways, and three of them were killed without warning at the same 20 random moments, then restarted at once:

  • Our processor, checkpoints every 2 real seconds: all 1,000 counts exactly right against batch, all 300,594 clicks counted, 20 crashes with no change.
  • Our processor, no checkpoint: Kafka saved the read position every real second, and the counts stayed in memory. After each kill it started from the saved position with empty counts. It counted 8,456 of 300,594 clicks (97% lost), 44 of 1,000 counts exact, and it left 0 messages unread. It read every message and kept almost none of the clicks.
  • Quix Streams, in exactly-once mode: Quix Streams is a Python library for stream processing. It saves its state, its position and its output together, and matched its own run with no kills in all 1,000 counts, with 292,477 clicks in both. (Batch is the reference for our two processors. For Quix it is its own uninterrupted run.)

The difference was what got saved together. "Reading every message" and "counting every message" are different claims. In the letters picture: you remember which letters you have opened, but you lost the tally.

Try it · Killed 20 timesLab 14 · 02_checkpoints.py · recorded run, same kill moments

Ours, checkpoint every 2 real s

Clicks counted, of 300,594
100.0%
Cells exactly right, of 1,000
1,000
Kills
20
Clicks counted
300,594
Messages unread at end
in checkpoint

Every restore went back to counts and offsets saved together, so the clicks after the checkpoint were counted once.

The workflow and the results

Here is the sequence the lab followed, and what each step showed.

  • Generate a known stream: 300,594 clicks on 100 ads over ten minutes, 3,170 duplicates, 3% of clicks late by one to ten minutes, spread over six partitions. A batch job (DuckDB, an embedded SQL database) computed the answer over the whole finished dataset, and it matched the generator's known totals exactly. That batch answer is the reference for every stream job.
  • Replay at 10 times real speed, and grade each job cell by cell: the 1,000 cells are the 10 minutes times the 100 ads. Six jobs read the same replay: processing time, event time with 0, 10 and 60 s of delay, event time with 10 s and corrections, and a sliding-window job that the video does not cover.
  • Kill and restart: three jobs were killed 20 times at the same random moments, and the fourth, Quix not killed, was the reference for the killed Quix.

Across those runs the rule held. Event time put every counted click in the right minute, and its totals fell short by exactly the clicks dropped as late. Corrections were the only setting that made every count exact. Checkpoints were the only setting that survived 20 kills with no loss.

Caveats

  • One replay, one run per job. The six jobs read one replay together, and each crash test is one run. The no-checkpoint result depends on where the kills land: an earlier run of the same test counted 14,614 clicks, and the table shows the later 8,456.
  • A clock bug was found and fixed. The processing-time job's clock ran about half a real second ahead of the replay, because each started its own clock. That run showed 5.7% exact and results about 5 s late. After the lab fixed the replay to share one start time, the numbers here came out at 12.5% and about 0.6 s. Event-time results were unchanged.
  • The lateness is the generator's design. The two-group shape made the 16% result specific to this stream. A stream with a different lateness distribution would show a different cost for each delay.
  • The data is simulated, on one laptop. The stream is generated, the replay is 10 times faster than real time, and the broker, database and processors share one machine. The shapes should carry over; the exact figures will not.
  • Not tested: sliding and session windows, checkpoint intervals (the lab asks why not checkpoint every 100 ms, but does not measure it), large state of gigabytes, and the lab's framework comparison (script 03_framework.py, which compares our processor with Quix on speed and on the same job). That is for the next chapter, where the two processors disagree on the same job.

The checklist

  1. Count by when it happened. Counting by arrival got 12.5% of the counts right here; event time got every counted click into its right minute.
  2. Choose the delay from the lateness you measured. Here 97% of clicks arrive within 5 s and 3% arrive one to ten minutes late; a delay of 60 s instead of 10 s cut the drops by 16%.
  3. Decide what late data does, on purpose. Either drop it and accept the error (8,118 clicks here), or add it and correct the minute (8,118 corrections here), which makes every count exact but means counts can change after they were first written.
  4. Save the counts and the read position together. A checkpoint did it every 2 real seconds and survived 20 kills with 1,000 of 1,000 counts exact; saving only the position lost 97% of the clicks.
  5. Test that a crash does not change the answer. Kill the processor during the run and compare the final counts with batch, not with the last result you saw.

Quiz

Try it · Check your understanding0 of 3 answered
  1. 1.A click happened at 10:04:58 and reached Kafka at 10:05:03. Counting by processing time (when the processor sees a click) puts it in which minute?

  2. 2.With a 10-second watermark delay the lab dropped 8,118 clicks, and with 60 seconds it dropped 6,784. Why didn't waiting six times as long fix it?

  3. 3.A processor saves its counts only with Kafka's auto-commit of its read position, every real second. It is killed and restarts from the saved position with empty counts. What happens to the totals?

Check your understanding

Try each question before opening its answer.

Counting by arrival got 12.5% of the counts right, and counting by event time put every counted click in its own minute. Why does event time still lose clicks?

Event time places each click correctly, but a watermark has to decide when a minute is final, and a click can arrive after that. A late click is either dropped or, with corrections, added by rewriting the minute. The 0-second delay dropped 9,520 clicks, and the errors were exactly those drops: missing clicks, never misplaced ones.

Why does the watermark use the slowest partition rather than the newest click?

A partition that is behind can still hold clicks for minutes that the newest click has already moved past. If the watermark followed the newest click, it would close those minutes early and the partition's clicks would look late. Taking the smallest value keeps a minute open until every partition has moved past it, minus the delay.

Why did waiting 60 seconds instead of 10 cut the dropped clicks by only 16%?

The lateness had two groups: 97% of clicks arrived within 5 seconds, and 3% arrived one to ten minutes late. Ten seconds already caught the fast group, and only a delay near ten minutes would catch the slow one. So six times the wait dropped 6,784 instead of 8,118 clicks, and every result came 50 seconds later.

Corrections made all 1,000 counts exact. What did that cost, and when is it the wrong choice?

It cost 8,118 rewrites, one for each late click, and a count that could change up to about ten minutes after it was first written, so every reader has to handle updates. It is the wrong choice when readers cannot accept a number that changes; then a delay and an honest drop count are simpler. Corrections fit when the exact total matters more than a stable first answer, such as a bill.

After a restart, the no-checkpoint processor read every message and still counted 8,456 of 300,594 clicks. What did it keep, and what did it lose?

It kept the read position, because Kafka's auto-commit had saved it every real second. It lost the counts, which were only in memory. Each restart counted what came after the saved position and wrote those partial counts over the full ones. A checkpoint saves the counts and the position in one step, which is why the same kills left all 1,000 counts exact.

Next up: Chapter 33, two stream processors that disagree on the same job. The lab's framework comparison runs our processor and Quix Streams on the same job, and they disagree on 526 of 1,000 counts. The next chapter explains why, and counts in kilobytes with sketches.

Learning something useful?

New labs, articles, and videos on evaluating and testing AI systems come out regularly. Follow along so you don't miss the next one.