MapReduce
medium 30 minMapReduce processes very large data on many machines with two small functions.
Video lesson · Chapter 1 of 5
Count words across three pieces of a book
Theory
Read or listen first. About 2 min.
What it is
MapReduce is a way to write programs that run over very large data. You write two functions. Map looks at one record and emits key and value pairs. Reduce gets one key with all its values and produces a result.
Everything else is done by the framework: it cuts the input into pieces, runs map beside the data, sorts and moves the pairs so that equal keys meet, runs reduce, and starts failed work again.
Why it exists
Reading a terabyte from one disk at 100 megabytes a second takes almost three hours. A thousand disks reading at once need about ten seconds. But a program on a thousand machines must also survive broken ones, slow ones and a slow network.
Before MapReduce, each such program solved these problems again. Its idea was to limit what you may write, so that the framework can do the hard parts for everyone. It is used less today than its successors, but they kept its central step, the shuffle, and its words.
A short history
February 2003
Engineers at Google write the first version of the MapReduce library, and in August add locality and load balancing.
December 2004
Jeffrey Dean and Sanjay Ghemawat publish the MapReduce paper at the OSDI conference.
April 2006
The first release of Apache Hadoop, an open-source implementation with its own distributed file system, HDFS.
2012
The Spark paper on resilient distributed datasets is published at NSDI. Keeping data in memory between steps makes repeated jobs much faster.
Words to know
- Split
- One piece of the input, read by one map task.
- Map task
- Runs your map function on one split.
- Intermediate pair
- A key and value that map emitted.
- Partitioner
- Decides which reduce task gets a key.
- Shuffle
- Moving the pairs from map tasks to reduce tasks, sorted by key.
- Combiner
- A small reduce that runs beside the map, before the network.
- Skew
- One key or task with far more data than the rest.
- Straggler
- A task that is much slower than the others.
- Locality
- Running the work on a machine that holds the data.
How it works
Step through the idea, or press Play.
Map. Each map task reads one split and emits key and value pairs, beside the data
Understand it
Start here
Counting shells on the beach
You have a heap of shells and want to know how many there are of each kind. One person would take all day, so many hands help.
Five, four and three make twelve. Nine cards travelled instead of twelve shells.
The idea
Word count, the first program
From text to counts
from itertools import groupbydef mapper(line): for word in line.lower().split(): yield word, 1def reducer(word, counts): return word, sum(counts)lines = ["hello world", "hello mapreduce", "world of data"]pairs = sorted(p for line in lines for p in mapper(line))for word, group in groupby(pairs, key=lambda p: p[0]): print(*reducer(word, (n for _, n in group)))What the framework gives you
Parallel work
Tasks run at the same time on many machines.
Growth
Add machines to process more, until the shuffle or one big key is the limit.
Failed tasks run again
Without your program noticing.
Locality
Map runs where the data is, or near it. Moving code is cheaper than moving data.
Same answer
If map and reduce are deterministic, running a task again gives the same output.
Batch
The result comes when the whole input has been processed.
Map
The map phase
Map sees one record at a time and emits zero or more pairs. For the line hello world hello it emits (hello, 1), (world, 1), (hello, 1). It knows nothing about other lines, so a thousand map tasks need no agreement.
Good mappers
- Handle each record alone
- Emit key and value pairs
- Keep no state that the result depends on
- Use a combiner for local sums
- Count and skip malformed records
Mappers that hurt
- State carried between records
- A call to an outside service for each record
- Relying on record order
- Very large keys
- Ignoring a key that holds most records
How many map tasks?
Shuffle
Shuffle and sort
Before and after
| Where | Pairs |
|---|---|
| Map task 1 emits | (a, 1) (b, 1) (a, 1) |
| Map task 2 emits | (b, 1) (c, 1) (a, 1) |
| Reduce gets key a | 1, 1, 1 |
| Reduce gets key b | 1, 1 |
| Reduce gets key c | 1 |
- 1
Partition
Each pair is assigned to a reduce task, normally by hash of the key modulo the number of reduce tasks.
- 2
Sort and spill
Pairs fill a memory buffer. When it is nearly full they are sorted and written to the map machine's own disk.
- 3
Fetch
Each reduce task copies its part from every map task.
- 4
Merge
Sorted runs are merged, so equal keys come one after another, and reduce can read a key's values as a stream.
One map task and one reduce task
The shuffle moves data over the network and through disks, so it is often the slowest part. When memory is full, data spills to disk. Three things help: a combiner, compressed map output, and dropping unneeded fields early. The sorting itself is the one known from SSTables: sorted runs that are merged.
Time for the shuffle
Combiner
Add up before you send
A combiner runs on the map machine over its own output. For word count it turns a thousand pairs (the, 1) into one pair (the, 1000). The framework may run it never, once or several times, so the answer must not depend on it. That needs an operation that is commutative and associative, with an output that looks like its input.
| Operation | Combine directly? | How |
|---|---|---|
| Sum | Yes | [1, 2, 3] gives 6 |
| Count | Yes, by adding | Three records emit 1 each, and reduce adds: 3 |
| Maximum, minimum | Yes | The maximum of [1, 5, 3] is 5 |
| Average | No | Send sum and count: (12, 3) gives 4 |
| Median | No | Needs all values, or an approximate sketch |
| Distinct users | No | Send sets, or a sketch that can be merged |
Can I combine this?
Reduce
The reduce phase
Reduce gets a key and all its values: (hello, [1, 1]) gives (hello, 2). Different keys need no agreement, so reduce tasks run in parallel. Each one processes its keys in sorted order and writes one output file.
To get a fully sorted result, partition by range instead of by hash: task 0 gets words a to m and task 1 gets n to z. Equal letter ranges are rarely equal work, so sample the keys first and choose the borders from the sample.
More programs in two functions
| Job | Map emits | Reduce does |
|---|---|---|
| Inverted index | word, document id | Sorted list of unique ids |
| Sales per product | product, (amount, units, 1) | Totals, then divide for the average |
| Log errors per service | service, 1 for each error line | Sum |
| Join orders with users | user id, (kind, record) | Pair the user with each order |
| Grep | line, if it matches | Nothing: a job may have no reduce |
Cluster
Who does what
One coordinator, many workers
When something fails
Workers report to the coordinator, and silence means dead. In the original paper, a sort job took 44% longer with backup copies switched off, because of a few slow machines. Hadoop calls these backups speculative execution and tries a map task up to four times by default.
Skew
One key that is too big
All values of a key go to one reduce task. If most records are about one key, such as the word the or one very popular user, that task runs long after the others have finished.
| Remedy | How | Limit |
|---|---|---|
| Combiner | Add up before the network | Only for operations that combine |
| Salt the key | the becomes the-0 to the-9, then a second job adds ten results | An extra step |
| Own partitioner | Give known large keys their own task | You must know them, and one key still has one task |
| More reduce tasks | Spreads many medium keys | Does not split one key |
| Map-side join | Send the small table to every map task, with no shuffle | The small table must fit in memory |
Limits
When to use it, and when not
It fits when
- There are terabytes or more to read
- Waiting minutes or hours is fine
- Work can be divided by key
- Tasks are independent
- Jobs are long, so surviving failures matters
It does not fit when
- Answers are needed at once: use stream processing
- The data fits on one machine: use one machine
- Many steps follow each other
- The same data is read again and again
- People ask questions live: use an OLAP engine
One job is one map and one reduce. A longer program is a chain of jobs, and each writes its full output to replicated files before the next one reads them. This waiting and writing is what dataflow engines remove.
Which tool?
Do
- Use combiners where the operation allows
- Choose keys that spread the work
- Compress map output
- Reuse objects in hot loops on the JVM
- Set memory from measurements
Do not
- Create objects for every record without need
- Use large values as keys
- Ignore locality
- Test only on small samples
- Assume that keys are equally common
The same split, work and merge for a live request is fan-out and fan-in. Batch against streams is compared in batch and stream.
Summary
The whole topic in one minute.
Map emits pairs, shuffle brings equal keys together in sorted order, reduce finishes each key. Tasks are independent, so a failed one is simply run again, and a slow one is run twice.
The shuffle is usually the cost. Make it smaller with a combiner, when your operation allows it, and watch for one key that holds most of the data. For many steps or repeated passes, use an engine that keeps data in memory between steps.
- Map emits pairs, shuffle groups by key, reduce finishes each key.
- Map output stays on local disks; final output is replicated.
- The shuffle is usually the cost; combiners shrink it.
- Average needs sum and count.
- Failed work is run again, slow work is run twice.
- One huge key defeats any number of machines.