Sina Vafadar

MapReduce

Nov 26, 2026 · 32 min

A lab on MapReduce: Simplified Data Processing on Large Clusters, by Jeffrey Dean and Sanjay Ghemawat, OSDI 2004.

Papers · Dean and Ghemawat, OSDI 2004 · Recall lab

By 2004, engineers at Google had written hundreds of special-purpose programs that chewed through crawled documents and request logs to build inverted indices, link graphs and daily summaries. Each computation was simple. What made them hard was everything around it: how to split the work across hundreds of machines, move the data, survive the machines that died along the way, and keep the slow ones from holding everything up. MapReduce is the abstraction that took all of that into one library, and left the programmer with two functions to write. By the time of the paper, hundreds of MapReduce programs had been written, and upwards of 1,000 jobs ran on Google’s clusters every day.

Read alongside DDIA chapter 10, Batch Processing, which builds on this paper: what you do once you have MapReduce, from joins and workflows to the dataflow engines that came after it.

The programming model § 2 Programming Model

Two functions, and the library does the rest

The computation takes a set of input key/value pairs and produces a set of output pairs. The user writes map, which takes one input pair and produces any number of intermediate pairs, and reduce, which takes one intermediate key and all the values that share it, through an iterator, and merges them into a usually smaller set. The library groups the intermediate values by key in between. The idea comes from the map and reduce primitives of Lisp and other functional languages.

The types are map (k1, v1) → list(k2, v2) and reduce (k2, list(v2)) → list(v2): the input comes from one domain, and the intermediate and output pairs from another. The canonical example counts words. Map emits (w, 1) for every word w in a document; reduce sums the counts for each word. The iterator matters more than it looks: it lets reduce handle a list of values far too large to fit in memory.

The paper gives seven programs that fit the model. Each is just a choice of what map emits and what reduce does with it:

Seven programs from § 2.3, as map and reduce

programmap emitsreduce
Word count(word, 1) for every wordadds the counts
Distributed grepa line, if it matches the patternidentity: copies the lines to the output
URL access frequency(URL, 1) for every request in the web logsadds them: (URL, total count)
Reverse web-link graph(target, source) for every link to target found in page sourceconcatenates the sources: (target, list(source))
Term vector per host(hostname, term vector) per document, the host taken from its URLadds a host’s term vectors, drops infrequent terms
Inverted index(word, document ID) for every wordsorts the IDs: (word, list(document ID))
Distributed sort(key, record), the key extracted from the recordidentity, relying on partitioning and ordering (below)

A term vector is the most important words in a document or set of documents, as a list of (word, frequency) pairs. An inverted index is easy to extend with word positions.

Besides the two functions, the user fills in a specification object: the input and output files and optional tuning parameters, then calls MapReduce with it. The paper’s appendix gives the whole word-count program in the C++ library. Shortened, it is this:

Appendix A: word count, the whole program

class WordCounter : public Mapper {
  virtual void Map(const MapInput& input) {
    const string& text = input.value();
    for each word in text:            // the paper scans for whitespace by hand
      Emit(word, "1");
  }
};
REGISTER_MAPPER(WordCounter);

class Adder : public Reducer {
  virtual void Reduce(ReduceInput* input) {
    int64 value = 0;
    while (!input->done()) {          // iterate over all values for this key
      value += StringToInt(input->value());
      input->NextValue();
    }
    Emit(IntToString(value));
  }
};
REGISTER_REDUCER(Adder);

int main(int argc, char** argv) {
  MapReduceSpecification spec;
  for (int i = 1; i < argc; i++) {    // one input per file pattern
    MapReduceInput* input = spec.add_input();
    input->set_format("text");
    input->set_filepattern(argv[i]);
    input->set_mapper_class("WordCounter");
  }
  MapReduceOutput* out = spec.output();
  out->set_filebase("/gfs/test/freq");  // freq-00000-of-00100, ...
  out->set_num_tasks(100);              // R = 100
  out->set_format("text");
  out->set_reducer_class("Adder");
  out->set_combiner_class("Adder");     // partial sums inside map tasks
  spec.set_machines(2000);
  spec.set_map_megabytes(100);
  spec.set_reduce_megabytes(100);
  MapReduceResult result;
  if (!MapReduce(spec, &result)) abort();
  return 0;                            // result holds counters, time, machines
}

Three lines in it come back later in this lab. set_num_tasks(100) is R, the number of reduce tasks and output files. set_combiner_class("Adder") reuses the reduce class as a combiner. And set_machines(2000) caps the workers. The library passes strings to and from user code, which converts them to whatever types it needs.

Figure 1, run for real § 3.1 Execution Overview

One job, seven steps

Many implementations of the interface are possible: one for a small shared-memory machine, another for a large NUMA multiprocessor, another for a cluster. The paper’s targets Google’s environment in 2004, in five points. Machines are dual-processor x86 running Linux, with 2 to 4 GB of memory. Networking is commodity, 100 Mbit/s or 1 Gbit/s per machine, with far less bisection bandwidth overall. A cluster has hundreds or thousands of machines, so machine failures are common. Storage is inexpensive IDE disks attached to each machine, managed by the Google File System, which replicates for reliability. And users submit jobs to a cluster scheduling system, which maps each job’s tasks onto available machines.

Here is the whole flow, with word count running through it on three lines of text. Every pair in every box below comes out of actually running it.

Word count through Figure 1’s seven steps

Input splits
split 0the quick brown fox jumps over the lazy dog
split 1the dog barks and the fox runs
split 2a quick dog and a lazy fox
Map
map task 0idle
map task 1idle
map task 2idle
Intermediate, local
worker 0, local disknothing yet
worker 1, local disknothing yet
worker 2, local disknothing yet
Reduce
reduce task 0idle
reduce task 1idle
Output, in GFS
output file 0empty
output file 1empty
(1) Split the input

The library cuts the input into M = 3 splits, typically 16 to 64 MB each in real jobs (the user can change the size with an optional parameter), and starts copies of the program on the cluster. Here each split is one line of text.

§ 3.2 What the master keeps

For every map task and reduce task, its state (idle, in progress or completed) and, unless it is idle, which worker has it. And for every completed map task, the locations and sizes of its R intermediate regions. The master is the conduit through which those locations travel from map tasks to reduce tasks: it records them as map tasks complete and pushes them incrementally to the workers running reduce tasks, which is what lets the shuffle start before the map phase ends.

Who gets which key § 4.1 Partitioning Function · § 4.2 Ordering Guarantees

Every copy of a key meets in one place

The user chooses R, the number of reduce tasks and so of output files. The partitioning function decides which of them each intermediate key goes to. The default, hash(key) mod R, tends to give well-balanced partitions. Sometimes the keys need grouping some other way; the paper’s example is URLs that should be grouped by site. Here are twelve URLs from three hosts going into R = 4 files.

The same twelve keys, two partitioning functions

output file 0output file 1output file 2output file 3
example.com/about/blog/2//blog/1
news.site//world/tech/sport
shop.store/item/9/cart/item/7/
hash(key) mod R

Hashing the whole key spreads keys evenly over the files, which balances the reduce tasks. It also scatters each host across files. Files used per host: example.com 3, news.site 2, shop.store 4.

Within each partition, the intermediate pairs are processed in increasing key order. That makes it easy to produce a sorted output file per partition, which is handy when the output needs efficient lookups by key. The paper’s sort benchmark leans on both guarantees: its partitioning function uses the first bytes of the key, with built-in knowledge of the key distribution, so that the R sorted files concatenate into one sorted whole. A general sort would first run a sampling pass to choose the split points.

Saving the network § 4.3 Combiner Function

Add up before you send

Word frequencies follow a Zipf distribution, so every map task produces hundreds or thousands of (the, 1) records, and all of them travel over the network to the single reduce task that adds them up. The combiner does part of the reduce on the map worker before anything is sent. The only difference between the two is where the output goes: a combiner writes to the intermediate file, a reduce to the final output.

8 map tasks, 4 reduce tasks: records received

reduce task 04,460reduce task 11,260reduce task 21,529reduce task 3751
Every (word, 1) crosses the network

8 map tasks of 1,000 words each, drawn from a Zipf distribution, as real word frequencies are. Each emits 1,000 pairs, so 8,000 records, 47,041 bytes, cross the network to 4 reduce tasks. The word the alone is 1,555 separate (the, 1) records, all to one reduce task, which adds them up to 1,555.

The combiner cut the records crossing the network from 8,000 to 744. Notice the bars without it: one reduce task receives far more than the others, because it got the. Hashing balances the number of keys, not the number of values, and a combiner is one of the few things that evens that out.

Re-execution as the answer § 3.3 Fault Tolerance · § 4.6 Skipping Bad Records

When a machine dies, run its work again

A library meant for thousands of machines has to tolerate their failure. MapReduce’s answer is almost always the same: run the lost work again. That only works because the programming model is restricted. Map and reduce are expected to be deterministic functions of their input, so a second run produces the same thing as the first, and the only problem left is making sure exactly one of them counts.

Four failures

MasterWorker AWorker BReduce workerdead, its disk unreachablepingokpingrun map 3 againmap 3 doneread map 3 from BA marked failed
The master stops hearing from worker A

The master pings every worker periodically. When A stops answering, the master marks it failed and resets every map task A completed to idle, along with anything A had in progress: completed map output lives on A’s local disk, which nobody can reach now. Completed reduce tasks are safe, because their output is in the global file system.

Map task 3 runs again on B, and any reduce task that had not yet read its output from A reads it from B.

The paper’s own example is drastic: during one job, network maintenance made groups of 80 machines at a time unreachable for several minutes. The master re-executed their work and the job finished. When map and reduce are deterministic, the distributed run produces the same output as a non-faulting sequential run of the whole program, which is what makes the system easy to reason about.

Counters, without double counting

User code can create named counters, such as words processed or German documents indexed, and increment them in map or reduce. Workers piggyback the values on their ping responses, and the master aggregates them only from successful tasks, so a task that ran twice, for a backup or after a failure, is not counted twice. Users check sanity with them: output pairs equal to input pairs, a plausible share of German documents. Some counters the library keeps by itself, such as the number of input pairs processed and output pairs produced, and the master shows them live on its status page.

Side effects are yours to make safe

Some programs write extra files from map or reduce. The library leaves it to the application to make those atomic and idempotent, usually by writing a temporary file and renaming it. There is no two-phase commit across several output files of one task, so a task whose files must agree with each other should be deterministic. The paper says this has never been an issue in practice.

Beyond map and reduce § 4.4 Input and Output Types · § 4.7 Local Execution · § 4.8 Status Information

The rest of the toolkit

Map and reduce are enough for most needs, and the paper lists the extensions that turned out to be useful. Partitioning, ordering, the combiner, side effects, skipping bad records and counters are covered above. Three remain, and they are what made the library comfortable to use every day.

Input and output types

The library reads several formats. In text mode each line is a pair: the key is its offset in the file, the value its contents. Another format stores pairs sorted by key. Each input type knows how to split itself into ranges for map tasks, so text splits fall on line boundaries. A reader need not read a file: it can pull records from a database or from data structures in memory. Output types work the same way, and users can add either by implementing a small interface.

Local execution

Debugging map or reduce is hard when the work runs on thousands of machines and the master decides assignments on the fly. So there is a second implementation that runs the whole job sequentially on the local machine, with controls to limit it to particular map tasks. Run the program with a flag, and gdb or any other tool works on it.

Status information

The master runs an internal HTTP server with status pages: tasks completed and in progress, bytes of input, intermediate data and output, processing rates, and links to each task’s standard output and error. Users predict how long a job will take and whether to add machines. The top page shows which workers failed and which tasks they were running, which helps find bugs in user code.

The scarce resource § 3.4 Locality · § 3.5 Task Granularity

Move the computation to the data

Network bandwidth is the scarce resource in this environment, so the master schedules each map task on a machine that already holds a replica of its input block. GFS splits files into 64 MB blocks and keeps about three copies of each on different machines. Failing a local replica, the master picks a machine on the same network switch. Here is that rule on a model cluster of 60 machines in 3 racks, reading 600 blocks.

Where each map task’s input was read from

workers in the jobread from local disksame rackacross the network
6 of 6026%74%0%
15 of 6057%43%0%
30 of 6088%11%1%
60 of 6097%3%0%

A job using a sliver of the cluster reads most of its input from the same rack, because only 6 machines can be close to only so many replicas. A job using the whole cluster reads 97% of its blocks from local disk and almost none across the network, which matches the paper: when a large job runs on a significant fraction of the workers, most input is read locally and consumes no network bandwidth. The paper’s sort shows it too: its input rate beats its shuffle and output rates, because most input bypasses the network.

Many more tasks than machines

M and R should be much larger than the number of workers. Each worker then does many tasks, which balances the load dynamically, and a failed worker’s completed tasks spread over all the others when they rerun. A typical job ran with M = 200,000 and R = 5,000 on 2,000 machines. Splits are sized at 16 to 64 MB so that locality works best, and R is a small multiple of the workers.

What bounds it

The master makes O(M + R) scheduling decisions and keeps O(M × R) state: about one byte per pair of map and reduce task. At the typical job’s size that is 1.0 GB of master memory. R is also bounded by the users, because each reduce task produces its own output file.

The last few tasks § 3.6 Backup Tasks · § 5.4 · § 5.5

One slow machine can hold up a thousand

A straggler is a machine that takes unusually long on one of the last few tasks. Causes in the paper: a bad disk whose correctable errors cut reads from 30 MB/s to 1 MB/s, other jobs scheduled on the same machine, and once a bug that disabled processor caches and slowed machines by over a factor of one hundred. The fix is general: when the operation is close to completion, the master starts backup copies of the remaining in-progress tasks, and a task is done when either copy finishes. Google tuned it to cost no more than a few percent of extra computational resources.

The paper measures this on a sort of 1010 100-byte records, one terabyte, on about 1,800 machines (Figure 3). The model below is a much smaller cluster of 20 workers running 80 map tasks and 30 reduce tasks, but it runs the same three executions.

Figure 3’s three executions, as three runs of the model

050100w0w1w2w3w4slow w5w6w7w8w9w10w11w12w13w14slow w15w16w17w18w19done at 98
Normal execution, with backup tasks

Two machines are slow, as some always are in a big cluster. Backup tasks race the last tasks near the end, so the slow machines cannot hold the job up.

Model: done at 98. Paper: 891 seconds.

map taskreduce taskbackup copyovertaken, stoppedlost with a killed worker

In the paper, disabling backup tasks made the sort 44% slower: after 960 seconds all but 5 reduce tasks were done, and those stragglers took another 300. In the model it is 38%. Killing 200 of 1,746 workers cost the paper only 5%, and the model 5%: re-executing a few map tasks is cheap when there are thousands of them. Now try it yourself.

The job simulator

050100w0w1w2w3w4slow w5w6w7w8w9w10w11w12w13w14slow w15w16w17w18w19done at 98

map task reduce task backup copy overtaken, stopped lost with a killed worker

The job finishes at 98, against 90 for the same job on 20 healthy workers. 2 of the workers run 3 times slower, as a machine does with a failing disk or other jobs competing for it.

With backup tasks the job takes 98; without, it would take 135, 38% longer. 4 copies were overtaken and stopped, and the backups cost 9% more machine time than the work itself.

What it did at Google § 5 Performance · § 6 Experience

A terabyte in two and a half minutes

The paper measures two programs that stand for most real uses: one that hunts for a little data in a lot (grep), and one that rewrites a lot of data from one shape to another (sort). Both ran on a quiet weekend afternoon, on this cluster. Every number below is the paper’s or computed from it.

The test cluster, § 5.1

machinesabout 1,800
each machinetwo 2 GHz Xeons, 4 GB of memory (1 to 1.5 GB taken by other jobs), two 160 GB IDE disks, gigabit Ethernet
networktwo-level tree, 100 to 200 Gbit/s at the root, round trips under 1 ms

Grep: scan a terabyte

The job looks for a relatively rare three-character pattern in 10,000,000,000 records of 100 bytes, 1 TB; in 64 MB splits that is 14,901, which the paper rounds to M = 15,000, with R = 1. The scan peaks above 30 GB/s with 1,764 workers, about 17 MB/s each. It finds 92,337 matches. Figure 2 shows the scan rate climbing as more machines are assigned, peaking, then falling as map tasks finish, to zero about 80 seconds in. The whole job takes about 150 seconds, about a minute of it startup: copying the program to every worker, opening the 1,000 input files in GFS, and fetching the block locations that locality needs.

Sort: rewrite a terabyte

M = 15,000, R = 4,000, output written as two GFS replicas, so two terabytes out. The whole run takes 891 seconds, 16% faster than the best reported TeraSort result of the time, 1,057 seconds. The map side reads more slowly than grep did, because sort’s map tasks spend about half their time writing intermediate output to local disk.

The paper’s sort, second by second (Figure 3)

0 s200 s400 s600 s800 s1000 s1200 s(a) normal891 sall map tasks donefirst reduce batch doneshuffle donewrites done(b) no backup tasks1,283 sall but 5 reduce tasks done(c) 200 workers killed933 s

Input stops early because the input is read locally and fast, and every map task is done by 200 seconds. The shuffle starts with the first finished map task and comes in two humps: about 1,700 reduce tasks run first, one per machine, and the rest follow as those finish. Writing is the slowest stage because it stores 2 copies of everything (erasure coding, the paper notes, would be cheaper). Without backup tasks, the last 5 reduce tasks alone add 300 seconds.

August 2004, from Table 1

per job, on averagevalue
input read112 GB
intermediate data, as a share of input23%
output written, as a share of input6%
input per map task33 MB
worker machines, and deaths among them

157, 1.2

machine-days2.7
map tasks, and reduce tasks

3,351, 55

Across the month: 395 unique map implementations, 269 unique reduce implementations, and 426 unique combinations of the two; 3,288 TB read, 758 TB of intermediate data, 193 TB written, 79,186 machine-days. 29,423 jobs that month, each averaging 634 seconds. A worker died in the average job, and nobody had to do anything about it.

The first version of the library was written in February 2003, and August 2003 brought significant enhancements, including the locality optimization and dynamic load balancing across workers. From there it spread across Google: large-scale machine learning, clustering for Google News and Froogle, extracting data for reports of popular queries (Google Zeitgeist), extracting properties of web pages for new products such as geographic locations for localized search, and large-scale graph computations. Figure 4 counts separate MapReduce programs in Google’s main source tree: zero in early 2003, almost 900 by late September 2004. The authors credit the speed of the cycle: write a simple program and run it on a thousand machines within half an hour, even without any experience of parallel systems.

The largest use was a rewrite of the production indexing system for web search, a sequence of five to ten MapReduce operations over more than 20 terabytes of crawled documents. One phase shrank from about 3,800 lines of C++ to about 700, 82% less code, because fault tolerance, distribution and parallelization moved into the library. Conceptually unrelated computations could stay separate passes instead of being mixed together to save a pass over the data, so a change that took months in the old system took days. Slow machines, failures and network hiccups were handled without an operator, and performance improved simply by adding machines to the indexing cluster.

What it borrowed

MapReduce is a simplification and distillation of restricted parallel programming models such as parallel prefix computation, scaled to thousands of machines with fault tolerance. The locality optimization is inspired by active disks; backup tasks resemble eager scheduling in the Charlotte system, whose weakness, a task that fails repeatedly stalling the whole computation, skipping bad records partly fixes; the sort is similar to NOW-Sort. Bulk Synchronous Programming and some MPI primitives also raise the level of abstraction, but leave fault tolerance to the programmer. River balances work by carefully scheduling disk and network transfers; MapReduce instead cuts the job into many small tasks and races the last ones. BAD-FS shares redundant execution and locality-aware scheduling, across a wide-area network. TACC also relies on re-execution. The cluster manager underneath is similar in spirit to Condor.

Why it worked, and what the authors learned

They give three reasons for its success: the model is easy to use, even without experience of parallel and distributed systems, because it hides parallelization, fault tolerance, locality and load balancing; a large variety of problems fit it, from web search indexing to sorting, data mining and machine learning; and the implementation scales to clusters of thousands of machines and uses them efficiently. Then three lessons. First, restricting the programming model is what makes it easy to parallelize, distribute and make fault-tolerant. Second, network bandwidth is scarce, so locality, and writing a single copy of intermediate data to local disk, both exist to save it. Third, redundant execution handles slow machines, machine failures and data loss alike.

Recall check 12 questions

Did it stick?

One attempt per question; the explanation appears either way.

1. What are the types of the user’s map and reduce functions?

2. Where does a map task write its intermediate output?

3. Why are completed map tasks re-executed when their worker fails, but completed reduce tasks are not?

4. What does the partitioning function decide?

5. When is it safe to use the reduce function as a combiner?

6. In the combiner exhibit, how many records cross the network with the combiner, against how many without it?

7. What is a straggler, and what does MapReduce do about one?

8. Why should M and R be much larger than the number of workers?

9. How does the master save network bandwidth when scheduling map tasks?

10. What happens if the master fails?

11. What guarantees the output of a reduce task that ran twice contains one execution’s data?

12. Table 1 reports 3,288 TB of input and 758 TB of intermediate data in August 2004. Roughly what fraction of input became intermediate data?

Answered 0 of 12 · 0 correct

Vocabulary Click to flip

The terms this paper installs


The paper in one breath. Write map and reduce, and the library splits the input into M pieces, runs map tasks where the data already is, writes each task’s output to local disk in R regions by a hash of the key, lets reduce tasks fetch and sort their region from every map worker, and writes R output files to GFS. A combiner shrinks what crosses the network when reduce is commutative and associative. Faults are handled by running the work again: completed map tasks from a dead worker, in-progress tasks anywhere, and the last few tasks of a job as backup copies, which in the paper turned a 1,283-second sort into a 891-second one. Atomic commits of task output keep re-execution invisible, as long as map and reduce are deterministic. The restriction is the whole point: because programs are written this way, the system can parallelize them, place them, retry them and race them without the programmer knowing.

← all lab notes