Batch vs stream processing

Lesson 4.2 · 11 min read · by Vinay C

We'll cover the following

Visual summary

Infographic summarizing Batch vs stream processing: Your bank sends a monthly statement and also texts you the moment a card payment looks suspicious. Both use the same…

Download imageFree to share, please link back to this lesson.

The problem: when does the answer need to exist?

Your bank sends a monthly statement and also texts you the moment a card payment looks suspicious. Both use the same transactions. The difference is when the work runs. The statement waits until the month is over and processes everything at once. The fraud text must fire within seconds of one payment, so it processes each event as it arrives.

That is the whole topic. Batch processing works on a finished, fixed pile of data on a schedule. Stream processing works on events continuously, one at a time or in tiny groups, as they arrive. Pick by how stale the answer is allowed to be.

BatchStream
InputA bounded set: yesterday's files or table. It has an end.Unbounded events that keep arriving. It has no end.
RunsOn a schedule (hourly, nightly), then stops.Always on.
LatencyMinutes to hours.Seconds to milliseconds.
ExamplesNightly billing, daily reports, ML training.Fraud alerts, live dashboards, trending, monitoring.
ToolsSpark, MapReduce, SQL in a warehouse.Flink, Kafka Streams, Spark Structured Streaming.
Fixing a bugRe-run the job on the same input.Replay the log from an older offset (needs a replayable source such as Kafka).
Hard partScale and scheduling.State, time and out-of-order data.

How to choose

  • Ask: what does a wrong or late answer cost? A fraud check that runs tomorrow is useless, so stream. An invoice that runs at 2 a.m. is fine, so batch.
  • Default to batch when the answer can wait. It is simpler to build, test and fix: same input, same output, re-run if wrong.
  • Use stream only when freshness is the product. It costs you always-on servers, state management and late-data handling.
  • "Real time" is rarely needed. A dashboard refreshed every minute can be a small batch job (a micro-batch). Ask what the user would do differently with a 1-second answer instead of a 1-minute one.

Why streaming is harder: time

In batch, all the data is already there, so order does not matter. In a stream, events arrive late and out of order. Say a user taps "like" at 12:00:30 on a phone that then enters a tunnel. The event reaches your servers at 12:20. Two clocks now disagree:

  • Event time: when it actually happened (12:00:30, stamped on the phone).
  • Processing time: when your system saw it (12:20).

If you count by processing time, that like lands in the 12:20 minute, which is wrong. So aggregate by event time. The catch is that you can never be sure all events for 12:00 have arrived. That is what watermarks are for.

Windows: cutting an endless stream into pieces

You cannot "count all clicks" on a stream that never ends, so you count per window.

WindowShapeExample
TumblingFixed size, no overlap.Clicks per minute: 12:00-12:01, 12:01-12:02, ...
SlidingFixed size, overlapping, moves by a smaller step.Last 5 minutes, updated every minute (each event counts in 5 windows).
SessionCloses after a gap of inactivity.One user's visit: ends after 30 minutes with no clicks.

Watermarks: when is a window done?

Here is the puzzle. You are counting likes per minute. When can you announce "12:00 to 12:01 had 3 likes"? You cannot wait forever, because a slow phone might still send a 12:00 like later. You cannot announce at 12:01:00 either, because events are still in transit. You need a rule for "it is now safe enough to close the window". That rule is the watermark.

A watermark is a clock for event time, not for the wall. It says: "I believe every event with an event time up to W has already arrived." The system computes it from the data it has seen:

watermark = (newest event time seen so far) - (how late you allow events to be)

The allowed delay is your choice, say 2 minutes. Think of a bus driver: "I leave 2 minutes after the last passenger I expected." When the watermark passes the end of a window, that window closes and emits its result. Here is the same per-minute window, with a 2 minute allowed delay, as events arrive in this order:

window we watch: 12:00:00 - 12:01:00   (allowed delay: 2 min)

arrival  event time   newest seen   watermark   what happens
-------  -----------  ------------  ----------  --------------------------------
  1      12:00:10     12:00:10      11:58:10    goes in window 12:00, count = 1
  2      12:00:40     12:00:40      11:58:40    goes in window 12:00, count = 2
  3      12:01:30     12:01:30      11:59:30    goes in window 12:01 (next one)
  4      12:00:55     12:01:30      11:59:30    OUT OF ORDER but window 12:00 is
                                                still open, count = 3
  5      12:03:05     12:03:05      12:01:05    watermark 12:01:05 passed 12:01:00
                                                -> window 12:00 CLOSES, emits 3
  6      12:00:30     12:03:05      12:01:05    arrives 3 min late; window 12:00
                                                is closed -> this event is LATE
  • Rows 1 to 4: the watermark stays behind the window's end (12:01:00), so the window keeps accepting events, even out of order ones like row 4.
  • Row 5: a much newer event pushes the watermark past 12:01:00. The system now assumes nothing older is coming, so it closes the window and emits the count.
  • Row 6: that assumption was wrong for this one phone (it was in a tunnel). The event is late.

What to do with a late event

  • Drop it. Fine for a live dashboard where being a little off does not matter.
  • Send it to a side output. Keep late events in a separate stream so a batch job can fix the numbers later.
  • Allowed lateness. Keep the window's state a bit longer, say 5 more minutes. If row 6 arrives inside that time, the window updates its result to 4 and emits a correction. After that time, the state is deleted and the event is treated as dropped.

Choosing the allowed delay is a dial, not a fact:

Allowed delayResults arriveLate events
Small (seconds)FastMore of them are dropped or corrected
Large (minutes)Slow, windows stay open longer and use more memoryFewer, results are more complete

Rule of thumb: measure how late events really arrive (for example 99% within 1 minute), set the delay near that, and let a nightly batch job fix the rest if exactness matters.

State and exactly-once

  • State. Counts and joins need memory across events (e.g. the running count per hashtag). It lives inside the operator, often in RocksDB, and is checkpointed to durable storage. After a crash the job resumes from the last checkpoint instead of starting over.
  • Exactly-once results come from three pieces together: checkpoints, a replayable source (Kafka offsets), and an idempotent or transactional sink. This is the same "at-least-once plus idempotent" idea from Message queues and Kafka.

Lambda vs kappa: serving fast and exact answers

Sometimes you want both: a fast approximate number now and an exact number later. Two classic designs:

HowTrade-off
LambdaTwo paths: a batch layer (slow, exact) and a speed layer (fast, approximate). Queries merge both.Two codebases that must produce the same numbers. Heavy to maintain.
KappaOne streaming path. To fix a bug or change logic, replay the log (Kafka with long retention) through the new code.Simpler, but needs a replayable log and a stream engine you trust.

Many teams today pick kappa when they can, and keep a small nightly batch job only where exact corrections matter (billing, finance).

Example: trending hashtags

clicks / posts -> Kafka (partitioned by hashtag)
  -> Flink: 5-minute sliding window, count per hashtag, keep top 10
  -> Redis (the API reads the top 10 from here)

Same Kafka topic also lands in object storage (S3) -> nightly Spark job
recomputes exact numbers and corrects late data.

Why this shape: Kafka keys by hashtag so one worker owns each hashtag's count. Flink gives the fresh answer in seconds. Redis serves it fast. The nightly job is the safety net for late events.

Check yourselfA phone reconnects after a tunnel and sends events that are 20 minutes old, after your per-minute window has closed. What do you do?

Aggregate by event time with a watermark plus some allowed lateness (say 5 minutes). Events later than that go to a side output or are fixed by the nightly batch job. Choose by how exact the number must be: billing needs the correction, a live dashboard can ignore the stragglers.

Check yourselfProduct asks for "real-time" revenue numbers on an internal dashboard that managers check a few times a day. Batch or stream?

Batch, or micro-batch every few minutes. Nobody acts on a 1-second-old revenue figure, and a scheduled job is far cheaper to run and fix than an always-on stream with state and late-data handling.

Summary: say it in the interview

  • "Batch when the answer can wait and must be exact; stream when it must be fresh. Kafka as a replayable log lets me do both from one source."