AlgoViz

MapReduce

medium 30 min

MapReduce 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

0:00 / 4:34

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

  1. February 2003

    Engineers at Google write the first version of the MapReduce library, and in August add locality and load balancing.

  2. December 2004

    Jeffrey Dean and Sanjay Ghemawat publish the MapReduce paper at the OSDI conference.

  3. April 2006

    The first release of Apache Hadoop, an open-source implementation with its own distributed file system, HDFS.

  4. 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.

Step 1 of 3

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.

Twelve shells, six hands
12 shells, 1 person

Five, four and three make twelve. Nine cards travelled instead of twelve shells.

The idea

Word count, the first program

From text to counts

Three splits in HDFS are read by three map tasks holding the texts hello world, hello mapreduce and world of data. Map tasks 1 and 3 send pairs to both reduce tasks and map task 2 only to reduce task 1. Reduce task 1 handles data, hello and mapreduce; reduce task 2 handles of and world. Each writes one output part.
The orange arrows are the shuffle: any map task may have something for any reduce task.
Python
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)))
All the code you write for word count. The last lines stand in for the framework.
Edit and run it in your browser

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?

⌈1 TB128 MB⌉=7,813⌈7,813400⌉×30 s=600 s\left\lceil \frac{1\ \text{TB}}{128\ \text{MB}} \right\rceil = 7{,}813 \qquad \left\lceil \frac{7{,}813}{400} \right\rceil \times 30\,\text{s} = 600\,\text{s}
128 MB is the default block size in HDFS (counted here in decimal units). With 400 tasks at a time and an assumed 30 seconds each, the map phase is 20 rounds, or 10 minutes.

Shuffle

Shuffle and sort

Before and after

WherePairs
Map task 1 emits(a, 1) (b, 1) (a, 1)
Map task 2 emits(b, 1) (c, 1) (a, 1)
Reduce gets key a1, 1, 1
Reduce gets key b1, 1
Reduce gets key c1
  1. 1

    Partition

    Each pair is assigned to a reduce task, normally by hash of the key modulo the number of reduce tasks.

  2. 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. 3

    Fetch

    Each reduce task copies its part from every map task.

  4. 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

Map output goes to the local disk, not to the replicated file system.

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

t≈datamachines×bandwidth=200,000 MB40×100 MB/s=50 st \approx \frac{\text{data}}{\text{machines} \times \text{bandwidth}} = \frac{200{,}000\ \text{MB}}{40 \times 100\ \text{MB/s}} = 50\ \text{s}
Assumed 200 GB of map output and 100 MB/s of usable network per machine. A combiner that leaves a tenth turns 50 seconds into 5. One skewed reduce task can still take far longer.

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.

OperationCombine directly?How
SumYes[1, 2, 3] gives 6
CountYes, by addingThree records emit 1 each, and reduce adds: 3
Maximum, minimumYesThe maximum of [1, 5, 3] is 5
AverageNoSend sum and count: (12, 3) gives 4
MedianNoNeeds all values, or an approximate sketch
Distinct usersNoSend sets, or a sketch that can be merged
The average of averages is wrong: groups [2, 4] and [9] have averages 3 and 9, which average to 6, but the true average is 5.

Can I combine this?

A sum can reuse its reduce. An average has to carry a sum and a count.

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

JobMap emitsReduce does
Inverted indexword, document idSorted list of unique ids
Sales per productproduct, (amount, units, 1)Totals, then divide for the average
Log errors per serviceservice, 1 for each error lineSum
Join orders with usersuser id, (kind, record)Pair the user with each order
Grepline, if it matchesNothing: a job may have no reduce

Cluster

Who does what

One coordinator, many workers

A coordinator with a task table assigns map task 1 to worker A, which has split 1, and map task 2 to worker B, which has split 2. Both write to their local disk. Worker C fetches from both disks for reduce task 1 and writes the result to HDFS with three copies.
Data flows between workers. The coordinator only keeps track.

When something fails

Finished map output was on the dead machine's disk, so it is needed again. Finished reduce output is already in the replicated file system.

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.

RemedyHowLimit
CombinerAdd up before the networkOnly for operations that combine
Salt the keythe becomes the-0 to the-9, then a second job adds ten resultsAn extra step
Own partitionerGive known large keys their own taskYou must know them, and one key still has one task
More reduce tasksSpreads many medium keysDoes not split one key
Map-side joinSend the small table to every map task, with no shuffleThe 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?

For new batch work, most teams choose a dataflow engine. The thinking is the same.

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.

Sources