Distributed systems · L2Stream processing

Stream processing

Count, sum and join events as they arrive. Learn event time, windows, watermarks and checkpoints, and what "exactly-once" really promises.

L2 SeniorDistributed systems20 min read
Fact-checked by AI against cited sources · Human review pendingLast reviewed 8 Nov 2026 · How we check content
Section 1 of 8

What broke

A made-up story to show a common failure. Not about a real company.

A ride app shows a live chart: rides started per minute, per city. A small job reads ride events from Kafka and counts them. Each count goes into the minute when the job reads the event.

One evening the job is down for 10 minutes during a deploy. Kafka keeps the events, so nothing is lost. When the job comes back, it reads the 10-minute backlog in about 30 seconds.

The chart shows 10 empty minutes, then one minute with about ten times the normal rides. A pricing rule watches that chart. It sees "demand spike" and raises prices across the city.

There was no spike. The rides happened at a normal rate. The job counted them by when it read them, not by when they happened. The team switches to the time inside each event. Then phones that were offline in a tunnel send their events 3 minutes late, and the team learns about late data.

Section 2 of 8

The idea in simple words

A stream processor is a program that runs forever. It reads an endless flow of events, keeps some memory between them, and sends out results. Apache Flink, Kafka Streams and Spark Structured Streaming are the common tools.

Every event has two times. Event time is when it happened on the device. Processing time is when your machine sees it. 1 The gap between them changes all the time. Network delays, backlogs and offline phones can make it minutes, hours or days. 10

You cannot sum an endless stream, so you cut it into windows, like "each minute". 1 If you group by processing time, events land in the wrong window whenever the gap changes. 10 That is the ride chart bug.

Grouping by event time is correct, but raises a new question. When is the 12:00 minute finished? A late event could still arrive. A watermark is the engine's answer: a marker that says "event time has now reached t". 1

The key idea. Group by when things happened, not when you saw them. A watermark decides when a window is done. Some events will still come late, so decide on purpose what to do with them.

Section 3 of 8

How it works

Step through one window. Use Next and Back, or the ← and → keys.

Events arrive out of order: a watermark closes a one-minute window, a late event updates it, a very late one goes to a side outputCount rides per minute, by event time wm = newest − 5 s · lateness 30 s · side output on 12:00 12:01 12:01:30 abwma 12:00:10, b 12:00:40 · wm 12:00:35 · count 2 cc 12:00:20 is out of order, but wm < 12:01 · count 3 dwmd 12:01:08 → wm 12:01:03 → emit 3 ee 12:00:50 is late, within 30 s → emit 4 fwmf 12:01:40 → wm 12:01:35 → window state deleted gg 12:00:55 is too late → side output, not counted SeniorPath
  1. The box is the window for 12:00 to 12:01, by event time. Rides a and b arrive. The watermark (wm) is the newest event time minus 5 seconds: 12:00:35. The count so far is 2.
  2. Ride c happened at 12:00:20 but arrives after b. It is behind the watermark, but its window has not ended, so c still counts. The count is 3. Nothing is sent yet.
  3. Ride d, at 12:01:08, moves the watermark to 12:01:03. That is past the end of the window. The window fires and sends a count of 3.
  4. Ride e happened at 12:00:50 but arrives now. The watermark is past the window's end. With 30 seconds of allowed lateness, the window still accepts it and fires again: 4.
  5. Ride f moves the watermark to 12:01:35. That is past 12:01 plus 30 seconds. The engine deletes the window's state for good.
  6. Ride g, at 12:00:55, arrives even later. Its window is gone. We turned on a side output, so it goes there, where you can log it or fix the count later. Without one, Flink drops it.
Step 1 of 6

Windows

A tumbling window has a fixed size and never overlaps. Each event belongs to exactly one, like "12:00 to 12:01". A sliding window has a size and a slide. A 10-minute window that slides every 5 minutes overlaps, so one event can count in two windows. A session window closes after a gap with no events, for example 30 minutes without a click. 3

Watermarks and late data

A common rule is "newest event time seen, minus a fixed delay". Flink's built-in bounded out-of-orderness strategy follows this rule. 2 With a 5-second delay, a window ending at 12:01 fires soon after an event from 12:01:05 or later arrives.

An operator with many inputs uses the smallest watermark of them. 1 So one quiet Kafka partition can hold back the whole job. Flink's withIdleness setting marks such an input as idle so the rest can move on. 2

Pick the delay with care. A watermark that is too slow makes every result wait. One that is too fast closes windows early and turns normal events into late ones. 11

An event is late when it arrives after the watermark has passed its time. 1 For windows, what matters is the end of the window. Flink drops an event only if the watermark has already passed the end of its window plus the allowed lateness. The allowed lateness is 0 by default. 3 If you set it, an event that arrives within that time still joins its window, and the window can fire again with a new result. Flink keeps the window's state until the lateness runs out. After that, you can route even later events to a side output instead of losing them silently. 3

Kafka Streams calls the same idea a grace period. A record that arrives after it is discarded for that window. 12 Spark uses a watermark to know how late data can be, and to clean up old state. 13

Keyed state and where it lives

A count per city must be remembered between events. Flink keeps this keyed state next to the operator, split by key, so each update is local. 4 Kafka Streams also keeps local state stores, with automatic recovery. 12

Flink's default state backend keeps state as Java objects on the heap. It is fast, but limited by memory. The RocksDB backend keeps state on local disk, so it suits long windows and very large state. Each access must be serialized, and the docs call it "an order of magnitude slower" on average. RocksDB also supports incremental checkpoints. 5

Checkpoints: barriers in the stream

If a machine dies, the counts in memory are gone. So Flink takes regular snapshots, called checkpoints. The design is "inspired by" the Chandy-Lamport algorithm for distributed snapshots. 4 The 2015 paper behind it describes how, for a dataflow with no cycles, the snapshot needs only operator state, not the messages in flight. 9

It works like this. 4

  1. The sources insert a checkpoint barrier into the stream and note their position, such as a Kafka offset.
  2. Barriers never overtake records. Everything before barrier n belongs to checkpoint n.
  3. An operator with two inputs waits until barrier n has come from both. This is called alignment. Then it passes the barrier on and saves its state.
  4. When every sink has received barrier n and told the coordinator, checkpoint n is complete.

On a failure, Flink restores all state from the last complete checkpoint. It rewinds the sources to the saved offsets and reads again. 4 Note that checkpointing is off until you turn it on. 7

A savepoint is a checkpoint you trigger by hand. It does not expire when newer checkpoints finish. 4 You use it to stop a job, deploy new code, or change parallelism, then resume. Give each operator a stable ID with uid(), or the new version may not find its old state. 6

What "exactly-once" means here

Flink's exactly-once is about state. After a restore, records processed since the checkpoint have not touched the saved state. 4 But those records are processed again. A call to an outside API inside your code can run twice.

End-to-end exactly-once needs two more things. The source must rewind to the checkpoint position. The sink must take part, by committing writes in a transaction or by writing idempotently. 7 Spark says the same: replayable sources plus idempotent sinks. 13 Kafka Streams with exactly_once_v2 covers reading from Kafka and writing results back to Kafka topics. 12

Uber's ad pipeline shows the cost. Flink writes results to Kafka in transactions that commit only at the next checkpoint, every 2 minutes. Readers use read_committed, so they see results only after the next checkpoint, which can be about 2 minutes later. Uber says the checkpoint interval is the main delay, so the pipeline is "not exactly 'real-time'". Uber also gives each record a unique ID, so its databases can upsert or deduplicate. 14

Backpressure

When a sink is slow, buffers fill and the slowness spreads back to the source. Barriers travel with the data, so they wait in the same queues. 4 Checkpoints then take much longer. 8 Flink offers two fixes. Buffer debloating keeps less data in flight. Unaligned checkpoints let barriers pass buffered data, but save that data in the checkpoint, which adds I/O. 8

Section 4 of 8

Trade-offs

OptionState across events?Event-time windows?Good for
Plain consumer + databaseNo Each event is handled alone.No You write it yourself.Copying, enriching or upserting each event. Simple to run.
Kafka StreamsYes Local state stores.Yes , with a grace period.Kafka in, Kafka out, with exactly-once inside Kafka.
Apache FlinkYes Heap or RocksDB, with checkpoints.Yes , with watermarks, lateness and side outputs.Large state and complex time logic. More moving parts to run.
Spark Structured StreamingYes Yes , with watermarks.Teams already on Spark. Results come in small batches, for example every second. 13
Nightly batch jobn/an/aReports where a day of delay is fine. Easiest to fix and rerun.

Simple rule: if each event can be handled alone, a consumer plus an idempotent write is enough. Reach for a stream processor when you need windows, joins over time, or large state per key.

Section 5 of 8

At work: how a senior uses this

  • Ask first: "Which time are we grouping by?" Business questions almost always mean event time.
  • Write down the watermark delay and the allowed lateness, and why. Then measure how late events really are.
  • Never drop late events silently. Send them to a side output with a counter and an alert.
  • Watch for a stuck watermark. One idle partition can stop every window from firing.
  • Turn checkpointing on, store checkpoints in durable storage, and set uid() on every stateful operator before the first deploy.
  • For every sink, ask: "What happens when the last 2 minutes are replayed?" Use a transactional or idempotent sink.
  • Choose the checkpoint interval as a latency budget, since transactional sinks only commit at checkpoints.
  • Use RocksDB when state may outgrow memory. Size the local disks for it.
Section 6 of 8

With AI

What to ask the agent

"Here is our Flink job. List every operator that uses processing time. For each, tell me if the business question needs event time instead."

"Add a bounded out-of-orderness watermark of 10 seconds, idleness detection of 1 minute, allowed lateness of 2 minutes, and a side output for late events with a metric."

"Write a test that feeds events out of order into this windowed count, including one late and one very late event. Assert each window's output."

"Review this sink. If the job restarts from the last checkpoint, could any row be written twice? Show me how to make it idempotent."

What to check yourself

  • The timestamp comes from a field in the event, not from System.currentTimeMillis().
  • Late data goes somewhere you can see. The default drops it.
  • Side effects inside operators, such as HTTP calls, are safe to repeat.
  • Every stateful operator has a stable uid(), so a savepoint restore works after a code change.
  • The test really sends events out of order. A test with sorted input proves nothing about watermarks.
  • The agent did not "fix" late data by making the watermark delay huge. That only delays every result.
Section 7 of 8

Check yourself

1. A job counts orders per minute using processing time. It was down for 10 minutes and then catches up in 30 seconds. What does the chart show?

Show answer

A gap of 10 minutes, then one minute with about 10 minutes of orders in it. Processing-time windows use the clock of the machine. All the old events are read in one minute, so they are all counted in that minute.

2. In Flink, what does a watermark with time 12:01:00 tell an operator?

Show answer

That event time has reached 12:01:00, so no more events at or before that time are expected. A watermark is a promise about event time, not about the clock. It can be wrong, which is why late events exist.

3. Your Flink job has exactly-once checkpointing on. It calls a payment API inside a map function. The job fails and restarts. What can happen?

Show answer

Some payments are sent twice, because records after the last checkpoint are processed again. Flink restores state and replays input from the last checkpoint. Its state ends up as if each event counted once, but outside calls repeat.

4. What is the main reason to choose the RocksDB state backend over the heap backend?

Show answer

Your state is too large for memory, for example long windows or many keys. RocksDB keeps state on local disk, so it can hold much more. Each access must be serialized, so it is slower than the heap.

5. You need a Kafka consumer that writes each order to Postgres, keyed by order ID. There are no windows or joins. What do you use?

Show answer

A plain consumer with idempotent upserts. A stream processor adds little here. There is no state across events and no time logic. An upsert by order ID is already safe to repeat.

Your progress is saved only in this browser. Export it to keep it safe.

Was this clear?
Report a mistake (opens GitHub in a new tab)
Section 8 of 8

Go deeper

Show 14 sources and related lessons
  1. Paris Carbone, Gyula Fóra, Stephan Ewen, Seif Haridi and Kostas Tzoumas, “Lightweight Asynchronous Snapshots for Distributed Dataflows” (2015) (opens in a new tab)
    The paper behind Flink's checkpoints (Asynchronous Barrier Snapshotting).
  2. Tyler Akidau, “Streaming 101: The world beyond batch”, O'Reilly Radar (2015) (opens in a new tab)
    Event time vs processing time, the skew between them, and fixed, sliding and session windows.
  3. Tyler Akidau, “Streaming 102: The world beyond batch”, O'Reilly Radar (2016) (opens in a new tab)
    Perfect vs heuristic watermarks, watermarks that are too slow or too fast, triggers and allowed lateness.
  4. Apache Kafka documentation (4.3): Kafka Streams Core Concepts (opens in a new tab)
    Local state stores, the grace period for out-of-order records, and exactly_once_v2.
  5. Apache Spark documentation (4.3): Structured Streaming, Getting Started (opens in a new tab)
    The trigger interval, watermarks for late data, and end-to-end exactly-once with replayable sources and idempotent sinks.
  6. Uber Engineering, “Real-Time Exactly-Once Ad Event Processing with Apache Flink, Kafka, and Pinot” (2021) (opens in a new tab)
    A real pipeline with one-minute tumbling windows, Kafka transactions, a 2-minute checkpoint interval and record IDs for upserts.

Case studies: LinkedIn: The log: the simple idea under databases and streams

Related: Queues vs logs and delivery guarantees · Sagas, outbox and CDC · Time, clocks and ordering · Idempotency, retries and timeouts · Backpressure and flow control

Before this: Queues vs logs. Related: Time, clocks and ordering, Idempotency, retries and timeouts, Sagas, the outbox pattern and CDC, Exactly-once and effectively-once, and LinkedIn's case on the log. Coming later: counting and top-k at scale, fraud and risk systems, and ML platforms with feature stores.

Term

See full entry

Jump to a section

  1. 1What broke
  2. 2The idea in simple words
  3. 3How it works
  4. 4Trade-offs
  5. 5At work
  6. 6With AI
  7. 7Check yourself
  8. 8Go deeper