A billion click events meet ten million user profiles on ten machines. A sort-merge join sends all 101 GB across the network; a broadcast join sends 10 GB. Add a bot that makes 20% of the clicks, and one sort-merge reducer gets 2.6 times its share: 441 s against 113 s.
Pick a join plan and switch the bot on. Then we build each part from zero: Unix pipes, the shuffle, failures, joins, hot keys, dataflow engines, recomputation and the output.
You need a little Python and what a file and a hash are. We build the rest from zero.
Illustrative and seeded. We simulate 1,000,000 events over 10,000 users with Zipf popularity, and each simulated row stands for 1,000 real ones. Rows are 100 bytes. Each machine reads its disk at 200 MB/s, receives 125 MB/s from the network and handles 2 million rows a second. GB means 109 bytes.
Chapter 0
Time a scan of yesterday's logs on one machine, then on many
Your web servers wrote 10 TB of access logs yesterday. Someone wants the 100 most visited pages. The question takes one line of SQL. Reading the data is the hard part.
A batch job reads a large, fixed input, computes, and writes a new output. Nobody waits on it with a spinner. Its measure is throughput: how much data it gets through per hour. An online service answers one request in milliseconds; a batch job answers one question over all the data.
Each bar is the time to read the whole input once, at 500 MB/s per machine. Move the data size, then pick how many machines share the work.
Illustrative: 500 MB/s is one fast disk read in sequence. This assumes a perfect split; the rest of the lesson is about what splitting costs.
Call the data size D, one machine's read speed b, the number of machines n, and the scan time T.
T equals D, divided by n times b.
Split the D bytes evenly over n machines. Each reads D/n bytes at speed b. They work at the same time, so the job takes as long as one share.
With made-up numbers: D = 10 TB, b = 500 MB/s. One machine needs 1013 / (5 × 108) = 20,000 s, about 5.6 hours. A hundred machines need 200 s.
That split hides three problems. Records that belong together, such as every visit to one page, sit on different machines. The job must regroup them: the shuffle. Some machine will be slow or will die mid-job. And the output must appear whole, or not at all.
This lesson follows Chapter 11 of Designing Data-Intensive Applications, 2nd edition, by Martin Kleppmann and Chris Riccomini (O'Reilly, 2026). We explain its ideas in our own words, with our own examples and simulations. Its question: how do you turn a computation that works on one machine into one that works on a thousand, and survives their failures? Batch jobs build derived data from the system of record. Sharding covers partitioning in a database; here we partition a computation.
Failure. Symptom: a nightly job on one big machine runs 6 hours, crashes at hour 5, and the report is late again. Measure: job time against the window you have. Cause: one machine reads every byte, and a crash throws all progress away. Fix: split the input so many machines read in parallel, and rerun only the lost pieces (Chapter 3).
Chapter 1
Run the Unix pipeline on a small log, then sort more data than fits in memory
On one machine, the Unix shell already answers "top pages". Each program reads lines on standard input and writes lines on standard output, and the pipe | joins them. On our seeded 60-line log:
bashcat access.log | awk '{print $7}' | sort | uniq -c | sort -rn | head -3 # 22 /home # 13 /cart # 9 /search
awk keeps field 7, the page. sort puts equal pages next to each other. uniq -c counts each run of equal lines. That middle step is the whole trick: sort to group. MapReduce will do the same thing across many machines.
McIlroy, Pinson and Tague set the rules in their 1978 foreword to the Unix issue of the Bell System Technical Journal. Make each program do one thing well. Expect its output to become the input of another, as yet unknown, program.
What if the log is bigger than memory? sort then does an external merge sort. It fills memory, sorts that chunk, and writes it to disk as a sorted run. Then it merges runs, k at a time, until one remains. Merge Sort covers the merge itself.
The top row is the sorted runs on disk. Each row below is one merge pass. Shrink memory, then raise the fan-in, and watch the passes and the bytes moved.
A real external merge sort on 1,200 seeded integers in this page. It counts every record read from and written to disk, with the input file as the first read.
How much disk traffic does it cost? Name the parts. Let N be the number of records and M the records that fit in memory. Let r be the runs, k the fan-in, p the merge passes and IO the records moved.
IO equals two times N times one plus p. Here p is the ceiling of log base k of r. And r is the ceiling of N over M.
The first pass reads N records and writes r runs. Each merge pass reads and writes everything again and cuts the run count by k. Count the passes, p plus one, and charge 2N for each.
From the device: N = 1,200, M = 100, so r = 12. With k = 4, p = 2 (12, then 3, then 1), and IO = 2 × 1,200 × 3 = 7,200 records moved. With k = 12, p = 1 and IO = 4,800. The page's sort counted the same.
Failure. Symptom: sorting a 50 GB file takes ten times longer than reading it. Measure: the merge passes in the temporary directory. Cause: little memory and a small fan-in. Fix: give sort more memory (-S) and a fast temporary disk (-T).
Chapter 2
Step a real word count through three map tasks and three reducers, with and without a combiner
Dean and Ghemawat described MapReduce at Google in 2004. You write two functions. Map takes one input record and emits key-value pairs. Reduce takes one key and all its values and emits a result. The framework splits the input, runs the tasks in parallel and regroups the pairs by key.
The regrouping is the shuffle, the distributed version of sort | uniq -c. Each map task writes its output to local disk as one partition per reducer. Each reducer fetches its partition from every map task and sorts what it fetched by key, so all values for one key arrive together.
Three map tasks share twelve documents of 40 words. Press Step to map, shuffle and reduce. Then switch the combiner on and step again.
A real MapReduce in this page on seeded text: 480 words from a 20-word vocabulary with Zipf frequencies. Keys go to reducer fnv(key) mod 3.
Which reducer gets a key? Call the number of reduce tasks R and the reducer a key goes to j.
j equals hash of key, mod R.
Hash the key, divide by R, and keep the remainder. Every map task computes the same j for the same key, without talking to anyone. So all copies of a key meet at one reducer.
From the device: hash("the") = 3,020,861,980. Divided by 3, that leaves 1. hash("log") = 1,062,293,841 leaves 0. Every map task sends "the" to reducer 1.
Without a combiner, the three map tasks send 480 pairs, one per word. Reducer 1 receives 239 of them, because "the" (135 pairs) and "data" (45) both hash there. A combiner runs the reduce function on each map task's output before the shuffle. It sends 59 pairs, 88% fewer. That works only when reduce can merge partial results, as a sum can. An average cannot; send (sum, count) pairs instead.
The input lives in a distributed file system. Google's GFS split files into 64 MB chunks with three copies each; HDFS uses 128 MB blocks by default. The scheduler runs each map task on a machine that holds a copy of its block, so most input never crosses the network. Many clusters now read from an object store such as S3 instead. Reduce output goes back to the file system.
Failure. Symptom: the shuffle of a word count moves more bytes than the input. Measure: map output records against input records. Cause: one pair per word, and no combiner. Fix: add a combiner. In Spark, use reduceByKey, not groupByKey, as its guide advises for sums and averages.
Chapter 3
Slow one machine, kill another, and see what backup tasks and re-execution buy
A job ends when its last task ends. One slow machine, a straggler, can hold up a thousand fast ones. Dean and Ghemawat saw a disk with read errors drop from 30 MB/s to 1 MB/s. A bug that disabled processor caches slowed machines a hundredfold.
Their fix: when the job is close to done, start a backup copy of each task still running, on a free machine. Whichever copy finishes first wins, and the master stops the other. On their 1 TB sort, turning backups off made the job take 1,283 s instead of 891 s, 44% longer. Hadoop and Spark call it speculative execution; Spark's is off by default.
Each row is a machine; each bar a task. Pink is a machine waiting for the job to end. Switch the slow machine on, then backup tasks, then kill machine 7.
Illustrative and seeded: 40 map tasks of 8.5 to 11.5 s on 10 machines. When no task is left to start, a free machine copies the running task that will end last.
Why worry about one slow machine in a thousand? Call the chance that a task straggles p, the number of tasks m, and the chance that at least one straggles P.
P equals one minus, one minus p, to the m.
One task runs normally with chance one minus p. All m run normally with that chance multiplied m times. P is what is left: some task is slow.
With made-up numbers: p = 0.001, one task in a thousand. With m = 40, P = 3.9%. With m = 1,000, P = 1 − 0.9991000 = 63%. Big jobs almost always have a straggler.
In the device, the slow machine stretches the job from 43.1 s to 77.2 s. One backup copy brings it to 49.2 s. Kill machine 7 instead: its running task restarts, and so does a finished map task whose output lived on its disk. The job ends at 49.9 s. Finished reduce tasks never rerun; their output is already in the file system. In the paper, killing 200 of 1,746 workers made the sort 5% slower.
Re-execution works only if tasks are deterministic: the same input gives the same output. A map function that reads the clock can give a rerun output that differs from what a reducer already used.
Failure. Symptom: a job sits at 99% for an hour. Measure: the slowest task's time against the median. Cause: one bad machine, or one task with far more data (Chapter 5). Fix: speculative execution for the first; it cannot help the second.
Chapter 4
Grow the users table and see when shuffling both sides beats copying the small one
The hero's job: a billion click events, each with a user ID, and ten million user profiles, each with a country. Count clicks per country. Every click first needs its user's country: a join on user ID.
Sort-merge join (reduce-side join): map tasks read both tables and emit each row keyed by user ID. The shuffle brings a user's profile and all their clicks to one reducer. With a secondary sort, the profile arrives first, so the reducer holds one profile in memory and streams the clicks past it. It shuffles both tables.
Broadcast hash join: if the users table fits in memory, send a full copy to every map task. Each joins its own clicks against a hash table of users; the clicks never move. Spark does this on its own for tables under 10 MB by default (spark.sql.autoBroadcastJoinThreshold).
Partitioned hash join: an earlier job may have split both tables by the same hash of user ID, into the same number of parts. Then task j joins part j of each, and nothing moves.
Bars compare network bytes for the three plans; the dashed line is the memory a task has for a hash table. Grow the users table and watch broadcast hit the line.
Illustrative and seeded, the hero's engine without the bot: 1 billion events of 100 bytes, 10 machines, 4 GB of hash-table memory per task. "Partitioned" assumes an earlier job already split both tables the same way.
When does copying beat shuffling? Call the number of machines n, the users table's size |U| and the events table's size |E|.
n times size of U is less than size of E plus size of U.
Broadcast sends the users table n times. Sort-merge sends each table once. Compare the two totals. Then check that one copy of U fits in a task's memory, or broadcast is not an option at all.
With the device's numbers: |E| = 100 GB, |U| = 1 GB, n = 10. Broadcast moves 10 GB, sort-merge 101 GB. At 100 million users, |U| = 10 GB: broadcast moves 100 GB against 110 GB, but 10 GB does not fit in 4 GB of memory.
Grouping uses the same machinery. To build each user's sessions, shuffle by user ID and sort each user's events by time.
Failure. Symptom: a broadcast join that worked for months now dies with out-of-memory errors. Measure: the broadcast table's size, per run. Cause: the "small" table outgrew task memory. Fix: cap broadcast by size and fall back to sort-merge, as Spark's threshold does.
Chapter 5
Turn up a bot's share of the clicks, then split its key and watch the busiest reducer shrink
A sort-merge join sends all of one user's rows to one reducer. Most users click a few times. A bot, or a celebrity's account, can click millions of times. Its reducer gets far more than its share, and the job waits for it. This is skew, and the user is a hot key.
Bars are reducers; the dashed line is a fair share and red marks more than 1.5 times it. The purple part of a bar is the busiest user's rows. Raise the bot, then salt.
Illustrative and seeded, the hero's engine: sort-merge join on 10 reducers. Hot keys are users with at least 2% of a 1% sample of the clicks.
Sharding derives how a hot key loads its shard. Here we add the fix.
Salting splits a hot key. Each of its clicks gets a random suffix from 0 to k−1. The job copies its profile row k times, once per suffix. A sample of the input finds the hot keys first. Call the reducer count R, the hot key's share of rows p, the salt count k, and the busiest reducer's load over the mean S.
S-k equals R times p over k, plus one minus p.
The hot reducer gets one piece of the hot key, p/k of the rows, plus its 1/R share of the rest. The mean reducer gets 1/R. Divide, and you get R times p over k, plus one minus p, if the other keys spread evenly.
With the device's numbers: R = 10, p = 0.2. Without salt, k = 1: S = 2 + 0.8 = 2.8; the simulation measured 2.59. With k = 10: S = 0.2 + 0.8 = 1.0; the simulation measured 1.45, because the ordinary users are lumpy too (1.35 with no bot at all).
Salting costs little here: three hot users, nine extra copies each, 27 extra profile rows. In the hero, it cut the job from 441 s to 291 s. A broadcast join has no hot reducer at all, because map tasks split clicks by file position, not by user. Spark's adaptive execution splits a join partition on its own when it is over 5 times the median and over 256 MB.
Failure. Symptom: 199 reducers finish in 2 minutes and one runs for an hour. Measure: rows per key, from a sample of the input. Cause: one key has a large share of the rows. Fix: salt the hot keys, or broadcast the small side; a backup copy will not help.
Chapter 6
Run an iterative job as a chain of MapReduce jobs, then as one dataflow, and count the bytes written
Real work is rarely one MapReduce job. PageRank repeats one step: each page passes its rank to the pages it links to. Each writes its whole output to the file system, three copies, and the next reads it back. The link lists never change, but every job rewrites them.
A dataflow engine plans the whole computation as one graph of operators. Spark (Zaharia and colleagues, 2012) and Flink are the best known. Operators that need no regrouping, such as a map followed by a filter, run back to back on one machine with no file in between. Only a step that regroups by key, a wide dependency, needs a shuffle. Shuffle files go to local disk, once, not to the replicated file system.
Two rows of bars: the MapReduce chain and the dataflow engine. Purple is writes to the distributed file system, blue is shuffle.
Illustrative: links 100 GB, ranks 2 GB, rank contributions 20 GB per iteration. The dataflow engine splits the links once by page and caches them, so only contributions cross the network.
How much does the chain write? Call the replica count r, the number of jobs k, and job i's output size Oi.
W-MR equals r times the sum over i from one to k of O-i.
Every job in the chain stores its output r times, even when the next job reads it once and throws it away. A dataflow engine stores only the last output r times: r times O-k.
With made-up numbers: 10 PageRank iterations, each writing links and ranks, Oi = 102 GB, r = 3. WMR = 3 × 1,020 = 3,060 GB. The dataflow engine writes 3 × 2 = 6 GB to the file system, plus 300 GB of shuffle files on local disks.
The RDD paper reports Spark up to 20 times faster than Hadoop on iterative jobs. Not writing has a price: a dead machine's results are gone. Flink in batch mode keeps intermediate results on non-ephemeral storage between stages, so it can go back to the latest one after a failure. Chapter 7 is how Spark recovers instead.
Engines also took on declarative interfaces: SQL and DataFrames. Seeing the whole query, the engine picks the join plan from Chapter 4. It also reads only the needed columns of a columnar file.
Failure. Symptom: a 10-step pipeline spends most of its time writing files nobody reads twice. Measure: bytes written per step against the final output. Cause: each step is its own job. Fix: run the steps as one dataflow job.
Chapter 7
Kill a machine mid-job and see how much work lineage, a checkpoint and a restart each redo
Spark records each dataset's lineage: the input and the steps that made it. Spark does not restore a lost partition from a copy. It computes the partition again from its parents. Only the lost partitions are redone, and in parallel on different machines.
Wide dependencies make the chain longer. A partition after a shuffle needs pieces of every parent partition. Spark keeps shuffle files on local disk, so the survivors' pieces are still there. The dead machine's pieces are not, so its parents are redone too, back to the input. The RDD paper warns that one failed node can then need "a complete re-execution" of its ancestors. A checkpoint, a copy written to the file system, cuts the chain.
Columns are iterations, rows are machines. Machine 6 dies while the last column runs. Orange cells are work redone; purple columns are checkpoints. Add checkpoints, then try a restart.
Illustrative: 8 machines, one partition each, every iteration ends in a shuffle, 400 machine-seconds of work per iteration. "MapReduce chain" stores every iteration's output in the file system, as in Chapter 6.
How much work comes back? Call the iteration that was running t, the newest checkpoint before it c, the work per iteration w, and the number of machines n.
W-redo equals t minus c, times w over n.
The dead machine's slice, w/n, must be redone for every iteration since the checkpoint: t minus c of them. Survivors keep their results.
With made-up numbers: t = 10, w = 400, n = 8. No checkpoint: (10 − 0) × 50 = 500 machine-seconds. A checkpoint every 4 iterations, so c = 8: 2 × 50 = 100. Restarting the job would redo all 4,000.
The MapReduce chain redoes only 50, one slice of one iteration, because every iteration is already in the file system. It paid 3,060 GB of writes for that. Lineage pays nothing until a failure. Checkpoints sit in between.
Recomputation needs determinism again. If an operator reads the clock or a random seed, the recomputed partition can differ from the one later tasks already used.
Failure. Symptom: after one executor dies, a 50-iteration job takes twice as long as normal. Measure: the stage history; look for long chains of recomputed stages. Cause: no checkpoint, so the lost partitions are rebuilt from iteration 1. Fix: checkpoint every few iterations, or after any expensive shuffle.
Chapter 8
Publish a job's output three ways while a task fails and a backup copy runs, and see what readers get
What is a batch job for? It builds derived data: a search index, a table of recommendations, features for a model, a warehouse table. Google rebuilt its search indexing system on MapReduce. Often the output is a file of keys and values that a serving system loads in bulk.
The tempting design is wrong: let each reduce task insert its rows into the live database as it goes. Tasks fail and rerun. Backup copies run twice. Either way, some rows land twice. And readers see a half-finished result while the job runs.
Eight reduce tasks write 50,000 rows each. Task 3 dies at 60% and reruns; task 6 gets a backup copy. Pick how they write.
Illustrative: 8 tasks, 50,000 rows each. "Midpoint" is halfway through the job's writes.
The MapReduce paper's answer is files. Each reduce task writes a temporary file and renames it to the final name when it finishes. The file system makes the rename atomic, so a failed or duplicate task leaves no trace. When the whole job finishes, readers switch to the new output directory in one step.
This buys human fault tolerance. The inputs are never changed, so a job with a bug can be fixed and run again. If the new output is wrong, point readers back at yesterday's. You cannot roll back a database written row by row so simply.
Writing from a task to any outside system has the same trap. The paper leaves such side effects to the programmer, who must make them atomic and idempotent. Keyed upserts remove the duplicates. They do not stop readers seeing a mix of old and new rows.
Failure. Symptom: a nightly job doubles some customers' totals, but only on nights with a retry. Measure: rows per key against the job's own output count. Cause: tasks insert into the database, and a rerun inserts again. Fix: write output files, then swap the whole output at once; or bulk load a finished file.
Chapter 9
Turn every knob of the hero's join and find the plan that wins at each size and skew
Back to the hero, with every knob: the plan, the machines, the users table, the bot and how long-tailed ordinary users are. Each setting reruns the seeded join and the count by country.
The top shows the traffic; the middle, rows per reducer against a fair share; the bottom, network and time for all four plans. Try 20 machines, then 100 M users.
Illustrative and seeded, the hero's engine. "Popularity tail" is the Zipf exponent of ordinary users. Broadcast turns red when the users table is over 4 GB of task memory. "Partitioned" assumes both tables were already split by user.
At the hero's settings, broadcast takes 113 s, partitioned 131 s, salted 291 s and plain sort-merge 441 s. Partitioned moves nothing, but it still has the hot reducer, skew 2.59. With 20 machines, broadcast drops to 63 s, while plain sort-merge's skew climbs to 4.49. With 4 machines, broadcast takes 263 s.
Now set 100 million users. The table is 10 GB, over the 4 GB a task has, so broadcast is out. Remove the bot and set the tail to 1.2. The top ordinary user then has 21% of clicks. Sort-merge takes 488 s, salted 253 s. Skew comes from the data, not only from bots.
Failure. Symptom: a join planned for last year's data now runs three times longer. Measure: the size of each input and the share of the top keys, every run. Cause: the users table outgrew broadcast, or a new hot key appeared. Fix: let the engine choose the plan from current sizes, and keep skew handling switched on.
Chapter 10
Keep the numbers, the rules and the code for the next batch job you design
A batch job is a Unix pipeline spread over many machines. Map tasks read their own blocks, the shuffle groups by a hash of the key, and reduce tasks aggregate. Joins shuffle both sides, copy the small side, or use inputs already split alike. Hot keys overload one reducer until you split them.
Failed or slow tasks rerun because tasks are deterministic. Dataflow engines skip the writes between steps and recompute lost slices from lineage. The output appears all at once, as files.
| Idea | Rule | This lesson's number |
|---|---|---|
| Scan time | T = D / (n · b) | 10 TB at 500 MB/s: 20,000 s on 1 machine, 200 s on 100 |
| External sort | IO = 2N(1 + p) | 1,200 records, memory 100, k = 4: 7,200 moves |
| Partitioner | j = hash(key) mod R | "the" → reducer 1 of 3 |
| Combiner | reduce before the shuffle | 480 pairs → 59 |
| Stragglers | P = 1 − (1 − p)m | 1,000 tasks at 0.1%: 63%; backups 77.2 → 49.2 s |
| Broadcast or shuffle | n · |U| < |E| + |U|, and U fits | 10 GB against 101 GB |
| Hot key | Sk = R · p/k + (1 − p) | bot 20%: 2.59 → 1.45; 441 → 291 s |
| Chain writes | WMR = r · Σ Oi | 10 iterations: 3,060 GB against 6 GB |
| Recompute | Wredo = (t − c) · w/n | 500 machine-s; 100 with checkpoints; 4,000 to restart |
| Output | temp file, then atomic rename | inserts: 80,000 duplicates; files: 0 |
reduceByKey, whenever reduce can merge partial results.pythonfrom collections import defaultdict def fnv(s): # 32-bit FNV-1a, the page's partitioner h = 0x811c9dc5 for ch in s: h = ((h ^ ord(ch)) * 0x01000193) & 0xFFFFFFFF return h def map_reduce(splits, mapper, reducer, R, combine=False): parts = [defaultdict(list) for _ in range(R)] # what each reducer fetches sent = 0 for split in splits: # one map task per split out = defaultdict(list) for record in split: for k, v in mapper(record): out[k].append(v) for k, vs in out.items(): vs = [reducer(k, vs)] if combine else vs # the combiner parts[fnv(k) % R][k].extend(vs); sent += len(vs) result = {k: reducer(k, vs) for p in parts for k, vs in sorted(p.items())} return result, sent words = lambda doc: ((w, 1) for w in doc.split()) total = lambda k, vs: sum(vs) splits = [["the job reads the log"], ["the log is big"], ["sort the log"]] print(map_reduce(splits, words, total, R=2)[1], map_reduce(splits, words, total, R=2, combine=True)[1]) # 12 11 def join_plan(E, U, n, mem): # sizes in bytes if U <= mem and n * U < E + U: return 'broadcast', n * U return 'sort-merge', E + U print(join_plan(100e9, 1e9, 10, 4e9), join_plan(100e9, 10e9, 10, 4e9)) # ('broadcast', 10000000000.0) ('sort-merge', 110000000000.0)
Now press Present or Teach and explain four things from memory. Why does every map task send the same key to the same reducer? When does a broadcast join beat a sort-merge join? Why does a backup copy not fix a hot key? Why does a job publish files, not insert rows? Then go back to the hero and find the plan that finishes first with the bot switched on.