Stream and Batch Processing
Processing large datasets all at once (batch) or continuously as events arrive (stream), and the time and correctness problems each brings.
What is it?
Two ways to compute over large amounts of data:
- Batch processing takes a bounded input (yesterday's logs, a full table snapshot), runs a job over all of it, and produces output. It has high latency (minutes to hours) but is simple to reason about: if the job fails, rerun it on the same input. - Stream processing handles an unbounded input that never ends (clicks, payments, sensor readings) and produces results continuously, often within seconds.
Streams raise questions batch never had to answer. "Count clicks per minute" needs windows to cut an endless stream into finite chunks. Events arrive late and out of order (a phone was offline), so you must decide whether a "minute" means when the event happened (event time) or when you saw it (processing time), and how long to wait for stragglers (watermarks). And if a processor crashes mid-stream, you need to recover without double-counting (exactly-once state).
Architecturally, teams have combined the two (Lambda architecture) or used streaming for everything, with replay instead of batch (Kappa architecture).
Explain like I'm 10
Batch is counting all the votes after the polls close: slow, but you see every ballot. Streaming is a live tally on election night: fast, but some ballots arrive late by mail, so you announce provisional results and say 'we'll treat this district as complete once mail-in ballots stop arriving'. That cut-off is a watermark.
Examples
Word count as MapReduce
// map: called once per input record, emits (key, value) pairs
function map(line: string, emit: (word: string, count: number) => void): void {
for (const word of line.toLowerCase().split(/\W+/).filter(Boolean)) {
emit(word, 1);
}
}
// The framework shuffles: all pairs with the same key go to one reducer,
// grouped and sorted by key.
// reduce: called once per key with all its values
function reduce(word: string, counts: number[], emit: (word: string, total: number) => void): void {
emit(word, counts.reduce((sum, count) => sum + count, 0));
}
// "to be or not to be" → map emits (to,1)(be,1)(or,1)(not,1)(to,1)(be,1)
// shuffle → to:[1,1] be:[1,1] or:[1] not:[1]
// reduce → to:2 be:2 or:1 not:1Map and reduce are pure functions over partitions of data, so the framework can run thousands in parallel and simply rerun any that fail.
Event-time tumbling window with a watermark (Flink-style pseudo-code)
clicks
// Use the timestamp inside the event, not the arrival time. Allow events
// to arrive up to 30 s out of order before the watermark passes them.
.assignTimestampsAndWatermarks(
WatermarkStrategy.forBoundedOutOfOrderness(Duration.ofSeconds(30))
.withTimestampAssigner((click) => click.occurredAt),
)
.keyBy((click) => click.pageId)
.window(TumblingEventTimeWindows.of(Duration.ofMinutes(1)))
.allowedLateness(Duration.ofMinutes(5)) // update results for late events
.sideOutputLateData(tooLateClicksTag) // after that, divert, don't drop silently
.aggregate(countClicks);
// The [12:00, 12:01) window fires once the watermark passes 12:01,
// i.e. after seeing an event with occurredAt ≥ 12:01:30.The watermark trades latency for completeness: a bigger bound waits longer but misses fewer late events.
How it works
MapReduce (Google, 2004; open-sourced as Hadoop) runs batch jobs as:
1. Map: read input splits in parallel, emit key-value pairs. 2. Shuffle: partition pairs by key, sort them and send each key's values to one reducer. 3. Reduce: combine each key's values into output.
Fault tolerance comes from determinism: a failed task is just rerun on the same input. Intermediate results go to disk between stages, which made multi-step jobs slow. Spark generalised this into a DAG of operators with in-memory intermediate data, and is now the common batch engine.
Stream processing engines (Flink, Kafka Streams, Spark Structured Streaming, Google Dataflow / Apache Beam) run long-lived operators that consume a stream, keep state (counts, joins, aggregates) and emit results continuously.
Windowing turns an unbounded stream into finite groups: - Tumbling: fixed size, non-overlapping (every 1 minute). - Sliding / hopping: fixed size, overlapping, advancing by a smaller step (a 5-minute window every 1 minute), so each event belongs to several windows. - Session: per key, closed after a gap of inactivity (a user's visit ends after 30 minutes without clicks). Sizes vary.
Event time vs processing time. Event time is when something happened (a timestamp in the event); processing time is when the operator sees it. They diverge because of network delays, offline devices, backlogs and replays. Windows by processing time are simple but give different results when you replay data; event-time windows are reproducible but must cope with out-of-order events.
Watermarks. A watermark with time T is the system's assertion that "no more events with event time < T are expected". When the watermark passes a window's end, the window can fire. Watermarks are heuristic: too aggressive and late events are missed; too conservative and results are delayed. Late events can update already-emitted results within an allowed lateness, or be sent to a side output.
Lambda architecture (Nathan Marz) runs a batch layer that periodically recomputes accurate results from all raw data, a speed layer that streams approximate recent results, and a serving layer that merges them. Downside: the same logic is written and maintained twice in two systems.
Kappa architecture (Jay Kreps, 2014) keeps only the streaming path. The raw events live in a replayable log (e.g. Kafka with long retention). To fix a bug or change logic, start a new version of the job reading from the beginning of the log, let it catch up, then switch readers to its output.
Exactly-once in stream processors really means effectively-once effects on state and output: events may be processed more than once after a failure, but the results reflect each exactly once. - Flink takes periodic consistent snapshots of all operator state and source offsets using checkpoint barriers (asynchronous barrier snapshotting, inspired by Chandy-Lamport). On failure it restores the latest checkpoint and replays sources from the saved offsets. Sinks must be transactional (two-phase commit tied to checkpoints) or idempotent for the output to be exactly-once too. - Kafka Streams uses Kafka transactions to commit state-store changelog writes, output records and input offsets atomically.
Windows over one key's events (time →)
events: x x x x x x x x
tumbling: |----1----|----2----|----3----|----4----|----5----|
sliding: |------A------|
|------B------|
|------C------|
session: |--x--x----x--| gap |-x-x---x-| gap |-x---x-|
Event time vs processing time
processing time ─►
event time 12:00:05 12:00:20 11:59:58 12:00:40 12:01:31
(arrival order) ▲ late, out of order
watermark (max seen − 30s) reaches 12:01:01 → window [12:00,12:01) fires
Lambda vs Kappa
Lambda: raw data ─┬─► batch layer (recompute all) ─┐
└─► speed layer (recent, approx) ┴─► serving layer
Kappa: log (replayable) ─► stream job v1 ─► output
└─► stream job v2 (replays from 0) ─► switch overWhy does it exist?
Data volumes outgrew single machines, so computation had to be split across clusters with automatic retry. Batch frameworks made that practical for large, finite datasets. Businesses then wanted results in seconds (fraud detection, live dashboards, alerting, personalization), which batch can't deliver, so stream processors added stateful, fault-tolerant computation over unbounded data, with explicit models of time to keep results correct despite late and out-of-order events.
When to use it
- Batch: periodic reports, training data, backfills, large joins and reprocessing where hours of latency are acceptable and simplicity and cost matter. - Stream: fraud and anomaly detection, real-time metrics and dashboards, alerting, keeping materialized views and search indexes fresh, sessionization, enriching events in flight. - Kappa when your raw events are already in a replayable log and you can afford to replay for corrections; Lambda mostly in legacy systems or when batch recomputation is the only practical way to get exact results.
When not to use it
- Don't build a streaming pipeline when a nightly batch meets the requirement; streaming adds state management, watermark tuning and 24/7 operations. - Don't rely on processing-time windows when results must be reproducible or correct per real-world time (billing, compliance). - Avoid Lambda architecture for new systems unless necessary; keeping two codebases producing identical results is a known pain point. - For small data that fits on one machine, a single SQL query or script beats any cluster framework.
Common mistakes
Windowing by processing time and then being surprised that replays or backlogs produce different numbers than the original run.
Setting watermarks too tight and silently dropping late events, or too loose and delaying every result. Measure real lateness distributions and send late data to a side output.
Claiming end-to-end exactly-once while writing to a non-idempotent external sink (sending emails, calling APIs) from inside the stream job.
Letting state grow without bound (per-user state with no TTL, session windows with no expiry), eventually exhausting memory or checkpoint storage.
Ignoring data skew in batch jobs: one hot key makes a single reducer run for hours while the rest finish in minutes.
Practice exercises
- Easy:
Classify each as batch or stream and justify: monthly invoices, credit-card fraud detection, nightly ML training data, a live 'users online' counter.
- Medium:
Events: user A clicks at 10:00, 10:10, 10:50 and 11:05. Group them into tumbling 30-minute windows and into session windows with a 30-minute gap. Explain how the results differ.
- Hard:
Design a pipeline computing per-merchant revenue per minute from a Kafka payments topic, with exactly-once results written to a database. Cover event time, watermarks, late events, checkpointing and the sink, and explain what happens if a worker crashes mid-window.
Interview questions
What's the difference between batch and stream processing?
Batch processes a bounded dataset in one job and produces output when it finishes, with high latency. Stream processing handles an unbounded, continuously arriving dataset and emits results incrementally with low latency.
Explain the phases of MapReduce.
Map runs in parallel over input splits, emitting key-value pairs. Shuffle partitions, sorts and moves the pairs so each key's values reach one reducer. Reduce aggregates each key's values into output.
How does MapReduce tolerate failures?
Tasks are deterministic functions of their input, and inputs and intermediate outputs are stored durably, so the framework reruns failed tasks on another machine without affecting the result.
Tumbling vs sliding vs session windows?
Tumbling: fixed-size, non-overlapping. Sliding (hopping): fixed size, overlapping, advancing by a step, so an event can belong to several windows. Session: per key, bounded by gaps of inactivity, with variable length.
Event time vs processing time?
Event time is when the event actually occurred, carried in the event. Processing time is when the system processes it. Event-time results are correct and reproducible despite delays and replays; processing-time results are simpler but depend on when data happened to arrive.
What is a watermark?
A marker asserting that events with event time earlier than T are not expected anymore. It lets the system decide when an event-time window is complete enough to emit, trading latency against completeness.
How do you handle late events?
Allow a lateness period during which late events update already-emitted results (emitting corrections), and send events later than that to a side output or dead-letter store for reconciliation instead of dropping them silently.
Lambda vs Kappa architecture?
Lambda runs a batch layer for accurate recomputation and a speed layer for recent results, merged in a serving layer, which means maintaining logic twice. Kappa uses only a streaming pipeline over a replayable log and reprocesses by replaying the log into a new job version.
How does Flink achieve exactly-once state?
It periodically injects checkpoint barriers into the streams; each operator snapshots its state when barriers align, along with source offsets. On failure it restores the last complete checkpoint and replays from those offsets, so state reflects each event once.
Is exactly-once end-to-end possible when writing to an external database?
Yes, if the sink participates: either a transactional sink whose commits are tied to checkpoints (two-phase commit, pre-commit on checkpoint and commit when it completes), or an idempotent sink keyed by deterministic ids so replays overwrite rather than duplicate. Non-idempotent side effects like emails can't be made exactly-once by the processor.