Count 12,144 clicks per minute while they arrive out of order. Group them by arrival time and 549 land in the wrong minute. Group them by when they happened and wait 2 s: 370 clicks come too late and the job drops them, nearly all from phones that were offline. Keep each minute open for late clicks, and all ten counts end exact.
Pick how the job decides that a minute is complete. Switch the offline phones off and on. Then we build each part from zero: logs, partitions, change capture, event sourcing, windows, watermarks, joins and crash recovery.
You need a little Python and what a database table is. We build the rest from zero.
Illustrative and seeded: 20 clicks a second for 10 minutes. A click reaches the job 0.1 s plus a random delay with a mean of 0.8 s after it happens. A click from an offline phone arrives 60 to 240 s late.
Chapter 0
Measure how stale a batch answer is, then shrink the batch
A shop counts its sales per minute. A batch job runs every hour over the last hour of orders. A sale at 14:01 shows up after 15:00, when that run finishes. The question is fine; the answer is old.
A stream is data that never ends: events keep arriving, one at a time. An event is a small, fixed record of something that happened, with the time it happened. Stream processing handles each event soon after it arrives, instead of waiting for a pile.
Blue dots are sales arriving. Orange bars are batch runs. The yellow line is how old the newest answer's data is. Shrink the interval and watch the runs pile up.
Illustrative. Sales arrive evenly; each run takes every sale since the last run started. A run that takes longer than the interval cannot keep up.
How long does a sale wait to reach the answer? Call the batch interval B, the time one run takes J, and the average wait A.
A equals B over two, plus J.
A sale lands at a random moment in the interval, so it waits B/2 on average for the next run to start. Then it waits J for that run to finish. Add the two.
With made-up numbers: B = 60 min, J = 5 min. A = 30 + 5 = 35 min, and the unluckiest sale waits B + J = 65 min. With B = 15 min, A = 12.5 min.
Why not run the batch every minute? Each run has a fixed start-up cost and reads its input from scratch. With J = 5 min and B = 1 min, a new run starts before the last one ends, and they pile up. A stream job instead runs all the time and keeps its state in memory between events.
This lesson follows Chapter 12 of Designing Data-Intensive Applications, 2nd edition, by Martin Kleppmann and Chris Riccomini (O'Reilly, 2026). We explain its ideas in our own words, with our own examples and simulations. Batch Processing built derived data from a fixed input. Here the input never ends.
Failure. Symptom: the "live" dashboard shows numbers from an hour ago. Measure: the time from an event to the answer that includes it. Cause: a batch job on a timer. Fix: process each event as it arrives (Chapter 5 onward).
Chapter 1
Process ten messages with a bug, ship the fix, and see which broker lets you redo the work
A producer writes events; a consumer reads them. Between them sits a message broker, a server that holds the events, so neither side waits for the other. Messaging covers queues and fan-out in depth. Here we need one difference.
A classic broker, of the kind built on the AMQP or JMS standards, keeps a queue. It hands each message to one consumer and deletes it when the consumer acknowledges it. A log-based broker, such as Kafka, appends each message to a file on disk and keeps it. Each consumer remembers its own position, an offset, and reads forward from it.
The consumer had a bug on messages 3 to 6 and wrote wrong results. Pick a broker, then deploy the fix and try to recover.
Illustrative: ten messages and one consumer. The log keeps every message for its retention time; the queue keeps only what nobody has acknowledged.
The Kafka paper (Kreps, Narkhede and Rao, 2011) lists this as a side benefit. A consumer can rewind to an old offset and read the data again, for example after a bug fix. The broker does not track who read what, so it cannot tell when every reader has finished. It deletes by age, typically after 7 days. How much disk does that take? Call the message rate λ, the bytes per message b, the retention time T, and the disk used S.
S equals lambda times b times T.
Every second adds lambda messages of b bytes each. The broker keeps T seconds of them. Multiply the three.
With made-up numbers: λ = 20,000 messages a second, b = 1 KB, T = 7 days = 604,800 s. S = 20,000 × 1,000 × 604,800 = 12.1 TB, and 36.3 TB with three copies. Decimal TB, 1012 bytes.
A queue suits work items, such as "resize this image", where order and history do not matter. A log suits a record of what happened, which many readers will each want to read in order, now and later.
Failure. Symptom: after a bug fix, a search index stays wrong for the products the bug touched. Measure: whether the broker still holds those messages. Cause: a queue deleted them when the buggy consumer acknowledged them. Fix: keep the history in a log, and replay from the offset before the bug.
Chapter 2
Split a topic over six partitions, add and slow consumers, and watch the lag
One log on one machine has a limit. So a topic, a named stream such as "clicks", splits into partitions. Each partition is its own log, on its own broker, with its own offsets. The producer sends a message to partition hash(key) mod P, so every message for one user goes to one partition, in order. Order holds inside a partition, not across them.
A consumer group is a set of consumers that share a topic. Each partition goes to exactly one consumer in the group. The Kafka paper makes the partition "the smallest unit of parallelism" for that reason: two consumers on one partition would need locks. Another group reads the same topic on its own, with its own offsets.
Each row is a partition after 60 s. Purple is read, pink is unread. Right: which consumer owns it. Add consumers past six, then slow consumer 2.
Illustrative and seeded: 1,000 users with Zipf popularity, partition = FNV-1a(user) mod 6. Each consumer reads up to 250 messages a second and takes a contiguous range of partitions.
The consumer commits its offset now and then; modern Kafka stores it in an internal topic. The gap between the newest offset and the committed one is the consumer lag. Turn it into time. Call the newest offset Oend and the committed one Oc. Call the partition's write rate λp and the age of its oldest unread message a.
a equals O-end minus O-c, divided by lambda-p.
The lag, O-end minus O-c, is a count of unread messages. Writing them took about lag divided by lambda-p seconds, so the next one to read is that old.
From the device, with consumer 2 slowed. Partition 4 has Oend − Oc = 5,107 unread messages and gets λp = 116 a second. a = 5,107 / 116 = 44 s. Its readers see data 44 s old, and it grows each second.
With six partitions, a seventh and eighth consumer sit idle. When a consumer joins, leaves or dies, the group reassigns partitions: a rebalance. A dead consumer's partitions resume from the last committed offset, so some messages are read twice (Chapter 8). Run a Consumer Group works out the throughput limit.
Failure. Symptom: alerts fire minutes after the problem. Measure: lag per partition, as a count and as an age. Cause: one slow consumer, or one partition that holds a hot key. Fix: add partitions and consumers for the first; a hot key needs a different key, because hashing sends all of it to one partition.
Chapter 3
Write to a database and a search index at the same time, then feed the index from the database's log
Your products live in a database. A search index and a cache hold copies, each derived data. The obvious design: when the app saves a product, it writes the database, then the index. These are dual writes, and two things break them.
First, a race. Two users edit the same product at once. Each writes the database, then the index. Their four writes can interleave in six orders that keep each user's own order. In two of the six, the database keeps one edit and the index keeps the other, for good. Second, a crash or error between the two writes leaves one copy without the change.
Each cell is a product that two users edited at once. Green: the database and the index agree. Red: they disagree. Switch to change data capture.
Illustrative and seeded: 300 products, two concurrent edits each, the four writes in a random order. With capture, the index applies the database's changes in the database's own order.
Worked number: 6 orders, 2 that disagree, so one in three. The seeded run found 90 of 300 products split, 30%.
Change data capture (CDC) fixes both. The app writes only the database, the one system of record. A connector reads the database's replication log and publishes each committed change, in commit order, to a log-based broker. The index and the cache consume that stream. They may lag, but they apply the same changes in the same order, so they end up equal. What the Leader Sends describes the log a follower uses; CDC hands that log to any reader.
Debezium is one such connector. For PostgreSQL it reads changes through logical decoding. It starts with a consistent snapshot, one "read" event per row, then streams creates, updates and deletes. Each event carries the row before and after, keyed by the primary key. After a delete it sends a tombstone, a message with that key and no value.
The tombstone serves log compaction. A compacted Kafka topic keeps at least the newest message for each key and drops older ones; a tombstone lets it drop the key entirely. A new index can then read the compacted topic from offset 0 and get every row's current value, without the full history.
Failure. Symptom: search shows an old price for a few products, forever. Measure: compare the index with the database, key by key. Cause: dual writes raced, or one write failed. Fix: write only the database and derive the index from its change stream. The Outbox is the same idea for events your app writes itself.
Chapter 4
Replay a cart's events to any moment, then add snapshots and count the work
CDC captures changes to rows. Event sourcing goes one step further: the app never stores the current state at all. It appends events, "added 2 mugs", "removed the pen", to an event log. The current state is a fold over that log: start empty and apply each event in order.
The log is the record; the state is derived. You can rebuild the state as of any event and find out how a cart went wrong. You can also build a second view, say "items often removed", from the same events. A command ("add the mug") may fail a check; once it passes, it becomes an event, a fact.
The row of boxes is 40 cart events. The cart beside them is rebuilt from them. Move the slider to replay to any point; switch snapshots on and count the orange events replayed.
Illustrative and seeded: 40 events over five items. A snapshot is the cart's state saved after every tenth event.
Replaying 50 million events at every restart is slow. So the system saves a snapshot, the state after every s events, and replays only what came after the newest one. Call the number of events N, the snapshot spacing s, and the events replayed R.
R equals N minus s times the floor of N over s.
The newest snapshot sits after s times the floor of N over s events. Load it, then replay the rest: N minus that.
With made-up numbers: N = 50,030,000 and s = 100,000. The newest snapshot is at 50,000,000, so R = 30,000 events instead of 50 million. In the device, N = 37 and s = 10 give R = 7.
A snapshot is derived data too; if one is corrupt, rebuild it from the log. One thing does not carry over from CDC: compaction. A CDC event holds the whole new row, so the newest one per key is enough. An event such as "added 2 mugs" depends on all the ones before it, so dropping old events would change the cart.
A database table and its change stream are two views of one thing. Fold the stream and you get the table; record each change to the table and you get the stream. Readers query a materialized view, a table kept up to date from the events. Splitting writes from reads this way is often called CQRS.
Failure. Symptom: a service takes 20 minutes to start after a deploy. Measure: events replayed at start-up. Cause: it rebuilds state from event 0. Fix: snapshot every s events and replay from the newest snapshot.
Chapter 5
Lay four window shapes over one user's clicks and count what each one sees
"Count the clicks" has no answer on a stream that never ends. "Count the clicks per minute" does. A window is a stretch of time the job aggregates over: a count, a sum, an average. When the window closes, the job emits its result and can forget its contents.
There are four common shapes:
Blue dots are one user's clicks over ten minutes. Teal bars are windows, with their counts. Try each shape.
Illustrative and seeded: 31 clicks from one user, in bursts with long pauses.
Names differ by system. The Dataflow paper and Flink call the hopping shape "sliding". Kafka Streams keeps "sliding" for a window aligned to each record's timestamp, as here. Hopping windows cost more work. Call the window length S, the hop A, and the windows each click falls into k.
k equals S over A.
Windows start every A seconds and last S seconds, so S over A of them are open at any moment. Each click lands in all of them. A tumbling window has A = S, so k = 1.
With made-up numbers: S = 5 min, A = 1 min, so k = 5. At 1,200 clicks a minute the job does 6,000 window updates a minute and keeps five windows of state per key.
In the device, hopping windows of 2 minutes find a burst of 14 clicks that the 1-minute tumbling windows split into 8 and 6. A session window with a 1-minute gap finds four visits. Pick the shape from the question, not the tool.
Failure. Symptom: a "trending now" list jumps around every minute. Measure: how much a rank moves between two neighbouring windows. Cause: 1-minute tumbling windows split bursts at the boundary. Fix: hopping windows, 5 minutes long every minute, at k = 5 times the work.
Chapter 6
Plot every click by when it happened and when it arrived, then set how long a window waits
Every click has two times. Event time is when it happened, stamped by the phone. Processing time is when the job sees it. A phone in a tunnel sends its clicks minutes late, and a restarted job reads an hour of backlog in seconds.
Group by processing time and that backlog lands in one minute; the hero put 549 clicks in the wrong minute this way. Group by event time and a new question appears. When is the minute from 10:00 to 10:01 complete? More of its clicks may still be on their way.
A watermark is the job's claim that no more events older than time W will arrive. MillWheel (Akidau and colleagues, 2013) called it the low watermark. A common rule takes the largest event time seen so far, minus a fixed wait. Call the largest event time seen tmax, the wait d, and the watermark W.
W equals t-max minus d.
Track the newest event time, t-max. Assume nothing older than t-max minus d is still coming. Fire every window that ends at or before W.
With made-up numbers: the newest click so far happened at tmax = 125.3 s, and d = 2 s. W = 123.3 s, past 120 s, so the window from 60 to 120 s fires. A click from 119 s that arrives now is late.
Each dot is a click: across, when it arrived; up, when it happened. The yellow line is the watermark. Red clicks came after their minute fired, and the job dropped them; pink ones updated it.
Illustrative and seeded, the hero's stream. The plot shows the first four minutes of event time; the read-out counts all ten.
The Dataflow paper (Akidau and colleagues, 2015) names the dilemma. A watermark is sometimes too fast: late data arrives behind it. It is sometimes too slow: one slow source holds it back. The answer: fire at the watermark, then fire again when late data comes. Flink calls the extra time allowed lateness. Its default is zero, so Flink drops late events; a side output can catch them.
In the device, d = 0 drops 482 clicks and d = 2 s drops 370, nearly all from offline phones. Five minutes of allowed lateness turns all 370 into updates, and each window's state lives 5 minutes longer.
Failure. Symptom: the stream's daily totals are 3% below the batch totals. Measure: events dropped as late. Cause: a short wait and no allowed lateness. Fix: allow lateness for your stragglers and send updates, or catch late events in a side output.
Chapter 7
Enrich clicks with each user's country while users move, three ways
A batch join sees both inputs whole (Three Ways to Join). A stream join never does. There are three kinds:
For a stream-table join, the job could query the users database for every click: a remote lookup, one network round trip per event. Usually it keeps a local copy of the table instead, fed by the table's change stream (Chapter 3). That copy lags the database by the CDC delay.
Each row is a user who moves country once, at the purple tick. Dots are their clicks: green right, red wrong. Yellow is the time the local copy is stale. Raise the lag, then join by event time.
Illustrative and seeded: 20 users, 2 clicks a second for 10 minutes, 10 users move once. The truth is the country at the moment of the click.
The right answer depends on time. A click from 10:00 should get the country the user had at 10:00. A lookup at processing time gets the newest value instead: wrong during the CDC lag, and wrong for any click that arrives late. A versioned table keeps each row's history, so the join can look up the value as of the click's event time. Kafka Streams supports versioned tables for this, and Flink SQL has event-time temporal joins.
A stream-stream join must hold both sides' events for the length of the window, waiting for a match. Call the event rate on one side λ, the window w, the bytes per event b, and the memory for that side M.
M equals lambda times w times b.
Every event waits w seconds for a partner. Lambda arrive each second, so lambda times w are waiting at once, at b bytes each.
With made-up numbers: 10 million impressions an hour, so λ = 2,778 a second, w = 3,600 s, b = 200 bytes. M = 10 million events, 2.0 GB, for the impressions alone.
Failure. Symptom: last month's sales report credits some orders to the wrong region. Measure: re-run a sample with each customer's region as of the order date. Cause: the join used the customer table as it is now. Fix: join on a versioned table by event time, or store the region in the order event itself.
Chapter 8
Crash a job mid-stream and compare four ways to restart it
A batch task that fails is rerun from its fixed input, and its output appears all at once (Write Files, Then Swap). A stream job never finishes, so it cannot wait until the end to publish. It must restart from somewhere in the middle without losing events and without counting them twice.
The job saves its input offsets and its state now and then. After a crash it goes back to the last save and reads again from there. The job replays the events between that save and the crash. Call the event rate λ, the time of the last save tk, the crash time tc, and the replayed events E.
E equals lambda times, t-c minus t-k.
Everything the job did after t-k is lost with the crash and done again. That is t-c minus t-k seconds of events, lambda per second.
From the device: λ = 10 a second, saves every 5 s, a crash at tc = 23.7 s, so tk = 20 s. E = 10 × 3.7 = 37 events replayed.
Replay is safe only if those 37 events leave no second trace. When You Commit Decides What You Lose covers the basic choice. Save the offset before processing and lose events (at most once). Save it after and repeat them (at least once). Stream processors get further with four tools:
600 events, each adding 1 to a total in the sink. Purple ticks are checkpoints, orange is work done twice. Pick a mode; then move the crash.
Illustrative: 10 events a second for 60 s. "At most once" reads in 1-second batches and commits each batch before working on it.
Exactly once here means effectively once: the job may process an event twice, but the visible result counts it once. It holds only inside the system. An email from before the crash goes out again after it, unless the email service also ignores repeats.
Failure. Symptom: after each restart, some counters jump. Measure: compare the sink's totals with a recount from the log. Cause: an at-least-once job adding to a counter. Fix: write keyed, idempotent results, or commit outputs and offsets together.
Chapter 9
Turn every knob of the hero's job, crash it, and find a setting that is exact, prompt and safe
Back to the hero, with the whole pipeline. Clicks arrive, and the job counts them per minute of event time. A crash may hit it at 367 s. A sink stores the counts: one sink adds what the job emits, one overwrites by minute, one commits with each checkpoint.
Bars are what the sink holds for each minute; the outline is the truth. Red is missing or extra clicks. Switch the crash on with the adding sink, then change the sink.
Illustrative and seeded, the hero's stream. The job checkpoints every 10 s; the crash rolls it back to 360 s. Late updates go to the sink as deltas or as full counts, by sink.
Start with the adding sink, a 2-second wait and the crash on. Minute 6 fired at 362.7 s, after the checkpoint at 360 s. The restart emits it again, and the sink stores 2,298 clicks against a true 1,198. The overwriting and transactional sinks store 1,149: correct apart from the 370 late clicks dropped everywhere.
Now allow 5 minutes of lateness. With the overwriting sink every minute ends exact, crash or not, and results come 2.4 s after each minute. The transactional sink is exact too, but each result waits for the next commit: 10 s after the minute. Exact, prompt and safe together needs event time, allowed lateness and a sink that ignores repeats.
Failure. Symptom: one minute in the report shows double the clicks, on a day with a restart. Measure: the job's restart times against the windows that fired just before them. Cause: a sink that adds, fed by a job that replays. Fix: key each result by its window and overwrite, or commit with the checkpoint.
Chapter 10
Keep the numbers, the rules and the code for the next stream job you build
A stream job is a batch job whose input never ends. Events sit in a partitioned log, so readers can replay them. Change capture turns a database into such a log, and event sourcing makes the log the record. Windows cut time into pieces; watermarks decide when a piece is complete, and allowed lateness repairs it. Joins need the right version of the table. Checkpoints plus idempotent or transactional sinks make a crash invisible.
| Idea | Rule | This lesson's number |
|---|---|---|
| Batch delay | A = B/2 + J | hourly, 5 min job: 35 min average, 65 worst |
| Log retention | S = λ · b · T | 20,000/s, 1 KB, 7 days: 12.1 TB per copy |
| Consumer lag | a = (Oend − Oc) / λp | 5,107 unread at 116/s: 44 s old |
| Dual writes | 2 of 6 orders disagree | 90 of 300 keys split; CDC: 0 |
| Snapshots | R = N − s · ⌊N/s⌋ | 50,030,000 events, s = 100,000: replay 30,000 |
| Hopping windows | k = S / A | 5 min every 1 min: 5 windows per click |
| Watermark | W = tmax − d | d = 2 s: 370 dropped; lateness 5 min: 0 dropped |
| Join state | M = λ · w · b | 10 M impressions an hour, 1 h window: 2.0 GB |
| Replay | E = λ · (tc − tk) | 10/s, crash 3.7 s after a save: 37 events |
| Sink after a crash | adds, overwrites or commits | adding: minute 6 = 2,298 against 1,198 |
pythondef window_count(events, size=60, wait=2, late=0): """events: (event_time, arrival_time) pairs. Tumbling windows by event time.""" count, fired, out = {}, set(), [] t_max, dropped = float('-inf'), 0 for te, tp in sorted(events, key=lambda e: e[1]): # in arrival order w = int(te // size) t_max = max(t_max, te) W = t_max - wait # the watermark if w in fired and W >= (w + 1) * size + late: dropped += 1 # too late even for an update else: count[w] = count.get(w, 0) + 1 if w in fired: out.append((w, count[w], 'update')) # send the full count: overwrite, not add for v in sorted(count): if v not in fired and W >= (v + 1) * size: fired.add(v); out.append((v, count[v], 'fire')) return out, dropped ev = [(10, 10.5), (59, 59.4), (61, 61.2), (63, 63.1), (58, 70.0), (125, 125.3)] print(window_count(ev)) # ([(0, 2, 'fire'), (1, 2, 'fire')], 1): the click from 58 s came too late print(window_count(ev, late=300)) # ([(0, 2, 'fire'), (0, 3, 'update'), (1, 2, 'fire')], 0)
Now press Present or Teach and explain four things from memory. Why can a log replay after a bug when a queue cannot? Why do dual writes leave copies that disagree? What does a watermark claim, and what happens to a click that arrives behind it? Why does a crash double a count only with some sinks? Then go back to the hero and find the setting that gets all ten minutes exact.