Systemsfor Aravinda
0 / 78 core
Week 5 · Messaging

Stream processing

1.5 hours · core path

Read first: Kafka

In one sitting

Event time is when the click happened and processing time is when you saw it, so a replay moves processing time and leaves event time alone. Tumbling, sliding, and session windows close on a watermark, which is a guess that late events are finished arriving. A consumer loop is the whole design until you need a window, a join, or state that must survive a crash without double-counting.

A Kafka consumer that reads a record and writes a row is already a stream processor. The frameworks exist for the moment that loop is no longer honest: you need a total per hour, you need to join two logs, or you need state that must survive a crash without counting a click twice. Until that moment, a loop and an offset are the design. After it, you have taken on a definition of time, and most of the bugs are you using the wrong clock.

Core concepts

Two clocks. Event time is the time on the event, the moment the user clicked. The producer stamps it. Processing time is when your operator saw the record, your wall clock. They diverge whenever a phone buffers, a consumer lags, or you replay yesterday’s log today. A replay is the clean demonstration. The bytes are the same, the event timestamps are the same, and processing time is “now.” Any total you grouped by processing time will move to the day you ran the replay. Any total you grouped by event time can be rebuilt, provided you still have the log and you use the same rule about late arrivals.

That last clause is the whole difficulty. Event time lets you rebuild. It also forces you to admit that the hour is not closed when the clock on the wall strikes the next hour. A click from 10:59 can arrive at 11:20. If you publish the hour at 11:00, you published early.

Windows. A window is which events share a total.

A tumbling window is a fixed slice that does not overlap the next one. The 10 o’clock hour holds clicks whose event time falls in that hour, starting at the top of the hour and stopping before the next. Each click belongs to one window. The state for a key is one bucket, then the next bucket. This is the shape of “clicks per hour” and “revenue per day.”

A sliding window overlaps. A 60-minute window that starts every 5 minutes means a click at 10:07 sits in every window that covers 10:07. The count of those windows is the length divided by the step, 60 / 5 = 12, for a steady stream away from the edges of the data. You did not get a smoother chart for free. You got about 12 times the buckets, and a naive store keeps about 12 copies of an hour of state. A structure that stores each click once and points windows at it avoids paying twelve times. The naive reading is the one that fills a disk.

A session window has no fixed edge. A gap defines it. Clicks from one user separated by less than the gap, say 30 minutes because that is the product’s definition of “still in the product,” are one session. The end of the session is not known when the click arrives. It is known when you are willing to bet that no further click with an earlier event time is still coming. That bet is the watermark. Session windows look friendly in a product doc and expensive in state: a key that never goes quiet never closes, and its state never drops, unless you also cap the session length.

A watermark is a guess. It is a policy that says “I now believe events with event time earlier than T are done arriving.” It is not a measurement of the user’s phone, and it is not a fact the log can prove. You invent T from what you have seen. Two common shapes, both guesses: processing time minus a bound you chose, or the latest event time you have observed on this partition minus a bound you chose. A phone that is still offline looks identical to a partition that is caught up. The watermark advances, the hour closes, and the phone’s click is suddenly late. The user did nothing wrong. Your guess expired.

The guess has operational coupling too. If T is the minimum event time across partitions, one stalled partition holds every window behind the slowest input. If T ignores a quiet partition, you close hours while that partition still has data. You are choosing which failure you would rather explain. There is no watermark that is “correct.” There is a bound on lateness you are willing to wait for, and a story for what happens after the bound.

Late means the window already closed. You have three moves, and you pick before launch. Drop the event. The hour is biased low by whatever fraction arrives late, and the bias is the policy, not a bug in the counter. Keep the window open longer. Results come out later, and fewer events count as late. Emit a revision. The hour goes out as 100 and later as 101. Downstream must replace a total, not increment one. A consumer that only knows how to add cannot host a revision. Delivery guarantees is the same lesson at a smaller scale: an increment applied twice lies, a row that sets the value can be corrected.

When a consumer loop is enough. Stay in the loop when each record is independent, you do not group by time, you do not join another stream, and the state update is safe under a second delivery. Last click per user is the textbook case. Read the record, and write it if its event time is newer than the stored one. A crash redelivers. The compare-and-set on event time writes the same row or an older one you ignore. That update is Idempotency and the exactly-once myth in its natural form: setting state, not adding. You do not need a window, a watermark, or a cluster to schedule operators. You need an offset and a table.

You outgrow the loop when the result is “unique users per campaign per hour,” because the state is a set per key per window, and a crash in the middle of the hour must not double-count the set. You outgrow it when clicks must meet impressions that live on another topic and another partition. You outgrow it when the state is larger than you want to rebuild from scratch on every restart and you need a snapshot of “what I had computed” lined up with “which offsets I had read.” That snapshot is the reason the frameworks exist. It is not a reason to put a per-record copy job inside one.

The hour totals, once you do publish them, are a series you will keep or downsample or eventually drop. That storage problem is Time-series data. Do not make the stream job also the long-term archive unless you meant to.

A worked example

You count clicks per hour, by event time, tumbling. The topic is keyed by user id, so one user’s clicks are ordered on a partition. A phone that was offline is the entire plot.

Assumptions:

  • 10 million clicks a day. A sketch.
  • The hour closes 10 minutes after it ends. A watermark policy you are choosing for this product, not a default of any engine.
  • 1.5 percent of clicks arrive after that close. An assumption about the devices, which you would measure. Until you measure it, the 1.5 percent is a guess about the guess.
  • A session gap of 30 minutes, used only for the session contrast.
  • A sliding window of 60 minutes stepping every 5 minutes, used for the state contrast.
average rate
  10,000,000 / 86,400 = 115.7 clicks per second
  shortcut: 10,000,000 / 100,000 = 100 per second

one hour at the precise rate
  115.7 * 3,600 = about 417,000 clicks

one hour at the shortcut
  100 * 3,600 = 360,000 clicks

late, under the 1.5 percent assumption
  0.015 * 417,000 = about 6,250 clicks an hour

sliding buckets a click sits in
  60 / 5 = 12

A day is 86,400 seconds. The shortcut of 100,000 seconds says about 100 a second and about 360,000 an hour. The precise hour is about 417,000. The shortcut is low by about 16 percent, and that gap matters once the number is a bill. Say which divisor you used.

Walk three clicks. The window is the 10 o’clock hour.

Click C1 has event time 10:50 and arrives at 10:50. It counts in hour 10 whether you use event time or processing time. It teaches nothing. It is the happy path people generalize from.

Click C2 has event time 10:55 and arrives at 11:08. The phone was offline. By event time it belongs in hour 10. By processing time it belongs in hour 11. The watermark you assumed closes hour 10 at 11:10, so C2 gets in. A watermark of zero, “close the hour when the wall clock says 11:00,” would have called C2 late. The 10 minutes is the product waiting so that a short offline gap still counts. It is also 10 minutes of holding the result.

Click C3 has event time 10:59 and arrives at 11:20. The hour has been closed since 11:10. C3 is late relative to this policy. About 6,250 clicks an hour are in C3’s situation if the 1.5 percent assumption holds. If you drop them, every hour you publish is low by that fraction, forever, including hours where the devices were fine and hours where a subway outage made it 8 percent. The watermark did not discover the truth of the hour. You chose a cutoff, and the cutoff is a bias. If the hour is a trend line on an internal dashboard, dropping is a reasonable trade and you should label the chart with the bound. If the hour is what you bill an advertiser, 6,250 missing clicks an hour is a 1.5 percent undercount you will be asked to defend. Then you either wait longer or you emit a revision.

A revision means hour 10 goes out as a number, and later goes out as a new number for the same hour. The sink replaces the row for hour 10. It does not add the late click on top of a row that already included it, and it does not add it in a way that double-counts if the revision itself is retried. Set the hour’s total. Do not add the delta unless the delta carries an id you have stored. This is where teams who “just increment” cannot accept late data without corrupting the past, so they drop it, and then they forget the drop was a policy.

The replay failure is the second clock. Suppose the job had been windowing on processing time, and Monday’s hour totals looked fine. On Wednesday you replay Monday because of a bug in the filter. Processing time is Wednesday. Every Monday click lands in a Wednesday window. Monday’s rebuilt total is zero. Wednesday doubles. You have moved a day of counts by reprocessing, which is the one operation a log is supposed to make safe. Event time puts those clicks back on Monday. It does not save you from C3. The replay and the live job have to use the same lateness rule, or the historical total will not match the total you published on the day. “We replayed” and “we got a different number” is the symptom of a processing-time window, or of a watermark that moved.

flowchart TD
  c1[Click event time 1050] --> hour10[Counts in hour 10]
  c2[Click event time 1055] --> arr2[Arrives at processing time 1108]
  arr2 --> still[Still hour 10 by event time]
  c3[Click event time 1059] --> arr3[Arrives at processing time 1120]
  arr3 --> closed[Watermark already closed hour 10]

Sessions, briefly, so the gap is not a slogan. Clicks at 10:00, 10:20, and 10:40 are one session under a 30-minute gap. You cannot close it at 10:40. You close it when the watermark says event time has passed 11:10, because that is 10:40 plus the gap. A click with event time 10:50 that arrives after you closed the session either splits a session the user experienced as one, or forces a revision that merges them. Reordering makes this worse. Keying by user, which the topic already does, keeps one user’s clicks in order on a partition. A retry that produces the same click with a new key, or with no key, lands on another partition and the session logic is now merging two unordered streams. The window is only as ordered as the key.

Sliding state, so the 12 is not abstract. If a tumbling hour stores a set of click ids for one hot campaign, a sliding hour-every-5-minutes stores about 12 such sets if you are careless, with most of the ids repeated. One campaign that is 30 percent of traffic, an assumption, holds 0.30 × 417,000 = about 125,000 clicks in a tumbling hour, and about 1.5 million set-entries if you naively copy that set into 12 windows. Those entries sit on one partition if the key is the campaign. Partitioning and sharding still applies inside a fancy job. More parallelism does not split one key. The hot campaign’s window state is a hotspot with a watermark on top.

A consumer loop would have been enough for a different question. “What is the last click time for this user?” is a compare-and-set. You grew into windows because the question was “how many in this hour,” and the hour has edges, lateness, and revisions. Write down the question before you pick the framework. If the question has no “per hour” and no “joined to,” go back to the loop.

Tradeoffs

Choice What you gain What you spend
Consumer loop, set the row A small program, duplicates are harmless if the write is idempotent No windows, no joins, no snapshot of in-progress aggregates
Tumbling window on event time One bucket per click, totals you can rebuild A lateness policy, and late clicks to drop or revise
Tumbling window on processing time Easy to explain, matches “when we saw it” A replay moves the totals onto the day you replayed
Sliding window A smoother trailing total About length/step times the state if you store windows naively
Session window A boundary that matches idle time The end is a guess, quiet keys hold state, late clicks split sessions
Drop late events The published hour never changes A permanent downward bias equal to your lateness fraction
Revise the hour Late clicks can still count Every downstream reader must replace a value, not add to one
Wait longer to close Fewer late events Staler dashboards, more state in flight

The tradeoff interviewers can hear is drop versus revise. Dropping is simpler and silently wrong by a fraction you chose. Revising is honest and infects every consumer of the total. Pick it from whether the number is a bill or a picture. Do not pick it from the example config that shipped with the framework.

Pitfalls

  • Windowing on processing time and calling the job replayable. Symptom: Monday’s total changes because you ran the job on Wednesday. Move the window to event time, or stop promising rebuilds.
  • A watermark copied from a blog. Symptom: a subway morning shows up as a revenue drop, because the bound was five seconds and your devices are not. Measure lateness before you freeze the bound. Until then, say the bound is an assumption.
  • Closing the hour with an increment-only sink. Symptom: a late click either vanishes or is added twice when the revision retries. Store the hour’s value, keyed by the window, and replace it.
  • Sliding windows that multiply state by the overlap. Symptom: memory tracks 12 copies of the hot key and the operator restarts from an out-of-memory kill that looks like traffic. Store the events once over the longest window.
  • A session gap with no cap. Symptom: one abandoned client holds state until retention, and the checkpoint grows without a product reason. Cap the session, and make the cap a stated product rule.
  • A join with no bound on how late the other side can be. State grows for every unmatched click. Symptom: a memory leak that correlates with your best campaign, which is the one producing unmatched keys. Bound the join the same way you bound the watermark.
  • Forgetting that a stalled partition, if you take the min across partitions, stalls every window. Symptom: one consumer falls behind and the whole hourly job stops publishing. Lag on one partition is now a data-freshness incident for every key.
  • Running a per-record copy through a windowing engine “so we have one stack.” Symptom: an outage in the checkpoint manager stops a job a loop would have finished. Use the loop.

In the interview

Say the clock in the first minute of this topic. “I count by event time, tumbling hours, and I close the hour 10 minutes later as a policy I would measure. Late clicks after that are revisions if we bill from the total, and drops if it is a dashboard. I key by user so one user’s order holds. If the question is only last-click-per-user, I do not start this machinery. A consumer loop that writes the newer timestamp is enough.”

The number is the hour’s volume and the late fraction. Ten million a day is about 116 a second, about 417,000 an hour, and 1.5 percent late is about 6,250 clicks you are choosing to drop or to revise. The bottleneck is the hottest key’s state, not the average partition. The tradeoff is freshness against bias: wait longer, or publish a number you may have to replace.

Skip operator-API trivia and any checkpoint interval you cannot justify. Skip a claim that the framework gave you exactly-once end to end. The question that follows is “what if the click arrives 20 minutes late?” Answer with drop or revise, and say which downstream systems can tolerate a changed hour. If they ask what a restart does to the count, describe the barrier as a cut across state and offsets, and say the sink is inside that promise only if the sink write is in the cut or is idempotent.

Check yourself

A click has event time 10:55 and arrives at 11:08. Which tumbling hour owns it if you window on event time, and what did the watermark assume?

The 10 o’clock hour. Event time is 10:55, which falls in that hour, and the arrival at 11:08 is processing time. Under a policy that closes the hour 10 minutes after it ends, 11:08 is before the 11:10 close, so the click is on time. A policy that closes at 11:00 sharp would call the same click late. The hour is the event timestamp. The watermark is an assumption about how long you are willing to wait.

The same job windows on processing time. You replay Monday's log on Wednesday. What happens to Monday's total?

Monday’s clicks are observed on Wednesday, so they fall into Wednesday’s processing-time windows. Monday’s rebuilt total goes to zero and Wednesday gains a day. The log did not change. The clock you grouped by did. Event time keeps them on Monday, and you still need the same lateness rule as the live job or the rebuilt hour will not match the one you published.

When is a consumer loop enough, and what question forces you out of it?

A loop is enough when each record updates state you can set twice safely, with no window and no join. Last click per user is that case: write the event if its timestamp is newer. You leave the loop when the result is an aggregate over a time bucket, a join with another stream, or in-progress state that must snapshot with the offsets so a crash does not double-count. “Copy the event to a table” is still a loop.

Who is guessing when a watermark marks a click late, and what are the three things you can do about it?

You are. The watermark is a policy you chose, often wall-clock time or the latest event time you have seen, minus a bound. It cannot see a phone that has not reconnected. Once it has closed the hour you can drop the click and accept a low bias, wait longer so fewer clicks are late, or publish a revised total for that hour. A revision only works if readers replace the hour’s value.

A 60-minute window starts every 5 minutes. Why is the state not the same cost as one tumbling hour?

Away from the edges, each click falls in 60 / 5 = 12 windows. A store that copies the hour’s set into every window holds about 12 times the entries, mostly duplicates. One hot key still lands on one partition, so the multiplier hits that partition’s memory. Store each event once over the longest window, or expect the checkpoint to grow with the overlap.

Based on: Designing Data-Intensive Applications, Kleppmann and Riccomini; Jay Kreps, Neha Narkhede, and Jun Rao.