Batch Processing
Designing Data-Intensive Applications · Chapter 10 · Recall lab
Part III of the book is about systems that derive data: take what is in one or more systems of record and turn it into caches, indexes, recommendations and analytics. This chapter starts with the oldest way of doing that. Not a request and a response, not an event the moment it happens, but a large pile of input, a job that chews through it, and output at the end.
Services, batch jobs and streams
Services: online
Wait for a request, handle it as quickly as possible, send a response. Response time is the measure, and availability matters, because a human is usually waiting.
Batch processing: offline
Take a large, bounded input, run a job over it, produce output. Jobs take minutes to days and nobody waits on them; they are scheduled. Throughput is the measure.
Stream processing: near-real-time
Like batch, it consumes inputs and produces outputs rather than answering requests, but it operates on events shortly after they happen, on input that never ends. That is chapter 11.
Batch processing is old: punch-card tabulating machines, such as the Hollerith machines of the 1890 US census, computed aggregate statistics over large inputs. MapReduce, published by Google in 2004 and reimplemented as Hadoop, made it the way to process data at scale for a decade, and its ideas outlived it. To understand it, the chapter starts somewhere much smaller.
This chapter builds on Dean and Ghemawat’s MapReduce paper. The MapReduce lab runs that paper in depth: a job through all seven steps of its Figure 1, the combiner, backup tasks against stragglers. This chapter takes the model as given and asks what you do with it.
Five tools and a pipe
Say you run a website and want the five most popular pages. The web server appends a line to an access log for every request. One line of shell answers the question: read the log, pull out the URL, sort, count, sort by count, take the top five. Here it is on 14 log lines, one stage at a time, with each stage’s output computed by doing what the tool does.
cat | awk | sort | uniq -c | sort -r -n | head
216.58.223.198 - - [27/Feb/2015:17:55:11 +0000] "GET /js/main.js HTTP/1.1" 200 8917 "-" "Mozilla/5.0" 216.58.216.172 - - [27/Feb/2015:17:55:18 +0000] "GET /favicon.ico HTTP/1.1" 200 3580 "-" "Mozilla/5.0" 216.58.233.131 - - [27/Feb/2015:17:55:25 +0000] "GET /js/main.js HTTP/1.1" 200 8485 "-" "Mozilla/5.0" 216.58.226.2 - - [27/Feb/2015:17:55:32 +0000] "GET /img/logo.png HTTP/1.1" 200 8896 "-" "Mozilla/5.0" 216.58.215.234 - - [27/Feb/2015:17:55:39 +0000] "GET /css/typography.css HTTP/1.1" 200 7924 "-" "Mozilla/5.0" 216.58.221.178 - - [27/Feb/2015:17:55:46 +0000] "GET /index.html HTTP/1.1" 200 2388 "-" "Mozilla/5.0" 216.58.218.180 - - [27/Feb/2015:17:55:53 +0000] "GET /css/typography.css HTTP/1.1" 200 1012 "-" "Mozilla/5.0" 216.58.200.119 - - [27/Feb/2015:17:56:00 +0000] "GET /css/typography.css HTTP/1.1" 200 8767 "-" "Mozilla/5.0" 216.58.230.170 - - [27/Feb/2015:17:56:07 +0000] "GET /index.html HTTP/1.1" 200 8076 "-" "Mozilla/5.0" 216.58.229.145 - - [27/Feb/2015:17:56:14 +0000] "GET /js/main.js HTTP/1.1" 200 1638 "-" "Mozilla/5.0" 216.58.218.132 - - [27/Feb/2015:17:56:21 +0000] "GET /about.html HTTP/1.1" 200 8546 "-" "Mozilla/5.0" 216.58.220.115 - - [27/Feb/2015:17:56:28 +0000] "GET /index.html HTTP/1.1" 200 5470 "-" "Mozilla/5.0" 216.58.228.194 - - [27/Feb/2015:17:56:35 +0000] "GET /css/typography.css HTTP/1.1" 200 8698 "-" "Mozilla/5.0" 216.58.233.93 - - [27/Feb/2015:17:56:42 +0000] "GET /favicon.ico HTTP/1.1" 200 7200 "-" "Mozilla/5.0"
/js/main.js /favicon.ico /js/main.js /img/logo.png /css/typography.css /index.html /css/typography.css /css/typography.css /index.html /js/main.js /about.html /index.html /css/typography.css /favicon.ico
/about.html /css/typography.css /css/typography.css /css/typography.css /css/typography.css /favicon.ico /favicon.ico /img/logo.png /index.html /index.html /index.html /js/main.js /js/main.js /js/main.js
1 /about.html
4 /css/typography.css
2 /favicon.ico
1 /img/logo.png
3 /index.html
3 /js/main.js 4 /css/typography.css
3 /js/main.js
3 /index.html
2 /favicon.ico
1 /img/logo.png
1 /about.html 4 /css/typography.css
3 /js/main.js
3 /index.html
2 /favicon.ico
1 /img/logo.pngcat /var/log/nginx/access.logRead the log file. Each line is one request in nginx’s default format: client IP, timestamp, request line, status, size, referrer and user agent. 14 lines here; a real site has millions.
awk '{print $7}'Split each line on whitespace and print only the seventh field, which is the requested URL. awk’s default field splitting is the whole parser.
sortSort the URLs alphabetically, so every occurrence of a URL sits next to the others. The 14 lines are the same, only reordered.
uniq -cCollapse each run of identical adjacent lines into one, with a count in front. This only works because the input is sorted: uniq compares neighbours only. 6 distinct URLs remain.
sort -r -nSort again, numerically by the count, largest first. Where counts tie, GNU sort falls back to comparing whole lines, and -r reverses that too.
head -n 5Keep the first five lines: the five most requested URLs, /css/typography.css and /js/main.js at the top. The whole analysis is one line of shell.
The same job could be a short program that keeps a hash table from URL to count. Which is better
depends on the working set: how much must be in memory at once. If the distinct URLs fit, a
hash table is fine; with 1 GB of memory and about 100 bytes
per entry, that is about 10 million URLs. Beyond that, sorting wins: GNU
sort spills sorted runs to disk and merges them, and spreads the work over CPU cores. The pipeline
scales to datasets far larger than memory without changing a character, limited by how fast the disk
can read.
The Unix philosophy
Doug McIlroy, 1978: make each program do one thing well; expect the output of every program to become the input of another, as yet unknown; design software to be tried early; and use tools rather than unskilled help to lighten a programming task. Automation, rapid prototyping, incremental iteration, experiments: it reads like Agile and DevOps, decades earlier.
A uniform interface
Programs can be plugged together because they share one interface: a file, an ordered sequence
of bytes. By convention it is ASCII text, one record per line, fields separated by whitespace, and
tools as different as awk, sort and uniq all understand it. Programs with their own data
models cannot be composed this easily.
Separating logic from wiring
A program reads standard input and writes standard output; it does not know or care where they lead. The shell connects them. That loose coupling lets each tool stay small, and lets you rearrange them without touching their code. It stops being easy when a program needs several inputs or outputs.
Transparency and experimentation
Inputs are treated as immutable: run a pipeline as often as you like, nothing is damaged. Pipe
any stage into less to see what it produces. Write a stage’s output to a file and restart from
there. Unix tools are great for this, and their one big limit is that they run on a single
machine. That is where Hadoop comes in.
A Unix process spread across a cluster
A MapReduce job is like a Unix process: it takes one or more inputs and produces one or more outputs, and it does not modify its input. Its files live in a distributed filesystem, HDFS, Hadoop’s open source version of the Google File System. HDFS is shared-nothing: a daemon on each machine serves its own disks, a central NameNode tracks which blocks are where, and every block is replicated on several machines, or protected by erasure coding such as Reed–Solomon codes, to survive machine and disk failures. The largest deployments run on tens of thousands of machines, holding hundreds of petabytes.
A job runs in the same four steps as the Unix pipeline above, and only two of them are code you
write. The input files are broken into records; your mapper extracts a key and value from
each, as awk '{print $7}' did; the framework sorts all pairs by key, as sort did; your
reducer iterates over each key’s values, as uniq -c did. Mappers run one task per input block,
on a machine that holds a replica when possible, to put the computation near the data. The author
chooses the number of reducers, and each key goes to reducer hash(key) mod R. Each map task sorts
its output partitions and writes them to local disk; each reducer fetches its partition from every
mapper and merges them: the shuffle.
Workflows
One job can only do so much, so jobs are chained: one job’s output directory is the next one’s input. A recommendation system can be 50 to 100 MapReduce jobs. A job starts only when the previous one has completed successfully, and schedulers such as Oozie, Azkaban, Luigi, Airflow and Pinball manage those dependencies.
Higher-level tools
Writing raw MapReduce is laborious, so layers appeared on top: Pig, Hive, Cascading, Crunch and Google’s FlumeJava set up workflows of jobs automatically from a description of the stages. They come back at the end of the chapter, running on engines other than MapReduce.
A join with no indexes
A database answers a join that touches a few records by looking them up in an index. MapReduce has no indexes: a job reads the entire content of its input files, like a full table scan. That is wasteful for one user and exactly right for analytics, which joins everything with everything. The book’s example is a log of what users did on a website, joined with the user database to find which pages are popular with which age group.
A reduce-side sort-merge join, figures 10-2 and 10-3
User database
1041989-01-121731978-09-302151995-04-02Activity events
215/sign-up104/home173/cart104/search?q=boots215/home104/product/77173/checkoutTo reducer 0
1041989-01-121731978-09-30104/home173/cart104/search?q=boots104/product/77173/checkoutTo reducer 1
2151995-04-02215/sign-up215/homeReducer 0, sorted
1041989-01-12104/home104/search?q=boots104/product/771731978-09-30173/cart173/checkoutReducer 1, sorted
2151995-04-02215/sign-up215/homeReducer 0 output
/home by a user born 1989-01-12/search?q=boots by a user born 1989-01-12/product/77 by a user born 1989-01-12/cart by a user born 1978-09-30/checkout by a user born 1978-09-30Reducer 1 output
/sign-up by a user born 1995-04-02/home by a user born 1995-04-02A log of what logged-in users did, and the user database. The question needs both: which pages are popular with which age group. Looking up each event’s user over the network would be slow and would hammer the database, so the batch job joins a copy of the user table, extracted into the distributed filesystem, with the log.
One mapper reads the events and emits (user ID, event); another reads the users and emits (user ID, date of birth). Every record is sent to reducer hash(user ID) mod 2, so a user’s record and all of that user’s events arrive at the same reducer, wherever they came from.
Each reducer sorts by user ID, and a secondary sort puts the user record ahead of that user’s events. Now every user’s records are adjacent, user first.
The reducer reads the user record, keeps the date of birth in a local variable, then streams that user’s events, emitting each one with the date attached. It never holds more than one user’s record in memory and makes no network requests. 7 joined rows, one per event.
The pattern generalizes. The mapper’s choice of key is like an address: every record with the same
key is delivered to the same reducer, and MapReduce separates the network communication from the
application logic completely. The same machinery runs a GROUP BY: key by the grouping column and
the reducer sees each group whole, whether it is counting, summing, taking the top k, or collecting
all of one user’s activity into a session to see what they did and in what order.
Skew: when one key is huge
Bringing a key’s records together breaks down when one key has far more than the rest: a celebrity with millions of followers. Such hot keys, or linchpin objects, land on one reducer, and the whole job waits for it. Pig’s skewed join samples to find hot keys and spreads their records over several reducers, replicating the other side to each. Crunch’s sharded join does the same with the hot keys named in advance. Hive’s skewed join keeps the hot keys in table metadata and joins them map-side.
Grouping hot keys in two stages
For a GROUP BY on a hot key, the first job sends records to reducers at random, so each
reducer computes a partial result for a share of the hot key, a count, say. A second job then
combines the partial results into one value per key. The work is spread, at the cost of an extra
pass.
Reduce-side joins need nothing from their inputs, which is their strength; they pay by sorting, copying and merging everything. If you can assume something about the inputs, a join can happen in the mappers, with no reducers and no sort at all: the map-side joins. Which one applies depends on what you know about the data, so the next section tests them all.
Five situations, five join algorithms, twenty-five runs
Each row is a situation: the same two inputs, activity events and users, laid out differently or shaped differently. Each column is one of the chapter’s join algorithms. A small join engine runs each one with 8 mappers, 8 reducers and room for 2,500 user records in a mapper’s memory, counts every record that crosses the network, and checks the output against the true join. Click any cell for how the column works and the load on each task.
Every cell is a run: click one to see what happened
| Reduce-side sort-merge join works on any input | Broadcast hash join small table fits in memory | Partitioned hash join Hive’s bucketed map join | Map-side merge join inputs partitioned and sorted alike | Skewed join Pig’s skewed join, Crunch’s sharded join | |
|---|---|---|---|---|---|
| Small user table fits in memory | |||||
| Both inputs large arbitrary layout | |||||
| Partitioned alike same key, same hash, same count | |||||
| Partitioned and sorted the output of an earlier job | |||||
| One celebrity user a hot key |
works correct, with what it moved hot reducer correct, but one task does far more out of memory the hash table does not fit not applicable the inputs are not laid out for it
How the column works Mappers emit every record from both inputs keyed by user ID; the shuffle sends each key to one reducer and sorts it, with the user record first; the reducer joins one user at a time. It makes no assumptions about the inputs, which is its strength, and it pays for that by shuffling and sorting everything. A key with far more records than the rest lands on one reducer.
Small user table under Reduce-side sort-merge joinA table of 400 users against 20,000 events, neither partitioned nor sorted in any useful way.
Records handled by each reducer:
Works It shuffles 20,400 records across the network. The busiest task does 1.0 times the average work, and peak memory is one record. All 20,000 joined rows are correct.
How the column works Each mapper loads the whole small input, the user table, into an in-memory hash table, then streams its block of events and looks each one up. Nothing is shuffled and nothing is sorted, so it is fast, but only while the small input fits in every mapper’s memory: the whole table is copied into every one of them.
Small user table under Broadcast hash joinA table of 400 users against 20,000 events, neither partitioned nor sorted in any useful way.
Records handled by each mapper:
Works Nothing is shuffled: each mapper reads its input locally, and the 400-row user table is copied into all 8 mappers. The busiest task does 1.0 times the average work, and peak memory is 400 records. All 20,000 joined rows are correct.
How the column works If both inputs were already partitioned the same way (same key, same hash function, same number of partitions), mapper k only needs partition k of the user table. Each mapper loads one partition into a hash table and joins its matching partition of events, with no shuffle. It requires that earlier jobs wrote both inputs partitioned alike, and each partition must fit in memory.
Small user table under Partitioned hash joinA table of 400 users against 20,000 events, neither partitioned nor sorted in any useful way.
Not applicable The inputs are not partitioned the way a partitioned hash join requires, so it cannot be used at all. A query planner would not consider it here.
How the column works If both inputs are partitioned alike and sorted by the key within each partition, a mapper can read the two partitions in step, like the merge in a sorted-file database, joining records with equal keys as it goes. No shuffle, no sort, and no hash table: it needs almost no memory. Typically the inputs were the output of earlier MapReduce jobs that did the partitioning and sorting.
Small user table under Map-side merge joinA table of 400 users against 20,000 events, neither partitioned nor sorted in any useful way.
Not applicable The inputs are not partitioned the way a map-side merge join requires, so it cannot be used at all. A query planner would not consider it here.
How the column works First a sampling pass finds the hot keys. Then it runs like a sort-merge join, except that a hot key’s events are spread over several reducers at random, and that user’s record is replicated to each of them. The work is evened out, at the cost of a sampling job and a few extra copies of the hot records.
Small user table under Skewed joinA table of 400 users against 20,000 events, neither partitioned nor sorted in any useful way.
Records handled by each reducer:
Works It shuffles 20,400 records across the network. The busiest task does 1.0 times the average work, and peak memory is one record. All 20,000 joined rows are correct.
How the column works Mappers emit every record from both inputs keyed by user ID; the shuffle sends each key to one reducer and sorts it, with the user record first; the reducer joins one user at a time. It makes no assumptions about the inputs, which is its strength, and it pays for that by shuffling and sorting everything. A key with far more records than the rest lands on one reducer.
Both inputs large under Reduce-side sort-merge joinNow 16,000 users, too many for a mapper’s memory, against 20,000 events, laid out however earlier jobs left them.
Records handled by each reducer:
Works It shuffles 36,000 records across the network. The busiest task does 1.0 times the average work, and peak memory is one record. All 20,000 joined rows are correct.
How the column works Each mapper loads the whole small input, the user table, into an in-memory hash table, then streams its block of events and looks each one up. Nothing is shuffled and nothing is sorted, so it is fast, but only while the small input fits in every mapper’s memory: the whole table is copied into every one of them.
Both inputs large under Broadcast hash joinNow 16,000 users, too many for a mapper’s memory, against 20,000 events, laid out however earlier jobs left them.
Fails It needs 16,000 user records in a mapper’s memory, and a mapper has room for 2,500. The job fails, or spills to disk and loses its whole advantage.
How the column works If both inputs were already partitioned the same way (same key, same hash function, same number of partitions), mapper k only needs partition k of the user table. Each mapper loads one partition into a hash table and joins its matching partition of events, with no shuffle. It requires that earlier jobs wrote both inputs partitioned alike, and each partition must fit in memory.
Both inputs large under Partitioned hash joinNow 16,000 users, too many for a mapper’s memory, against 20,000 events, laid out however earlier jobs left them.
Not applicable The inputs are not partitioned the way a partitioned hash join requires, so it cannot be used at all. A query planner would not consider it here.
How the column works If both inputs are partitioned alike and sorted by the key within each partition, a mapper can read the two partitions in step, like the merge in a sorted-file database, joining records with equal keys as it goes. No shuffle, no sort, and no hash table: it needs almost no memory. Typically the inputs were the output of earlier MapReduce jobs that did the partitioning and sorting.
Both inputs large under Map-side merge joinNow 16,000 users, too many for a mapper’s memory, against 20,000 events, laid out however earlier jobs left them.
Not applicable The inputs are not partitioned the way a map-side merge join requires, so it cannot be used at all. A query planner would not consider it here.
How the column works First a sampling pass finds the hot keys. Then it runs like a sort-merge join, except that a hot key’s events are spread over several reducers at random, and that user’s record is replicated to each of them. The work is evened out, at the cost of a sampling job and a few extra copies of the hot records.
Both inputs large under Skewed joinNow 16,000 users, too many for a mapper’s memory, against 20,000 events, laid out however earlier jobs left them.
Records handled by each reducer:
Works It shuffles 36,000 records across the network. The busiest task does 1.0 times the average work, and peak memory is one record. All 20,000 joined rows are correct.
How the column works Mappers emit every record from both inputs keyed by user ID; the shuffle sends each key to one reducer and sorts it, with the user record first; the reducer joins one user at a time. It makes no assumptions about the inputs, which is its strength, and it pays for that by shuffling and sorting everything. A key with far more records than the rest lands on one reducer.
Partitioned alike under Reduce-side sort-merge joinBoth inputs were written by earlier jobs that partitioned them by user ID into the same 8 partitions, but did not sort them.
Records handled by each reducer:
Works It shuffles 36,000 records across the network. The busiest task does 1.0 times the average work, and peak memory is one record. All 20,000 joined rows are correct.
How the column works Each mapper loads the whole small input, the user table, into an in-memory hash table, then streams its block of events and looks each one up. Nothing is shuffled and nothing is sorted, so it is fast, but only while the small input fits in every mapper’s memory: the whole table is copied into every one of them.
Partitioned alike under Broadcast hash joinBoth inputs were written by earlier jobs that partitioned them by user ID into the same 8 partitions, but did not sort them.
Fails It needs 16,000 user records in a mapper’s memory, and a mapper has room for 2,500. The job fails, or spills to disk and loses its whole advantage.
How the column works If both inputs were already partitioned the same way (same key, same hash function, same number of partitions), mapper k only needs partition k of the user table. Each mapper loads one partition into a hash table and joins its matching partition of events, with no shuffle. It requires that earlier jobs wrote both inputs partitioned alike, and each partition must fit in memory.
Partitioned alike under Partitioned hash joinBoth inputs were written by earlier jobs that partitioned them by user ID into the same 8 partitions, but did not sort them.
Records handled by each mapper:
Works Nothing is shuffled: each mapper reads its input locally. The busiest task does 1.0 times the average work, and peak memory is 2,004 records. All 20,000 joined rows are correct.
How the column works If both inputs are partitioned alike and sorted by the key within each partition, a mapper can read the two partitions in step, like the merge in a sorted-file database, joining records with equal keys as it goes. No shuffle, no sort, and no hash table: it needs almost no memory. Typically the inputs were the output of earlier MapReduce jobs that did the partitioning and sorting.
Partitioned alike under Map-side merge joinBoth inputs were written by earlier jobs that partitioned them by user ID into the same 8 partitions, but did not sort them.
Not applicable The inputs are not sorted the way a map-side merge join requires, so it cannot be used at all. A query planner would not consider it here.
How the column works First a sampling pass finds the hot keys. Then it runs like a sort-merge join, except that a hot key’s events are spread over several reducers at random, and that user’s record is replicated to each of them. The work is evened out, at the cost of a sampling job and a few extra copies of the hot records.
Partitioned alike under Skewed joinBoth inputs were written by earlier jobs that partitioned them by user ID into the same 8 partitions, but did not sort them.
Records handled by each reducer:
Works It shuffles 36,000 records across the network. The busiest task does 1.0 times the average work, and peak memory is one record. All 20,000 joined rows are correct.
How the column works Mappers emit every record from both inputs keyed by user ID; the shuffle sends each key to one reducer and sorts it, with the user record first; the reducer joins one user at a time. It makes no assumptions about the inputs, which is its strength, and it pays for that by shuffling and sorting everything. A key with far more records than the rest lands on one reducer.
Partitioned and sorted under Reduce-side sort-merge joinAs before, and each partition is also sorted by user ID, as a MapReduce job’s output naturally is.
Records handled by each reducer:
Works It shuffles 36,000 records across the network. The busiest task does 1.0 times the average work, and peak memory is one record. All 20,000 joined rows are correct.
How the column works Each mapper loads the whole small input, the user table, into an in-memory hash table, then streams its block of events and looks each one up. Nothing is shuffled and nothing is sorted, so it is fast, but only while the small input fits in every mapper’s memory: the whole table is copied into every one of them.
Partitioned and sorted under Broadcast hash joinAs before, and each partition is also sorted by user ID, as a MapReduce job’s output naturally is.
Fails It needs 16,000 user records in a mapper’s memory, and a mapper has room for 2,500. The job fails, or spills to disk and loses its whole advantage.
How the column works If both inputs were already partitioned the same way (same key, same hash function, same number of partitions), mapper k only needs partition k of the user table. Each mapper loads one partition into a hash table and joins its matching partition of events, with no shuffle. It requires that earlier jobs wrote both inputs partitioned alike, and each partition must fit in memory.
Partitioned and sorted under Partitioned hash joinAs before, and each partition is also sorted by user ID, as a MapReduce job’s output naturally is.
Records handled by each mapper:
Works Nothing is shuffled: each mapper reads its input locally. The busiest task does 1.0 times the average work, and peak memory is 2,004 records. All 20,000 joined rows are correct.
How the column works If both inputs are partitioned alike and sorted by the key within each partition, a mapper can read the two partitions in step, like the merge in a sorted-file database, joining records with equal keys as it goes. No shuffle, no sort, and no hash table: it needs almost no memory. Typically the inputs were the output of earlier MapReduce jobs that did the partitioning and sorting.
Partitioned and sorted under Map-side merge joinAs before, and each partition is also sorted by user ID, as a MapReduce job’s output naturally is.
Records handled by each mapper:
Works Nothing is shuffled: each mapper reads its input locally. The busiest task does 1.0 times the average work, and peak memory is one record. All 20,000 joined rows are correct.
How the column works First a sampling pass finds the hot keys. Then it runs like a sort-merge join, except that a hot key’s events are spread over several reducers at random, and that user’s record is replicated to each of them. The work is evened out, at the cost of a sampling job and a few extra copies of the hot records.
Partitioned and sorted under Skewed joinAs before, and each partition is also sorted by user ID, as a MapReduce job’s output naturally is.
Records handled by each reducer:
Works It shuffles 36,000 records across the network. The busiest task does 1.0 times the average work, and peak memory is one record. All 20,000 joined rows are correct.
How the column works Mappers emit every record from both inputs keyed by user ID; the shuffle sends each key to one reducer and sorts it, with the user record first; the reducer joins one user at a time. It makes no assumptions about the inputs, which is its strength, and it pays for that by shuffling and sorting everything. A key with far more records than the rest lands on one reducer.
One celebrity user under Reduce-side sort-merge joinLarge inputs again, but one user, a celebrity, accounts for 40% of all activity: a linchpin object, or hot key.
Records handled by each reducer:
Works, slowly It works, but the busiest reducer gets 11,411 records, 2.5 times the average: the celebrity’s events all hash to one place. The whole job waits for that one task. All 20,000 joined rows are correct.
How the column works Each mapper loads the whole small input, the user table, into an in-memory hash table, then streams its block of events and looks each one up. Nothing is shuffled and nothing is sorted, so it is fast, but only while the small input fits in every mapper’s memory: the whole table is copied into every one of them.
One celebrity user under Broadcast hash joinLarge inputs again, but one user, a celebrity, accounts for 40% of all activity: a linchpin object, or hot key.
Fails It needs 16,000 user records in a mapper’s memory, and a mapper has room for 2,500. The job fails, or spills to disk and loses its whole advantage.
How the column works If both inputs were already partitioned the same way (same key, same hash function, same number of partitions), mapper k only needs partition k of the user table. Each mapper loads one partition into a hash table and joins its matching partition of events, with no shuffle. It requires that earlier jobs wrote both inputs partitioned alike, and each partition must fit in memory.
One celebrity user under Partitioned hash joinLarge inputs again, but one user, a celebrity, accounts for 40% of all activity: a linchpin object, or hot key.
Not applicable The inputs are not partitioned the way a partitioned hash join requires, so it cannot be used at all. A query planner would not consider it here.
How the column works If both inputs are partitioned alike and sorted by the key within each partition, a mapper can read the two partitions in step, like the merge in a sorted-file database, joining records with equal keys as it goes. No shuffle, no sort, and no hash table: it needs almost no memory. Typically the inputs were the output of earlier MapReduce jobs that did the partitioning and sorting.
One celebrity user under Map-side merge joinLarge inputs again, but one user, a celebrity, accounts for 40% of all activity: a linchpin object, or hot key.
Not applicable The inputs are not partitioned the way a map-side merge join requires, so it cannot be used at all. A query planner would not consider it here.
How the column works First a sampling pass finds the hot keys. Then it runs like a sort-merge join, except that a hot key’s events are spread over several reducers at random, and that user’s record is replicated to each of them. The work is evened out, at the cost of a sampling job and a few extra copies of the hot records.
One celebrity user under Skewed joinLarge inputs again, but one user, a celebrity, accounts for 40% of all activity: a linchpin object, or hot key.
Records handled by each reducer:
Works It shuffles 36,005 records across the network, after sampling found 1 hot key and spread it over 6 reducers. The busiest task does 1.1 times the average work, and peak memory is one record. All 20,000 joined rows are correct.
The grid is the chapter’s advice in one picture. With a small table, a broadcast hash join wins: nothing moves. When both inputs are large, only the joins that make no assumptions apply, unless earlier jobs wrote the inputs partitioned alike, which opens the partitioned hash join, or partitioned and sorted alike, which opens the merge join. With a celebrity in the data, the plain sort-merge join gives one reducer 2.5 times the average work, and the skewed join brings it down to 1.1. Notice what the map-side joins depend on: the physical layout of datasets written by earlier jobs. That is why the partitioning and sort order of outputs is recorded in metadata, as in HCatalog and the Hive metastore.
Two variants worth knowing. A broadcast hash join’s small input can live in a read-only index on the mapper’s local disk instead of in memory, as long as the frequently used parts stay in the operating system’s page cache. And the broadcast join goes by many names: Pig’s replicated join, Hive’s MapJoin, and the same idea in Cascading, Crunch and MPP engines such as Impala.
Not reports: indexes, models and databases
A batch job’s output is rarely a report. It is something an application uses. Google’s original use of MapReduce was to build the indexes for its search engine, a workflow of five to ten jobs, and Lucene and Solr indexes are still built this way: mappers partition the documents, reducers build each partition’s index, and the index files are written once and never changed. Another common output is a database for an online service: the features for a classifier, or the recommendations a website looks up for each user.
Two ways to get a job’s output into a serving database
A network request per record is orders of magnitude slower than a batch task’s normal throughput, and many tasks writing at once can overwhelm the database and hurt the online system that shares it. Worse, a retried task repeats writes the failed attempt already made, and other jobs see partial results.
Two tasks of 1,000 rows each, one failing halfway: the database ends with 2,500 rows, 500 of them duplicates.
The job writes its output as files in the distributed filesystem, immutable once written. Servers load them in bulk, and switch to the new files only when the whole job has succeeded; a failed task’s partial output is simply thrown away. Voldemort, Terrapin, ElephantDB and HBase bulk loading work this way.
Two tasks of 1,000 rows each, one failing halfway: the database ends with 2,000 rows, no duplicates.
Why immutable output is the right default
Buggy code that ran on a database leaves corrupted data behind; buggy code that wrote new files can be rolled back to the previous output and rerun. That is human fault tolerance, and Agile teams call it minimizing irreversibility. A failed task is retried automatically, because its inputs are unchanged and its partial output is discarded. The same files can feed many different jobs, including monitoring jobs that compare a run’s output with the last one.
Logic and wiring again
As in Unix, a MapReduce job’s code does not know where its inputs come from or its outputs go.
The input directory, the output directory and the scheduling are configured separately. One
team can write a job that does one thing well while another decides where and when it runs: the
same reuse that made sort and uniq useful.
An operating system, not a database
Massively parallel processing (MPP) databases, from Teradata onward, had run analytic SQL across clusters for over a decade before MapReduce. The biggest difference is that an MPP database is a database, tightly integrated around SQL, while MapReduce and a distributed filesystem are more like a general-purpose operating system that can run arbitrary programs.
Diversity of storage
A database requires you to model data before importing it. Hadoop lets you dump data into HDFS as it is, and work out how to interpret it later: a data lake, or enterprise data hub. The burden of interpretation moves to the consumer, a schema-on-read approach, and collecting data becomes fast. The sushi principle: raw data is better.
Diversity of processing models
SQL is a great fit for many queries, not for all: machine learning, recommendation, full-text indexes and image analysis need code. Hadoop runs SQL engines such as Hive and Impala and arbitrary programs, and HBase for random-access OLTP, side by side on the same cluster, over the same files. Each system can bring its own processing model.
The two also make opposite assumptions about failure. When a node crashes mid-query, an MPP database aborts the whole query and runs it again, which is fine for queries of seconds or minutes on dedicated hardware. MapReduce retries the failed task, and writes data to disk eagerly so that it can. That design comes from Google’s mixed-use datacenters, where batch tasks run at low priority and are preempted when online services need the machines: a task that runs for an hour has about a 5% chance of being killed. Choose a job’s size and see what each approach costs:
Restart the query, or retry the task
Each task is killed with probability 5%. An MPP database, which reruns the whole query when anything fails, finishes on average after about 28,529 attempts, since each attempt survives only about one time in 28,529. MapReduce reruns only the killed tasks, so the job costs about 1.05× the work, 5% extra.
Where machines are rarely preempted, task failures are rare too, and the cost of MapReduce’s caution is less obviously worth paying. Which leads to the engines that came after it.
Stop writing everything down
MapReduce is one programming model among many, and a fairly low-level one. Its biggest cost is materialization: every job writes its whole output to the distributed filesystem before the next can start. Unix pipes stream; MapReduce writes everything down. Here is the same three-stage workflow both ways.
One workflow, two engines
Every job waits for all tasks of the job before it, so the slowest task of each stage holds up the next. Each job writes its whole output to the distributed filesystem, 3 replicas of every block, and the next job begins with mappers that only read it back. Finished at 52, with 3,456 MB written to replicated storage.
Spark, Tez and Flink run the whole workflow as one job. A partition flows into the next operator as soon as it is ready, over the network or a local pipe, kept in memory or on local disk; there are no redundant mappers and no replicated intermediate files. Only the final output is written to the distributed filesystem. Finished at 35, 34% sooner, with 1,152 MB written.
Spark, Tez and Flink are dataflow engines: they model a whole workflow as one job, a graph of operators, and choose how to connect them. An operator’s output can be repartitioned and sorted, like MapReduce’s shuffle; partitioned without sorting, enough for a partitioned hash join; or broadcast to every partition of the next operator, for a broadcast hash join. Sorting happens only where it is actually needed, there are no redundant map tasks, operators start as soon as their input is ready, and existing processes are reused rather than started for each task. In the exhibit the dataflow version finishes 34% sooner. Pig, Hive and Cascading can switch from MapReduce to Tez or Spark with a configuration change.
Fault tolerance without materialization
With nothing written down, a lost partition must be recomputed from whatever earlier data is still available. Spark tracks each dataset’s ancestry with the resilient distributed dataset (RDD) abstraction; Flink checkpoints operator state. Recomputation is only safe if operators are deterministic, which the next exhibit tests. When intermediate data is much smaller than its source, or expensive to compute, materializing it is cheaper than recomputing it.
Some writing remains
A sorting operator must consume its entire input before it can output anything, so any stage that sorts still accumulates state, if only in memory or on local disk. And the final output of the job is still written to the distributed filesystem, as with MapReduce.
Recomputing a lost partition
| records sampled | |
|---|---|
| first run, already consumed downstream | 102 |
| recomputed after a failure | 102 |
| in both | 102 |
An operator keeps a random 10% of its input. Part of its output has already gone downstream when a machine fails, and the engine recomputes the lost partition from the input, as Spark does from an RDD’s lineage. The same seed gives the same sample, so the recomputed output is identical: recovery is invisible. Iteration order of hash tables, random numbers and the system clock are the usual sources of nondeterminism.
| records sampled | |
|---|---|
| first run, already consumed downstream | 108 |
| recomputed after a failure | 114 |
| in both | 9 |
An operator keeps a random 10% of its input. Part of its output has already gone downstream when a machine fails, and the engine recomputes the lost partition from the input, as Spark does from an RDD’s lineage. Only 9 records are in both samples, so downstream operators now hold results from two different runs that contradict each other. The only fix is to kill the downstream operators too and run them again. Iteration order of hash tables, random numbers and the system clock are the usual sources of nondeterminism.
Think like a vertex
Some algorithms, such as PageRank, which estimates how important a web page is from the pages that link to it, repeat a step until it stops changing. Running each iteration as a MapReduce job rereads and rewrites the entire graph every time, even when only a small part has changed. The bulk synchronous parallel model, popularized by Google’s Pregel and implemented in Apache Giraph, Spark’s GraphX and Flink’s Gelly, does it differently: each vertex keeps its state in memory and sends messages to other vertices along the edges, in rounds called supersteps.
PageRank on five pages, 12 supersteps
Each of the 5 pages starts with rank 1/5. In every superstep, each vertex sends its rank divided by its number of outgoing links along each link, 8 messages in all, and the framework delivers them all before the next superstep begins.
Each vertex sets its rank to 3% plus 0.85 times the sum of the messages it received. The biggest change this round was 0.170. Ranking now: C > A > B > D > E.
Each vertex sets its rank to 3% plus 0.85 times the sum of the messages it received. The biggest change this round was 0.108. Ranking now: A > C > B > D > E.
Each vertex sets its rank to 3% plus 0.85 times the sum of the messages it received. The biggest change this round was 0.077. Ranking now: C > A > B > D > E.
Each vertex sets its rank to 3% plus 0.85 times the sum of the messages it received. The biggest change this round was 0.014. Ranking now: C > A > B > D > E.
No rank moved by more than 0.001 this round, so the computation stops. C ranks highest, then A: pages that well-linked pages link to.
How Pregel survives failures
Messages are delivered exactly once in each superstep, after all of the previous superstep’s messages; the framework batches them and retries lost ones. For machine failures, it checkpoints the state of every vertex at the end of an iteration, and on a failure rolls the whole computation back to the last checkpoint and restarts from there.
When a distributed graph is slower
A vertex does not know which machine it runs on, so the graph is usually partitioned by vertex ID, with no attempt to keep connected vertices together. Most messages then cross the network, and that overhead can dominate. If the graph fits in one machine’s memory, a single-machine algorithm can beat a distributed one; GraphChi even works from local disk.
Declarative again
Engineers wrote raw MapReduce for a few years, then moved to higher-level languages: Hive, Pig, Cascading and Crunch, now running on Tez, Spark and Flink. Less code, and the same code runs on whichever engine is best. And because relational operators say what to compute rather than how, an engine can choose for itself.
Letting the optimizer choose the join
Spell out a join in code and you pick the algorithm. Declare it, and a cost-based optimizer in Hive, Spark or Flink can choose from the grid above by looking at the inputs: their sizes, how they are partitioned and sorted. Engines also adopted the MPP tricks of columnar storage, vectorized execution and generating code at runtime. Batch systems still let you call arbitrary code where you need it.
Specialized domains
Some algorithms are needed again and again, so they get reusable implementations: machine learning in Mahout and Spark’s MLlib, and MADlib inside MPP databases; k-nearest-neighbor search; approximate search; spatial algorithms; genome analysis, with approximate string matching. Batch processing engines and MPP databases are becoming more alike.
Did it stick?
1. How does the book distinguish batch processing from services and stream processing?
2. In the log pipeline, why must the input be sorted before `uniq -c`?
3. When does sorting beat an in-memory hash table for counting URLs?
4. Which idea from Unix does MapReduce share most directly?
5. In a reduce-side sort-merge join, why does the secondary sort put the user record first?
6. When is a broadcast hash join possible?
7. What does a map-side merge join require of its inputs?
8. In the grid, how much more work does the busiest reducer get in a plain sort-merge join with one celebrity user?
9. Why should a batch job not write directly into the production database from its tasks?
10. Why does MapReduce retry individual tasks while MPP databases abort the whole query?
11. What do dataflow engines like Spark, Tez and Flink avoid compared with chains of MapReduce jobs?
12. In the Pregel model, what happens in one superstep?
Answered 0 of 12 · 0 correct
The terms this chapter installs
Chapter 10 in one breath. Batch processing takes a bounded input and produces output, and its best ideas came from Unix: small programs that do one thing, a uniform interface, logic separated from wiring, inputs that are never modified. MapReduce spread that over thousands of machines: the mapper extracts keys, the framework partitions and sorts, the reducer sees each key’s values together, and a distributed filesystem plays the part of the file. Joins happen by bringing related records to the same place, in the reducer when you know nothing about the inputs, in the mappers when you know their size or layout, with sampling to cope with hot keys. Output is best written as new immutable files, so a failed or buggy job can simply be discarded and rerun. MapReduce retries tasks rather than queries because it was built for clusters where tasks get preempted. Dataflow engines keep the model and drop the materialization; Pregel handles iterative graph algorithms in supersteps; declarative languages let the engine pick the algorithm. All of it works on bounded input. The next chapter removes that assumption.