AlgoViz

Stream processing

medium 30 min

Stream processing handles events one after another as they arrive, without waiting for the data to end.

Video lesson · Chapter 1 of 5

Count a live crowd through a moving gate

0:00 / 4:36

Stream processing in 80 seconds

1:20Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

Stream processing treats data as a flow of events that has no end. A program reads each event soon after it happens, updates something it remembers, and sends results on. It does not stop when it has finished, because it never has.

An event is a small record of something that happened: a click, a payment, a temperature reading. It carries the time when it happened. Because events travel over networks, that time can differ from the time the program sees it.

In plain words: data comes in like a river, not in buckets. You handle each drop as it passes, and the answer is ready in milliseconds to minutes instead of the next morning.

Why it exists

Some answers lose their value quickly. A payment that looks like fraud must be stopped before it completes. A machine that overheats must be switched off now, not in tomorrow's report.

Other work is simply smoother when it is spread over the day. A job that handles each event once does not need to read a whole day of data again at night. The price is that a program running for months must cope with late data, growing memory and crashes.

A short history

  1. 1985

    Chandy and Lamport publish a way to take a consistent snapshot of a running distributed system. Flink's documentation names it as the basis of its checkpoints.

  2. 2003

    The Aurora paper in the VLDB Journal describes a database system built for monitoring data streams instead of stored tables.

  3. 2013

    Google publishes MillWheel, a framework for low-latency processing, at VLDB. The Discretized Streams paper, on running a stream as many small batches, appears at SOSP.

  4. January 2015

    Apache Flink is announced as a top-level project of the Apache Software Foundation.

  5. 2015

    Google's Dataflow Model paper gives the questions many systems use: what to compute, where in event time, when to show results, and how to correct them.

  6. 2017

    Kafka 0.11 adds transactions, so reading from a topic, computing and writing to another topic can be done exactly once inside Kafka.

Words to know

Unbounded data
Data with no known end.
Event time
When the event happened, written inside the event.
Processing time
What the clock of the machine says when it handles the event.
Window
A finite piece of the stream that can be counted or added up.
Watermark
The job's estimate of how far event time has come: older events are not expected any more.
State
What the job remembers between events, such as a count per user.
Checkpoint
A saved copy of the state together with the position in the input.
Backpressure
A slow step making the steps before it slow down too.
Sink
Where results go: a database, a topic, an alert.

How it works

Step through the idea, or press Play.

Step 1 of 3

Events flow into a log. The log keeps them, so they can be read again

Understand it

Start here

Boats under the bridge

Noor stands on a bridge over a brook. Children upstream launch paper boats and write the minute of the launch on each one. Noor must say how many boats were launched in each minute.

How many boats each minute?
Boats by minute9:0039:009:009:00

Counting is easy. Deciding when a minute is complete is the hard part of stream processing.

The idea

What a streaming system looks like

Source, log, processor, sinks

Users send click events into our system. They are appended to a Kafka log. A Flink stream processor with windows and state reads them, writes counts to a database and to a live dashboard, and saves snapshots of state and offsets to object storage.
The log in the middle lets the processor stop, crash and read again. The snapshot store is easy to forget and matters most.
PartJobExamples
SourceProduces eventsSensors, clicks, application logs, database changes
LogKeeps events in order and lets them be read againKafka, Pulsar: see log-based queues
ProcessorFilters, joins, counts, remembersFlink, Kafka Streams, Spark Structured Streaming
SinkReceives resultsDatabase, dashboard, alert, another topic
  • Low latency

    Results in milliseconds to minutes, depending on the window and the wait for late events.

  • Unbounded data

    There is no last event, so you can never say: read everything, then sort.

  • Continuous

    The job runs day and night. A deployment is a pause and a restart from a snapshot.

  • Scalable

    Events are split by key over many parallel tasks.

  • Fault tolerant

    State is saved and the input can be read again.

  • Event time

    Results depend on when things happened, not on when the network delivered them.

The loop that never ends

Ingest, window, aggregate, emit, all day and all night.

Time

Two clocks

Event time

  • When the event happened
  • Written in the event: 10:00:00
  • The same after a replay
  • Needs a way to handle late events

Processing time

  • When the machine handles it: 10:00:05
  • Nothing to wait for, so the fastest
  • Changes when the job is slow or replays
  • Fine for health checks of the job itself

The gap between the two clocks is seconds on a good day and hours when a phone was in a tunnel or a job was down. A report by processing time would show a false dip during the outage and a false peak after it.

Out of order is normal

The log keeps the order of arrival. Event time is a different order.

Time

Watermarks: when is a window complete?

A watermark with time t says: the job believes that event time has reached t, and no more events at or before t are expected. Flink defines it in these terms. A common rule is to take the newest event time seen and subtract a fixed bound.

Bounded out-of-orderness

W=max⁡(event time)−B10:00:11−5 s=10:00:06W = \max(\text{event time}) - B \qquad 10{:}00{:}11 - 5\text{ s} = 10{:}00{:}06
B is how late you expect events to be. Windows that end at or before W can close.

What to do with an event after its window closed

ChoiceResultWhen
Drop itSimple, slightly low countsMetrics that tolerate gaps. Flink does this unless you change it: allowed lateness is 0 by default
Allow latenessThe window stays a while and sends a corrected resultThe sink can overwrite an earlier answer
Side outputLate events go to a separate streamYou must not lose them: count them later or inspect them
RecomputeRun the affected hours again from the log or filesMoney and legal reports

Windows

Tumbling, hopping, session

WindowSizeOverlapUse
TumblingFixed, for example 5 s: 0 to 5, 5 to 10, 10 to 15No: each event is in one windowFive-minute counts, hourly reports
Hopping (Flink says sliding)Fixed, for example 10 s every 5 s: 0 to 10, 5 to 15Yes: an event is in severalRolling averages, trends
SessionGrows with activity, ends after a quiet gapNo, per keyOne visit of one user

Which window?

The price of overlap

windows per event=sizehop10 min1 min=10\text{windows per event} = \frac{\text{size}}{\text{hop}} \qquad \frac{10\text{ min}}{1\text{ min}} = 10
At a peak of 3,000 events a second that is 30,000 updates a second. Adding up ten tumbling one-minute counts when you read is often cheaper.

State

State per key

Counting, joining and finding patterns need memory. The stream is split by a key, such as the user, so that one task sees all events of a key and can keep their state locally without locks.

Same key, same task

One job with three parallel tasks. Partition 0 feeds a task holding users A and D, partition 1 a task holding users B and E, partition 2 a task holding users C and F. All three write counts to one results database.
Run counts per user: user A has 5 clicks, user B has 12. Each number lives in one task only.

How much state?

106 keys×10 open windows×100 bytes=1 GB10^6 \text{ keys} \times 10 \text{ open windows} \times 100 \text{ bytes} = 1 \text{ GB}
Assumed numbers. This is what every snapshot must copy, or copy the changes of, so limit it with an expiry.

Healthy state

  • A key is deleted after a time without events
  • A window is deleted after it closes
  • Counts and sketches instead of raw events
  • Keys spread evenly

Trouble

  • One entry per user, for ever
  • A join that waits for a partner without a limit
  • All events of a window kept in a list
  • One key with half of the events

Guarantees

At most once, at least once, exactly once

GuaranteeMeaningGoodCostUse
At most once0 or 1 timeFastest, nothing to repeatEvents can be lostMetrics that tolerate gaps
At least once1 or more timesNo lossDuplicatesIdempotent work
Exactly onceThe effect counts 1 timeAccurateSnapshots, transactions, some latencyMoney, billing
See idempotency for making a repeat harmless.

How it works

  1. 1

    Checkpoint

    The job regularly saves its state and its positions in the log to durable storage, as one consistent snapshot. Markers called barriers flow with the events, so the job does not have to stop.

  2. 2

    Safe sink

    Results are either committed in a transaction when the checkpoint completes, or written with a key so that a repeat overwrites the same row.

  3. 3

    Recovery

    After a failure the job loads the last snapshot and reads the log again from the saved positions.

Crash and recovery

Two events are processed twice. Their effect is counted once.

Operations

Backpressure, lag and bad events

When a sink is slow, its inputs fill up, and the slowness travels upstream to the source. Flink's documentation describes exactly this direction. Because the source is a log, the events wait there, and the lag grows instead of events being lost.

Time to catch up

T=lagcapacity−arrivals=360,0002,000−1,000=360 sT = \frac{\text{lag}}{\text{capacity} - \text{arrivals}} = \frac{360{,}000}{2{,}000 - 1{,}000} = 360\text{ s}
Ten minutes at 600 events a second too slow leave 360,000 behind. Without spare capacity a job never catches up.

Do

  • Use event time for results
  • Plan for late events
  • Turn on checkpoints
  • Make operations idempotent
  • Monitor backpressure and lag

Do not

  • Keep unbounded state without cleanup
  • Ignore watermarks and order
  • Use processing time for totals
  • Let one poison event stop the job
  • Assume the sink is exactly once by itself

Numbers

A first estimate

100 million clicks a day, 200 bytes each (assumed)

QuestionArithmeticAnswer
Average rate100,000,000 / 100,000about 1,000 a second
Peak3 x 1,0003,000 a second
Data a day100,000,000 x 200 bytes20 GB
Log for 7 days, 3 copies20 GB x 7 x 3420 GB
Catch up after 1 hour down at peak10,800,000 / (9,000 - 3,000)1,800 s if the job can do 9,000 a second

When to use it

How fresh must the answer be?

Typical targets, as a design assumption

UseTargetConsequence
Trading decisionsUnder a millisecond or a fewUsually special software, not a general stream processor
Fraud check inside a paymentUnder 100 msState must be local, no window to wait for
Live analyticsUnder 1 s to a few secondsEarly results, corrected later
Monitoring and alertsUnder 5 sShort windows
Loading a warehouseUnder 1 min or a fewSmall batches are enough
Ask which decision depends on the answer. Nobody needs one second for a report read at breakfast.

Where it is used

  • Real-time analytics

    Live dashboards, click streams, business numbers, engagement.

  • Fraud detection

    Watching payments, finding patterns and unusual behaviour, scoring risk.

  • Sensors and monitoring

    Device data, infrastructure, maintenance before something breaks, alerts.

  • Event-driven services

    Orders, stock, notifications and keeping copies of data in step.

Compare the two ways of working in batch or stream. If one system must give both a quick and an exact answer, see Lambda architecture and Kappa architecture.

Summary

The whole topic in one minute.

Stream processing answers questions about data that never ends. Events are read from a log, assigned to windows by the time they happened, combined into state per key, and sent on when the watermark says a window is probably complete.

Correct results after a crash need three things together: a log that can be read again, a snapshot that holds state and position as one, and a sink that can take the same result twice. Start with the question of how fresh the answer must be. If hours are fine, a batch job is simpler.

  • A stream has no end, so windows cut it into pieces.
  • Use event time for results. Watermarks estimate when a window is complete.
  • Decide what happens to events that come after that.
  • State is kept per key and must be limited.
  • Replayable log, snapshot of state and offset, safe sink: together they give exactly-once effects.
  • Lag and spare capacity decide how fast you recover.

Sources