MapReduce and Hadoop
MapReduce is a programming model for processing huge datasets on a cluster of ordinary machines. You write two small functions, a map that turns each input record into key-value pairs and a reduce that combines all the values for one key, and the framework handles everything else: splitting the input, running thousands of copies of your functions in parallel, moving data between them, and re-running the pieces that fail. Hadoop is the open-source ecosystem that grew up around it, with its own distributed file system (HDFS), resource manager (YARN), database (HBase) and SQL layer (Hive).
A few properties define the approach:
- A deliberately tiny programming model: every job is map, then group by key, then reduce. That's restrictive, but it means the framework can parallelize and retry any job without knowing anything about it.
- Move the computation to the data: input files are already spread across the cluster's disks, so the scheduler runs each map task on (or near) a machine that holds its piece of the input, instead of pulling terabytes over the network.
- Fault tolerance by re-execution: map and reduce functions are deterministic and side-effect free, so when a machine dies, its tasks just run again somewhere else.
- Disk-based and batch-oriented: intermediate data is written to local disk, final output to HDFS. It's slow by modern standards, but it scales to petabytes on cheap hardware.
You'll rarely propose classic MapReduce in a new design today; Spark, managed warehouses and object storage have taken over most of its jobs. But the ideas are everywhere. "Map, shuffle by key, reduce" is how you explain any distributed aggregation, HDFS is the template for a distributed file system question, HBase is the canonical wide-column store, and interviewers still ask "how would you build an inverted index for a billion pages?" expecting a MapReduce-shaped answer. This post covers the model, each of the main Hadoop components, and what replaced them.
The MapReduce Model
The classic example is counting words in a large collection of documents.
def map(doc_id, text):
for word in text.split():
emit(word.lower(), 1)
def reduce(word, counts): # all the counts for one word, from every mapper
emit(word, sum(counts))
Between the two functions, the framework does the part that actually makes this distributed: it collects every (word, 1) pair emitted anywhere in the cluster, groups the pairs by key, and delivers each key with all of its values to exactly one reducer. This middle step is the shuffle, and it's the same idea as a shuffle in Spark or a GROUP BY in a distributed database.
Two optional pieces make jobs practical:
- Combiner: a mini-reduce that runs on each mapper's output before the shuffle. For word count, the combiner sums the 1s locally, so a mapper sends
("the", 48,211)instead of 48,211 separate pairs. It works whenever the reduce function is associative and commutative (sums, counts, max), and it often cuts shuffle traffic by orders of magnitude. - Partitioner: decides which reducer gets each key. The default is
hash(key) mod R, where R is the number of reducers. A custom partitioner can keep related keys together or produce globally sorted output (range partitioning on sampled split points).
But what is actually happening under the hood?
Let's follow a job over 1 TB of text with 128 MB input blocks and 200 reducers.
- Input splits. The framework splits the input into about 8,000 pieces (1 TB / 128 MB = 8,192), one per HDFS block. Each split becomes one map task.
- Scheduling. The scheduler asks HDFS where each block lives and tries to run each map task on a machine that holds a replica of its block (data-local), or at least in the same rack.
- Map. Each map task reads its split, calls
mapfor every record and writes the output to an in-memory buffer (100 MB by default). - Spill, partition, sort. When the buffer fills up (80% by default), the task sorts the buffered pairs by partition and then by key, runs the combiner, and spills them to a file on local disk. At the end, it merges its spill files into one file per task, laid out as 200 sorted sections, one per reducer.
- Shuffle. Each reduce task fetches its section from every one of the 8,000 map outputs over HTTP. Reducers start fetching as soon as some maps finish, but they can't run
reduceuntil every map is done, because the very last map could still emit a key they own. - Merge and reduce. Each reducer merge-sorts its fetched sections, so all values for a key end up next to each other, then streams through them, calling
reduceonce per key. - Output. Each reducer writes its output to HDFS as a separate file (
part-00000topart-00199). Output goes to a temporary directory first and is renamed into place when the job commits, so readers never see half a result.
Notice how much disk I/O this involves. Map output is written to local disk, read back to serve the shuffle, written again by reducers while merging, and the final output is written to HDFS with three replicas. A pipeline of five MapReduce jobs writes its full intermediate result to HDFS four times. That's the main reason Spark, which keeps data in memory between steps and only writes at shuffles, is so much faster for multi-step work.
Classic MapReduce Patterns
Most batch problems can be bent into this shape. These come up in interviews:
- Inverted index: map each
(doc_id, text)to(term, doc_id)pairs; the shuffle groups by term; reduce sorts and compresses the list of doc IDs into a posting list. This is how web search indexes were originally built. - Counting and aggregation: page views per URL, clicks per ad per hour. Map emits
(key, 1)with a combiner; reduce sums. - Reduce-side join: to join orders with users, map both datasets to
(user_id, tagged_record); the reducer for eachuser_idreceives the user record and all of that user's orders and emits the joined rows. It works for any sizes but shuffles both datasets. - Map-side (broadcast) join: if one dataset is small, load it into memory in every mapper and join during the map, with no shuffle at all.
- Distributed sort: sample the keys to pick range boundaries, range-partition so reducer i gets the i-th key range, and concatenate the sorted outputs. This is how sort benchmarks like TeraSort work.
- Graph algorithms like PageRank: each iteration is one job (map sends rank contributions along outgoing edges, reduce sums them per page). Running 30 iterations means 30 full jobs with 30 writes to HDFS, which is exactly the workload where Spark's in-memory caching won.
When an interviewer asks you to process a dataset too large for one machine, it helps to state the computation as "map to (key, value), group by key, reduce" before naming any technology. It shows you know where the shuffle is and what the key is, and that's the decision that drives cost and skew. Whether you then run it on Spark, Flink, BigQuery or MapReduce is an implementation choice.
Fault Tolerance and Stragglers
The framework assumes machines fail all the time.
- Failed task: rerun on another machine, up to a few attempts (4 by default) before the job fails.
- Failed machine running map tasks: even completed map tasks on that machine are rerun, because their output lived on its local disk and reducers can no longer fetch it.
- Failed machine running reduce tasks: only unfinished reduce tasks rerun. Finished ones already wrote their output to HDFS, which is replicated.
- Stragglers: near the end of a job, a few tasks often run much slower than the rest (a failing disk, an overloaded machine). With speculative execution, the framework starts a backup copy of each slow task and uses whichever finishes first. This made a big difference to tail job times at large scale.
All of this relies on tasks being deterministic and idempotent. A map task that writes to an external database, or calls a random number generator without a fixed seed, can produce different or duplicated results when retried or speculated.