Some questions are answered over all the data you have: yesterday's revenue by country, a recommendation model retrained on a year of clicks. Others must be answered as data arrives: fraud scores within 100 ms, a live count of viewers. Batch processing handles the first with engines like MapReduce and Spark; stream processing handles the second with Flink, Kafka Streams and friends. This lesson covers how both work, the hard parts of streaming (event time, windows, watermarks, state, exactly-once) and how architectures combine them. The simulation above runs a MapReduce word count so you can watch map, shuffle and reduce happen.
Think of it like
Counting votes
Batch is the official count: when polls close, ballot boxes from every district are collected, sorted by candidate in counting halls (shuffle) and tallied (reduce). It is slow but exact and can be redone from the paper ballots. Streaming is the live TV projection: results are updated as each district reports, some districts report late, and the network must decide when a district's number is final enough to call, knowing a straggling box could still arrive.
Batch vs stream
Batch processing
- Input is bounded: a known set of files or a table partition
- Runs periodically (hourly, nightly) and finishes
- Latency of minutes to hours; throughput is what matters
- Easy to reason about and to rerun: same input, same output
- ETL, reports, ML training, search index builds
Stream processing
- Input is unbounded: events keep arriving forever
- Runs continuously and never finishes
- Latency of milliseconds to seconds
- Must handle out-of-order and late events, and keep state safely
- Fraud detection, monitoring, live dashboards, real-time features
The line is blurrier than it looks: a batch job is a stream processor run over a bounded slice of a stream, and a stream is the never-ending log of events that batch jobs periodically snapshot. Modern engines (Spark, Flink, Beam) expose one API for both.
MapReduce
Google's 2004 MapReduce paper (Dean and Ghemawat) showed how to process petabytes on thousands of unreliable commodity machines by forcing every job into two pure functions. The framework handles distribution, scheduling and failures; the programmer only writes map and reduce. Hadoop brought it to everyone a couple of years later.
- 1
Split
The input (files in a distributed file system such as GFS or HDFS) is divided into splits, typically one per 64 to 128 MB block. Each split goes to one map task, ideally on a machine that already stores that block (data locality).
- 2
Map
map(key, value) → list of (k2, v2). For word count: for each word in the line, emit(word, 1). Map tasks run in parallel and know nothing about each other. - 3
Partition
Each emitted pair is assigned to one of R reducers by
hash(k2) mod R, so every occurrence of the same key goes to the same reducer. Map output is written to the mapper's local disk. - 4
Shuffle and sort
Each reducer fetches its partition from every mapper over the network and merge-sorts it by key, so all values for one key are adjacent. This all-to-all transfer is usually the most expensive phase.
- 5
Reduce
reduce(k2, list of v2) → output. For word count: sum the ones. Each reducer writes one output file (part-r-00000, ...) to the distributed file system.
split 1: "the cat sat" --map--> (the,1) (cat,1) (sat,1)
split 2: "the cat ran" --map--> (the,1) (cat,1) (ran,1)
shuffle: hash(key) mod 2 decides the reducer, then sort by key
reducer 0 receives: cat -> [1, 1] ran -> [1]
reducer 1 receives: sat -> [1] the -> [1, 1]
reduce: sum the values
part-r-00000: cat 2, ran 1
part-r-00001: sat 1, the 2Try it in the simulation above: run the job, step through the phases and watch how every occurrence of a word ends up at the same reducer. Edit the input to give one word many more occurrences than the rest and notice how much more work its reducer has to do.
- Combiner
- A mini-reduce run on each mapper's output before the shuffle. Turning a thousand
(the, 1)pairs into one(the, 1000)can cut network traffic dramatically. It is only valid when the operation is associative and commutative (sum, count, max), not for something like a median. - Straggler
- A task running much slower than its peers because of a bad disk or a busy machine. The job is only as fast as its slowest task, so the framework launches speculative backup copies of slow tasks and keeps whichever finishes first.
- Fault tolerance
- Map and reduce are deterministic functions of their input, so a failed task is simply rerun on another machine. Lost map output is recomputed from the input split.
- Data skew
- When one key is far more common than others (a celebrity user, the word "the"), its reducer becomes a hot spot. Mitigations: combiners, salting hot keys across several reducers, or a two-stage aggregation.
Spark: why it replaced MapReduce
Real pipelines are rarely one map and one reduce. Chained MapReduce jobs write every intermediate result to the replicated file system and read it back, which is brutal for iterative work like machine learning or graph algorithms. Apache Spark (from UC Berkeley's AMPLab) keeps intermediate data in memory where it can, and plans a whole multi-step job as one graph.
Hadoop MapReduce
- Fixed map then reduce; complex jobs are chains of separate jobs
- Materializes every intermediate result to replicated disk
- Verbose Java API
- Fault tolerance by re-running tasks from persisted data
Apache Spark
- Arbitrary DAG of operators (map, filter, join, groupBy...) in one job
- Pipelines narrow steps in memory; spills to disk only at shuffles or under memory pressure
- Concise APIs in Python, Scala, Java and SQL, plus ML, graph and streaming libraries
- Fault tolerance by lineage: recompute lost partitions from their parents
- RDD
- Resilient Distributed Dataset: an immutable, partitioned collection that remembers how it was derived (its lineage), so lost partitions can be rebuilt. Spark's original low-level API.
- DataFrame / Dataset
- A distributed table with a schema. Because Spark knows the columns and operations, its Catalyst optimizer can reorder filters, prune columns and pick join strategies, so DataFrame code usually beats hand-written RDD code.
- Transformation vs action
- Transformations (
filter,groupBy,join) are lazy: they only add nodes to the plan. Actions (count,show,write) trigger execution of the whole optimized plan. - Narrow vs wide dependency
- Narrow steps (map, filter) work partition by partition and are pipelined together. Wide steps (groupBy, join on unpartitioned data) need a shuffle, and the job is split into stages at those boundaries.
from pyspark.sql import SparkSession, functions as F
spark = SparkSession.builder.appName("top-pages").getOrCreate()
views = spark.read.parquet("s3://logs/pageviews/date=2026-11-04/")
top_pages = (
views.filter(F.col("status") == 200) # narrow: pipelined, no shuffle
.groupBy("page") # wide: shuffle boundary, new stage
.agg(F.count("*").alias("views"),
F.countDistinct("user_id").alias("users"))
.orderBy(F.desc("views"))
.limit(10)
)
top_pages.explain() # nothing has run yet: prints the optimized physical plan
top_pages.show() # action: Spark now schedules stages and tasks
# The same word count as MapReduce, with the RDD API.
# reduceByKey combines on the map side before shuffling, like a combiner.
counts = (spark.sparkContext.textFile("s3://corpus/books/*.txt")
.flatMap(lambda line: line.lower().split())
.map(lambda word: (word, 1))
.reduceByKey(lambda a, b: a + b))Stream processing
A stream processor reads events from a durable, replayable log (almost always Kafka or a similar system, see Message Queues & Pub/Sub), runs them through a graph of operators such as filter, keyBy, window and join, and writes results to databases, other topics or alerting systems. Apache Flink runs this graph as a long-lived cluster job, processing record by record; Kafka Streams is a library embedded in your own service that reads from and writes to Kafka; Spark Structured Streaming processes the stream as a series of small batches.
Event time vs processing time
| Event time | Processing time | |
|---|---|---|
| Meaning | When the event actually happened, stamped by the producer | When the operator happens to process it |
| Order | Events arrive out of order (mobile clients offline, retries, multiple partitions) | Always in order, by definition |
| Results | Deterministic: replaying the same data gives the same answer | Depend on load, lag and when you ran the job |
| Cost | Must wait for stragglers: needs watermarks and buffered state | Simple and lowest latency |
| Use for | Billing, analytics, anything that must be correct | Monitoring "what is the system doing right now" |
Windowing
An unbounded stream has no "end" at which to compute a total, so aggregations are computed over windows: finite slices of the stream, usually defined in event time and computed per key.
| Window | Definition | Each event belongs to | Example |
|---|---|---|---|
| Tumbling | Fixed size, no overlap: [12:00, 12:01), [12:01, 12:02)... | Exactly one window | Page views per minute |
| Sliding (hopping) | Fixed size, advancing by a smaller slide | size ÷ slide windows | Average latency over the last 5 minutes, updated every minute |
| Session | Per key, closed after a gap of inactivity | One session, which may merge with neighbors | A user's browsing session ends after 30 minutes idle |
| Global | One window per key for all time, with a custom trigger | The single window | Emit a running count every 1,000 events |
events: x x x x x
time: 0 1 2 3 4 5 6 7 8 9 10
tumbling 3: [0-3): 2 [3-6): 1 [6-9): 1 [9-12): 1
sliding 4 every 2: [0-4): 3 [2-6): 1 [4-8): 0 [6-10): 2 [8-12): 2
session gap 3: {0, 1, 3} then a gap of 5 minutes {8, 9}CREATE TABLE clicks (
user_id STRING,
page STRING,
ts TIMESTAMP(3),
WATERMARK FOR ts AS ts - INTERVAL '10' SECOND -- tolerate 10 s of disorder
) WITH (
'connector' = 'kafka',
'topic' = 'clicks',
'properties.bootstrap.servers' = 'kafka:9092',
'scan.startup.mode' = 'earliest-offset',
'format' = 'json'
);
SELECT window_start, window_end, page, COUNT(*) AS views
FROM TABLE(
TUMBLE(TABLE clicks, DESCRIPTOR(ts), INTERVAL '1' MINUTE))
GROUP BY window_start, window_end, page;Watermarks and late data
When can the window [12:00, 12:01) be closed? In event time you can never be certain that no more events for it will arrive. A watermark is the stream processor's declaration that event time has progressed to T: it does not expect any more events with timestamps earlier than T. When the watermark passes a window's end, the window fires.
Aggressive watermark (small delay)
- Results come out quickly
- More events arrive after their window fired (late data)
- Good for dashboards that tolerate small errors
Conservative watermark (large delay)
- Fewer late events, more complete results
- Higher latency and more buffered state
- Good for billing and anything audited
- Allowed lateness: keep a window's state for a while after it fires and emit an updated result when late events arrive. Downstream systems must accept upserts.
- Side outputs: route events that are too late to a separate stream for a correction job or for inspection, instead of silently dropping them.
- Idle partitions: a partition with no traffic holds the minimum watermark back and stalls every window. Mark idle sources so they stop blocking progress.
State, checkpoints and exactly-once
Windows, joins, deduplication and per-user features all need state that outlives individual events. Stream processors keep it partitioned by key, co-located with the computation (in memory or in an embedded RocksDB), and back it up regularly. Flink takes consistent snapshots of all operators' state plus source offsets using checkpoint barriers, a variant of the Chandy-Lamport distributed snapshot algorithm, without stopping the stream. Kafka Streams instead backs each state store with a compacted changelog topic.
| Guarantee | Meaning | How it is achieved |
|---|---|---|
| At most once | Events may be lost, never duplicated | Commit offsets before processing; no replay |
| At least once | Nothing lost, but effects may repeat after a failure | Replay from the last checkpoint; duplicates reach the output |
| Exactly once (effectively once) | Every event affects state and output exactly once | Replayable source + checkpointed state and offsets + transactional or idempotent sink |
import java.time.Duration;
import java.util.Properties;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.*;
import org.apache.kafka.streams.kstream.*;
public class PageViewsPerMinute {
public static void main(String[] args) {
Properties props = new Properties();
props.put(StreamsConfig.APPLICATION_ID_CONFIG, "page-views-per-minute");
props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "kafka:9092");
props.put(StreamsConfig.PROCESSING_GUARANTEE_CONFIG, StreamsConfig.EXACTLY_ONCE_V2);
StreamsBuilder builder = new StreamsBuilder();
builder.stream("clicks", Consumed.with(Serdes.String(), Serdes.String())) // key = page
.groupByKey()
.windowedBy(TimeWindows.ofSizeAndGrace(Duration.ofMinutes(1), Duration.ofSeconds(30)))
.count() // state store backed by a changelog topic
.toStream()
.map((windowed, count) -> KeyValue.pair(
windowed.key() + "@" + windowed.window().startTime(), count))
.to("page-views-per-minute", Produced.with(Serdes.String(), Serdes.Long()));
KafkaStreams streams = new KafkaStreams(builder.build(), props);
Runtime.getRuntime().addShutdownHook(new Thread(streams::close));
streams.start();
}
}Lambda vs Kappa architectures
Early streaming engines were fast but approximate and could not be trusted to be correct after failures. The Lambda architecture (Nathan Marz) ran two pipelines side by side: an accurate batch layer and a fast speed layer. Once stream processors gained exactly-once state and replayable logs, Jay Kreps proposed the Kappa architecture in 2014: keep only the streaming path and reprocess by replaying the log.
| Lambda | Kappa | |
|---|---|---|
| Pipelines | Batch and streaming, merged at query time | Streaming only |
| Code | Business logic written twice | Written once |
| Reprocessing | Rerun the batch job | Replay the log into a new version of the job |
| Best when | Huge historical recomputation, or a streaming engine you cannot trust for correctness | The log can hold (or tier) enough history and the engine has exactly-once state |
Many modern stacks land in between: streams for fresh results, plus batch jobs over a lakehouse (Parquet files with a table format such as Iceberg or Delta Lake on Blob & Object Storage) for heavy backfills and ML training, sharing logic through a unified API like Spark, Flink or Apache Beam.
Choosing an engine
| Engine | Model | Typical latency | Strengths |
|---|---|---|---|
| Hadoop MapReduce | Batch, disk between every step | Minutes to hours | Historical: mostly replaced by Spark |
| Apache Spark | Batch; streaming as micro-batches | Seconds (streaming) to hours | SQL, DataFrames, ML; the default for large batch ETL |
| Apache Flink | True streaming, record at a time; batch as a bounded stream | Milliseconds to seconds | Event time, large state, exactly-once, low latency |
| Kafka Streams | Library inside your service | Milliseconds | No cluster to operate; Kafka in, Kafka out |
| Apache Beam / Google Dataflow | Unified batch and stream API with pluggable runners | Depends on runner | Portable pipelines; fully managed on Dataflow |
Implementation
Map with a per-mapper combiner, partition by hash, shuffle and sort, then reduce: the same phases a cluster runs, minus the network. The partitioner uses a stable hash so that every mapper sends a given word to the same reducer.
import zlib
from collections import Counter, defaultdict
def map_phase(split: str) -> Counter:
# Map emits (word, 1); the Counter acts as a combiner, pre-summing locally.
return Counter(split.lower().split())
def partition(word: str, reducers: int) -> int:
return zlib.crc32(word.encode()) % reducers # stable across processes
def shuffle(map_outputs: list[Counter], reducers: int) -> list[dict[str, list[int]]]:
parts: list[dict[str, list[int]]] = [defaultdict(list) for _ in range(reducers)]
for output in map_outputs:
for word, count in output.items():
parts[partition(word, reducers)][word].append(count)
# Each reducer sees its keys in sorted order, like a merge sort of map files.
return [dict(sorted(p.items())) for p in parts]
def reduce_phase(groups: dict[str, list[int]]) -> dict[str, int]:
return {word: sum(counts) for word, counts in groups.items()}
def word_count(splits: list[str], reducers: int = 2) -> list[dict[str, int]]:
map_outputs = [map_phase(s) for s in splits] # parallel in a real cluster
return [reduce_phase(g) for g in shuffle(map_outputs, reducers)]
print(word_count(["the cat sat", "the cat ran", "the end"]))Key takeaways
- Batch processes bounded data for throughput and simple correctness; streaming processes unbounded data for low latency and must handle disorder and state.
- MapReduce is map, partition by key hash, shuffle and sort, reduce; combiners cut shuffle traffic and deterministic tasks make failures cheap to retry.
- Spark won by planning whole jobs as lazy DAGs, keeping intermediate data in memory and recovering through lineage, with an optimizer behind its DataFrame API.
- Use event time for correct results; windows (tumbling, sliding, session) bound aggregations, and watermarks decide when a window is complete enough to emit.
- Exactly-once means exactly-once effects: replayable sources, consistent checkpoints of state and offsets, and transactional or idempotent sinks.
- Lambda runs batch and speed layers in parallel; Kappa keeps one streaming pipeline and reprocesses by replaying the log.
Common pitfalls
- Windowing by processing time and getting wrong numbers whenever consumers lag or replay.
- Using a combiner for operations that are not associative and commutative, such as averages computed as averages of averages.
- Ignoring data skew, so one hot key makes a single reducer or task run for hours.
- Claiming exactly-once while writing to a sink that is neither transactional nor idempotent.
- Letting state grow forever: unbounded keys or windows without TTLs and lateness limits eventually exhaust memory or disk.
Interview tips
- Start by asking how fresh results must be; it decides batch, micro-batch or true streaming.
- Explain watermarks and late data concretely with a timestamped example, and say what you do with events that arrive after a window fires.
- Describe how the pipeline recovers from a crash: checkpoints, replay from offsets, and how the sink avoids duplicates.
Real-world applications
- Nightly ETL into a data warehouse or lakehouse with Spark, orchestrated by tools such as Airflow.
- Real-time fraud detection and risk scoring on payment events with Flink.
- Live metrics, trending topics and leaderboards computed with windowed aggregations over Kafka.
- Search index builds and ML feature pipelines that combine batch backfills with streaming updates.
Test yourself
In MapReduce, what guarantees that all values for the same key reach the same reducer?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.