AlgoViz

Batch or stream processing

easy 26 min

Batch processing collects a finite set of data and handles it all at once.

Video lesson · Chapter 1 of 5

One ledger, two clocks

0:00 / 4:00

Batch or stream in 75 seconds

1:15Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

There are two ways to work through data. Batch processing waits until a piece is complete, such as one day of payments, and then runs over all of it. The job starts, finishes and reports. Stream processing starts with the first event and keeps going. It updates its answer with every event or every few seconds.

The first works on bounded data: the job can see where it ends. The second works on unbounded data: there is always more to come. Nearly every other difference follows from this one.

Why it exists

Handling many records together is cheap, because fixed costs such as opening files, starting tasks and committing are shared. Having all the records also makes the answer complete. That is why batch has been the normal way for a long time.

But a batch answer is old when it arrives. Where a decision depends on the last minute, such as stopping a stolen card, the value is gone by morning. Streaming buys freshness and pays with complexity.

A short history

  1. 2004

    Google publishes MapReduce at OSDI: batch jobs over very large files on many ordinary machines.

  2. 2013

    The Discretized Streams paper at SOSP shows how to run a stream as a series of small batch jobs, the idea behind Spark Streaming. In the same year Google publishes MillWheel, which works record by record.

  3. 2015

    Google's Dataflow Model paper describes one model for bounded and unbounded data. Apache Beam, an open source unified model for batch and streaming, follows this line.

  4. 2018

    Spark 2.3 adds an experimental mode that processes records continuously beside its small batches.

Words to know

Bounded
With a known end, such as the files of one day.
Unbounded
Without an end, such as a topic of events.
Latency
How long until the answer is there.
Throughput
How much is handled per second.
Staleness
How old the data behind an answer is.
Micro-batch
A very small batch, run again and again.
Backfill
Running a job again over old data.
Schedule
The plan of when a batch job starts.

How it works

Step through the idea, or press Play.

Step 1 of 3

Batch. Collect, process, one result

Understand it

Start here

Laundry day and the cup

At Sam's home, shirts and cups are both washed, but not in the same way.

Wait for the load, or rinse it now
MON

Nobody washes one shirt at a time, and nobody waits a week for a clean cup.

The idea

Wait, or go now

Batch

Batch processing alone

Collect all day, run once

Payments are written all day into files, one folder per day. At two in the morning a Spark job reads yesterday's folder, stops when it is done, and replaces that day in a reports database.
The job exists for an hour. In between, no machine of it has to run.

Good at

  • High throughput: terabytes in one run
  • Simpler to write and debug
  • Complete data, so accurate answers
  • Easy to run again over old data
  • Cheap for large sets

Weak at

  • Answers come hours or days later
  • Data is old by then
  • Cannot react to one event
  • Uses many machines for a short time
  • A failure late in a long run costs hours

Typical schedules and tools

WhenJobTools
Daily at 02:00Load and transform into a warehouseSpark, or SQL in the warehouse
Every hourTotals per hourSpark, Trino
WeeklyTraining a modelSpark, Python jobs
MonthlyFinancial reportsSQL, Hive
How such jobs work inside: MapReduce and dataflow engines. Where results are asked: OLAP.

A batch run

How old can a batch answer be?

stalenessmax=interval+run time=24 h+1 h=25 h\text{staleness}_{max} = \text{interval} + \text{run time} = 24\text{ h} + 1\text{ h} = 25\text{ h}
Just before the next report appears, the newest data in the current one is 25 hours old. Running hourly with a 5-minute job gives 65 minutes.

Stream

Stream processing alone

Always running

Each payment is appended to a Kafka log as a new event. A Flink job that is always running and keeps state reads it as it comes and updates live numbers in five-second windows.
The job never ends, so upgrades, crashes and growing state are normal work. Details: stream processing.

Good at

  • Answers in milliseconds to minutes
  • Reacting to one event
  • Running continuously
  • Finding unusual behaviour at once
  • Work spread over the day

Hard

  • More difficult to write and test
  • Events arrive out of order
  • State has to be managed
  • Exactly-once results need care
  • Somebody has to run it day and night

Tools and how they work

ToolHow
Apache FlinkHandles records one by one, keeps state. Can also run bounded jobs in a batch mode
Apache KafkaKeeps the events. Kafka Streams is a library that processes them
Spark Structured StreamingSmall batches by default, as low as 100 milliseconds end to end in its guide
Apache StormAn earlier record-by-record system

The same payment on two roads

Thirteen hours between the two answers, about the same payment.

Cost

Latency against throughput

Each write, file or task has a fixed cost. Sharing it over many records makes each record cheap, but the first record has to wait for the last one.

Records per second

bc+b⋅wb=1:;12.01 ms≈498/sb=1,000:;1,00012 ms≈83,300/s\frac{b}{c + b \cdot w} \qquad b = 1:; \frac{1}{2.01\text{ ms}} \approx 498/\text{s} \qquad b = 1{,}000:; \frac{1{,}000}{12\text{ ms}} \approx 83{,}300/\text{s}
Assumed: a commit c of 2 ms and work w of 0.01 ms per record. b is how many records share one commit.

Compare

Side by side

AspectBatchStream
DataBoundedUnbounded
LatencyMinutes to daysMilliseconds to minutes
RunsOn a scheduleContinuously
Throughput per machineVery highHigh, with some overhead per event
ComplexityLowerHigher
StateComputed in the run, then goneKept and updated for months
Late dataIncluded if it arrives before the runWatermarks, corrections
RepairRun again over the filesReplay the log, if it is still there
MachinesMany for a short timeFew all the time

In between

Micro-batches and hybrids

Between the two ends there is a wide middle. A batch every five minutes is enough for many dashboards. It keeps batch's simple model and cuts the waiting.

StyleAnswer afterEffort
Nightly batchup to a dayLowest
Hourly batchabout an hourLow
Micro-batchseconds to minutesMedium
Record by recordmilliseconds to secondsHighest

If you need both a quick and an exact answer, there are two well-known shapes. Lambda architecture runs a batch path and a stream path side by side. Kappa architecture keeps only the stream and replays the log. Apache Beam and Flink also let one program run over bounded and unbounded data.

Repair

Running it again

A bug was found

Keep raw data whichever way you choose.

Decide

Which one?

Three questions

Batch when

  • You analyse history
  • Accuracy needs all the data
  • Volume matters more than speed
  • Results can wait hours
  • You train models
  • You load a warehouse

Stream when

  • Insight is needed now
  • Something must react
  • You monitor continuously
  • Fraud and unusual events
  • Live dashboards
  • Services react to events

Both in one company: an online shop, as an example

PartBatchStream
RecommendationsTrain the model at nightUse the last clicks
DeliveryDrivers' monthly payArrival time on the map
PaymentsReports for sellersFraud check
SearchWeekly quality reportStock changes in the index

Practice

Good habits

  • Start from the decision

    Choose by the latency somebody really needs.

  • Plan the repair

    Know how you would recompute before you launch.

  • Measure both

    Throughput and latency. One often hides the other.

  • Do not force real time

    If batch is enough, streaming only adds late events, backpressure and night shifts.

Summary

The whole topic in one minute.

Batch collects, then processes everything once: complete, simple to repeat, cheap per record, and late. Stream processes as events arrive: early, steady, and harder to run because of late data, state and replays.

Choose by the decision that depends on the answer. If nobody acts for hours, use batch. If minutes are fine, use smaller batches. If seconds matter, stream, and keep the raw data so that a batch job can produce the exact number.

  • Bounded data: batch. Unbounded data: stream.
  • Large groups share fixed costs, and the first record waits.
  • A batch answer can be as old as the interval plus the run time.
  • Streaming adds state, late events and replays.
  • Smaller batches solve many freshness problems.
  • Keep raw data, and make every job safe to repeat.

Sources