Module 2 ended with a confession: you have been using Spark as a black box. Before opening it, it is worth taking a step back, because Spark was born as a response to an earlier system, and almost all of its ideas are easier to understand once you know that one. The system is Hadoop, and its processing model is MapReduce.
The underlying question is easy to state: the web events of a single day at NovaMarket take up 7.6 GB spread in blocks across dozens of machines (lesson 02-01). How do you count how many events there are of each type without bringing all the data to a single computer? MapReduce was the first practical, general-purpose answer. In this lesson you will understand the model, simulate it in Python with no need for a cluster, see how Hadoop actually runs it and, above all, why it fell short. Those limitations are the starting point for the next lesson.
The problem: processing data that does not fit on one machine
On a single computer, counting events by type is trivial: you go through the file and keep a counter for each type. With the data spread across a cluster, three difficulties appear:
- Moving data is extremely expensive. Copying terabytes over the network to a central machine takes longer than the computation itself, and besides, they would not fit.
- Machines fail. With hundreds of nodes, one of them breaking down during a process that lasts hours is the norm, not the exception (lesson 01-04).
- Parallel programming is hard. Dividing up the work, coordinating processes, retrying whatever fails and bringing the results together is a job for specialists.
In 2004, Google published a paper describing how it solved these three difficulties in one go: MapReduce. Its contribution was a very clear division of responsibilities:
- The programmer writes just two small functions,
mapandreduce, thinking about one record or one key at a time. - The framework takes care of everything else: splitting the input, launching the tasks in parallel, moving the intermediate data, retrying whatever fails and collecting the output.
If a problem can be expressed with those two functions, it scales to thousands of machines without the programmer writing a single line of distributed code.
The MapReduce model: map, shuffle and reduce
MapReduce always works with key-value pairs and in three phases. The first and third phases are programmed by the user; the second is done by the framework.
| Phase | Who writes it | What it receives | What it produces |
|---|---|---|---|
| Map | The programmer | One input record (a line) | Zero or more (key, value) pairs |
| Shuffle & sort | The framework | All the pairs emitted by all the maps | The pairs grouped and sorted by key: (key, [values]) |
| Reduce | The programmer | A key and the list of all its values | One or more result pairs |
Let's apply it to Marc's question: how many events are there of each type?
- Map: for each event, emit the pair
(event_type, 1). In other words: "I have seen one of this type". - Shuffle & sort: the framework gathers all the ones for each type, whichever machine they come from.
- Reduce: for each type, add up its list of ones.
flowchart LR
subgraph Input[Input: blocks in HDFS]
B1[Block 1]
B2[Block 2]
B3[Block 3]
end
subgraph Map[Map phase: in parallel]
M1["map<br/>(purchase,1) (view,1) (view,1)"]
M2["map<br/>(view,1) (search,1)"]
M3["map<br/>(purchase,1) (view,1)"]
end
subgraph Shuffle[Shuffle and sort]
S1["purchase: [1,1]<br/>search: [1]"]
S2["view: [1,1,1,1]"]
end
subgraph Reduce[Reduce phase]
R1["reduce<br/>purchase 2, search 1"]
R2["reduce<br/>view 4"]
end
B1 --> M1
B2 --> M2
B3 --> M3
M1 --> S1
M1 --> S2
M2 --> S1
M2 --> S2
M3 --> S1
M3 --> S2
S1 --> R1
S2 --> R2
R1 --> O[Output in HDFS]
R2 --> O
Three ideas underpin the model:
- Map tasks are independent. Each one processes its block knowing nothing about the others; that is why they can run in parallel on as many machines as there are blocks, and why, if one fails, it is enough to repeat that one.
- The shuffle guarantees that all the values for a given key reach the same reduce. To decide which reduce task each pair goes to, a function is applied to the key (normally a hash): this is the partitioning by key from lesson 01-04.
- The shuffle is the expensive phase. It is the only one in which data travels over the network between machines. Remember this idea: it will reappear, under the same name, in Spark.
Many computations fit this mould by changing only the key and the value:
| Question | Key emitted by map | Value | What reduce does |
|---|---|---|---|
| Events by type | event_type |
1 |
Sum |
| Units sold by product | product_id |
quantity |
Sum |
| Maximum amount by channel | channel |
total_amount |
Maximum |
| Distinct sessions by device | device |
session_id |
Count distinct values |
A complete simulation in Python
None of the above needs a cluster to be understood. You are going to simulate the three phases in pure Python on the first 10,000 lines of web_events.json. Create ~/novamarket/simulated_mapreduce.py:
import json
from collections import defaultdict
from pathlib import Path
PATH = Path.home() / "novamarket" / "data" / "web_events.json"
NUM_LINES = 10_000 # sample size
NUM_CHUNKS = 4 # "blocks" the input is divided into
# ----------------------------------------------------------------------
# The two functions the programmer writes
# ----------------------------------------------------------------------
def map_function(line):
"""Receives a line and emits zero or more (key, value) pairs."""
event = json.loads(line)
yield (event["event_type"], 1)
def reduce_function(key, values):
"""Receives a key and ALL its values; emits the result."""
yield (key, sum(values))
# ----------------------------------------------------------------------
# What the framework does
# ----------------------------------------------------------------------
# 0. Input divided into chunks (in Hadoop, the HDFS blocks)
with open(PATH, encoding="utf-8") as f:
lines = [next(f) for _ in range(NUM_LINES)]
size = NUM_LINES // NUM_CHUNKS
chunks = [lines[i:i + size] for i in range(0, NUM_LINES, size)]
# 1. Map phase: one task per chunk, independent of one another
map_outputs = []
for chunk in chunks:
pairs = [pair for line in chunk for pair in map_function(line)]
map_outputs.append(pairs)
print("MAP - first pairs of chunk 0:", map_outputs[0][:4])
# 2. Shuffle & sort phase: gather the values for each key and sort
grouped = defaultdict(list)
for pairs in map_outputs:
for key, value in pairs:
grouped[key].append(value)
grouped = dict(sorted(grouped.items()))
for key, values in grouped.items():
print(f"SHUFFLE - {key}: list of {len(values)} ones")
# 3. Reduce phase: one call per key
print("REDUCE")
for key, values in grouped.items():
for final_key, total in reduce_function(key, values):
print(f" {final_key}\t{total}")What each part does
map_functionturns a line of text into a dictionary withjson.loadsand emits a single pair: the event type and a1. It usesyieldbecause, in general, a map can emit several pairs per record, or none at all (for example, to discard faulty lines).reduce_functionreceives a key with its complete list of values and returns the sum. It does not know where they come from or how many machines have been involved.- Step 0. The sample is divided into 4 chunks of 2,500 lines. They stand for the HDFS blocks: in a cluster, each one would be on a different machine.
- Step 1. A loop goes through the chunks and applies
map_functionto each line. Here it runs sequentially; in Hadoop, each pass of the loop would be a map task on a different node and they would all run at once. - Step 2. A dictionary gathers the values for each key and is then sorted by key. This is exactly what the shuffle does, except that in a cluster it involves sending data over the network.
- Step 3.
reduce_functionis called once per key.
Run it with the virtual environment activated:
MAP - first pairs of chunk 0: [('purchase', 1), ('product_view', 1), ('product_view', 1), ('product_view', 1)]
SHUFFLE - add_to_cart: list of 1038 ones
SHUFFLE - product_view: list of 7020 ones
SHUFFLE - purchase: list of 413 ones
SHUFFLE - search: list of 1529 ones
REDUCE
add_to_cart 1038
product_view 7020
purchase 413
search 1529The four totals add up to 10,000. Notice what does not appear in map_function or in reduce_function: no chunks, no machines, no network. That is the beauty of the model.
A classic optimisation: the combiner. Sending 7,020 ones over the network to add them up at the other end is a waste. MapReduce lets you apply a combiner function to the output of each map task before the shuffle: each chunk would then send its subtotal (
product_view, 1755) instead of its ones. It works when the operation can be applied piecewise without altering the result, as with a sum or a maximum; it is no direct use for an average.
Hadoop as a platform: HDFS, YARN and MapReduce
Google described MapReduce, but did not publish its code. Apache Hadoop, born in 2006, was the open-source implementation that put it within reach of any company. Its core has three pieces:
| Component | Role | Analogy |
|---|---|---|
| HDFS | Distributed storage | The cluster's disk |
| YARN | Resource management (CPU and memory) | The cluster's operating system |
| MapReduce | Processing engine | A program that runs on top of the other two |
You already know HDFS from lesson 02-01: files split into 128 MB blocks, distributed and replicated across the DataNodes, with the NameNode as the index. It is the file system MapReduce was designed for: each block of the input gives rise, in general, to one map task.
YARN: who hands out the resources
A cluster is shared by many processes at once. Someone has to decide how much memory and how many cores each one receives, and on which machines. That is the role of YARN (Yet Another Resource Negotiator), introduced in Hadoop 2:
- ResourceManager: the central arbiter. There is one per cluster; it knows the free resources on each node and allocates them to applications.
- NodeManager: an agent on each worker node. It launches and monitors the processes on its machine and reports to the ResourceManager.
- Container: a reserved slice of resources on a node (for example, 2 cores and 4 GB of memory) inside which a task runs. It has nothing to do with Docker containers: it is a YARN reservation unit.
- ApplicationMaster: a coordinating process for each application. It requests containers from the ResourceManager and distributes its job's tasks among them.
flowchart TB
C[Client: submits the job] --> RM[ResourceManager]
RM -->|allocates containers| NM1
RM -->|allocates containers| NM2
subgraph N1[Worker node 1]
NM1[NodeManager]
AM[Container:<br/>ApplicationMaster]
T1[Container:<br/>map task]
D1[(DataNode:<br/>blocks)]
end
subgraph N2[Worker node 2]
NM2[NodeManager]
T2[Container:<br/>map task]
T3[Container:<br/>reduce task]
D2[(DataNode:<br/>blocks)]
end
AM -.->|requests resources| RM
AM -.->|coordinates| T1
AM -.->|coordinates| T2
AM -.->|coordinates| T3
What matters about YARN is that it separated resource management from the processing engine. Thanks to that, a single Hadoop cluster can run MapReduce and other engines too, Spark among them.
Data locality
Notice in the diagram that each worker node hosts both a DataNode (which stores blocks) and a NodeManager (which runs tasks). That is no coincidence. Hadoop's design principle is:
It is cheaper to take the computation to the data than the data to the computation.
The code of a map takes up a few kilobytes; a block, 128 MB. So, when scheduling a map task, YARN tries to run it on a node that already holds a replica of the block it has to read. If it cannot, it tries another node in the same rack and, as a last resort, any other. This is data locality, and it explains why the map phase hardly uses the network.
The other side of the coin is that compute and storage are tied to the same machines: to gain computing capacity you also have to buy disks, and vice versa. In lesson 02-01 you saw that the cloud broke that tie.
A real job with Hadoop Streaming
MapReduce's native API is Java: a job is written with a Mapper class, a Reducer class and a main class that configures it, and is packaged in a JAR file. Even the simplest count runs to around sixty lines. We will not develop it here.
There is an alternative that is useful for learning: Hadoop Streaming, a utility included in Hadoop that lets you use as mapper and reducer any program that reads from standard input and writes to standard output. The contract is:
- The mapper receives lines on standard input and writes
key<TAB>valuepairs, one per line. - Hadoop sorts those lines by key (the shuffle & sort).
- The reducer receives the lines already sorted, so that all the lines for a given key arrive one after another.
Create the folder ~/novamarket/mapreduce/ and, inside it, mapper.py:
#!/usr/bin/env python3
"""Mapper: reads events (JSON Lines) and emits 'event_type<TAB>1'."""
import json
import sys
for line in sys.stdin:
line = line.strip()
if not line:
continue
event = json.loads(line)
print(f"{event['event_type']}\t1")And reducer.py:
#!/usr/bin/env python3
"""Reducer: receives 'key<TAB>value' SORTED by key and sums by key."""
import sys
current_key = None
total = 0
for line in sys.stdin:
key, value = line.rstrip("\n").split("\t")
if key != current_key:
if current_key is not None:
print(f"{current_key}\t{total}")
current_key = key
total = 0
total += int(value)
if current_key is not None:
print(f"{current_key}\t{total}")The mapper is straightforward. The reducer deserves attention, because it differs from the one in the simulation: here it does not receive a list per key, but a stream of sorted lines. So it remembers the key it is processing (current_key) and keeps accumulating; when the key changes, it knows the previous one has finished, prints its total and starts from zero. The final if prints the last key, which has no "next one" to trigger it. The advantage of this style is that the reducer never holds more than a counter in memory, even if a key has a billion values.
Testing it locally with pipes
The Streaming contract matches that of Unix pipes, so the job can be tested without Hadoop. The sort command plays the part of the shuffle:
cd ~/novamarket
head -n 10000 data/web_events.json | python mapreduce/mapper.py | sort | python mapreduce/reducer.pyThe same result as the simulation. If you replace head -n 10000 data/web_events.json with cat data/web_events.json, it processes the whole file and gives 21969, 140451, 8088 and 29992, the figures you checked in lesson 01-05 (the original file includes the 500 duplicates).
Try removing the sort from the pipeline as well: the reducer will print thousands of lines with repeated keys (purchase 1, product_view 4, search 1…), because it considers a key finished every time it changes. It is the best demonstration that the reducer depends on the order the shuffle guarantees.
Launching it on a cluster
On a Hadoop cluster, the same job would be submitted like this (an illustrative command: you do not have Hadoop installed and you do not need it for the course; the path to the JAR varies with the installation):
hadoop jar $HADOOP_HOME/share/hadoop/tools/lib/hadoop-streaming-*.jar \
-files mapreduce/mapper.py,mapreduce/reducer.py \
-mapper "python3 mapper.py" \
-reducer "python3 reducer.py" \
-input /novamarket/data/web_events.json \
-output /novamarket/output/events_by_type-filesdistributes the two scripts to every node that is going to run tasks.-mapperand-reducergive the command for each phase.-inputand-outputare HDFS paths, like those in lesson 02-01. The output directory must not exist: Hadoop refuses to overwrite results.
The result is not a file but a directory with one file per reduce task (part-00000, part-00001…) and an empty _SUCCESS file marking that the job finished properly. You have already seen that same structure in the Parquet folders Spark writes: it is a direct inheritance from Hadoop.
With the 7.6 GB of a real day of events, HDFS would have about 60 blocks and Hadoop would launch about 60 map tasks in parallel, each one next to its block.
The limitations of MapReduce
MapReduce delivered what it promised: processing petabytes on commodity machines and tolerating their failures. But day-to-day use brought serious shortcomings to light:
| Limitation | What it consists of | Consequence |
|---|---|---|
| Disk between phases | The output of each map is written to local disk, and that of each job to HDFS (with its three replicas) | Much of the time goes on reading and writing |
| Chaining jobs | A real computation is several MapReduce jobs in a row; each one reads from HDFS what the previous one wrote | A five-step analysis writes and rereads the data five times |
| Iterative algorithms | Machine learning repeats the same computation dozens of times over the same data | Each iteration reads it from disk again |
| High latency | Starting a job takes tens of seconds, however small it is | Unworkable for interactive queries |
| Verbosity | Everything has to be expressed as map and reduce | A join or a "top 10" takes a lot of code and craft |
| Batch only | It processes complete, closed datasets | It is no use for stream processing |
The join is a good illustration of the verbosity. The question "sales by category" requires joining order_lines with products. In MapReduce, that means the map reads both files, tags each record with its source and emits product_id as the key, and the reduce pairs up the records from one side with those from the other by hand; after that, a second job groups by category. In SQL it is four lines.
To ease this, tools emerged that translated SQL or high-level scripts into MapReduce jobs (they are introduced in lesson 06-01). They relieved the verbosity, but not the slowness, which was a consequence of the design: MapReduce was conceived when memory was expensive and scarce, which is why it rests everything on disk.
Around 2010, with memory far cheaper, a group at the University of California, Berkeley asked what would happen if the intermediate data were kept in memory and a multi-step computation were planned as a whole. The result was Apache Spark.
What remains relevant of Hadoop today
It would be a mistake to conclude that Hadoop "is dead". It is worth telling its pieces apart:
| Piece | Current situation |
|---|---|
| MapReduce as an engine | Practically abandoned for new developments; it survives in legacy processes. Spark and the SQL engines have replaced it |
| HDFS | Still in use in on-premise clusters; in the cloud, object storage has displaced it |
| YARN | Still current in existing Hadoop clusters as Spark's resource manager; in new deployments it competes with Kubernetes |
| The ideas | Fully current: divide and parallelise, tolerate failures by retrying tasks, data locality, the shuffle, thinking in keys and values |
| Formats and conventions | Parquet, ORC and Avro were born in this ecosystem; so were column=value partitioning and the part-* and _SUCCESS files |
Learning MapReduce today is not about writing MapReduce jobs, but about understanding what today's tools do under the bonnet. When, in the coming lessons, a Spark groupBy triggers a shuffle, you will know exactly what is happening and why it costs what it costs.
Common Mistakes and Tips
- Thinking the shuffle is a detail. It is the most expensive phase: it moves data over the network and sorts it. Anything that reduces the volume before the shuffle (filtering in the map, using a combiner) speeds up the job.
- Forgetting the
sortwhen testing a Streaming job locally. The reducer produces fragmented results. Without order there is no grouping. - Accumulating all the values for a key in a list in the reducer. With a very frequent key (skew, lesson 01-04), memory runs out. Process the stream value by value, as in
reducer.py. - Using a combiner with operations that do not allow it. The average of the averages is not the average. To compute it you have to carry the sum and the count separately and divide at the end.
- Confusing Hadoop with MapReduce. Hadoop is the platform (HDFS + YARN + MapReduce); MapReduce is only one of its engines, and today the least used.
- Confusing YARN containers with Docker containers. YARN's are resource reservations within a node.
- Tip: faced with any distributed computation, ask yourself "what is the key?". It is the question that organises MapReduce, and Spark, Kafka and the NoSQL databases as well.
Exercises
Exercise 1: designing map and reduce
Without writing any code, say which (key, value) pair the map would emit and what the reduce would do to answer these questions:
- How many orders are there in each status? (input:
orders.csv) - Which is the order with the highest amount in each channel? (input:
orders.csv) - How many events of type
purchasewere there per device? (input:web_events.json)
Exercise 2: events by device with Streaming
Write mapreduce/mapper_device.py to count events by device. Bear in mind that 1,000 events have a null device: emit them with the key unknown. Test it with the first 10,000 lines, reusing reducer.py unchanged.
Exercise 3: reasoning about the cluster
NovaMarket runs the count over the events of one month (30 days at 7.6 GB) in HDFS with 128 MB blocks.
- Roughly how many map tasks will be launched?
- One of the nodes shuts down halfway through the job. What happens?
- Broadly speaking, what volume would travel over the network in the shuffle with and without a combiner?
Solutions
Exercise 1
- Map emits
(status, 1); reduce sums. It is the same pattern as the event count. - Map emits
(channel, total_amount), or better(channel, (total_amount, order_id))so as to know which order it is; reduce keeps the maximum. It allows a combiner, because the maximum of the partial maxima is the global maximum. - Map filters: it only emits
(device, 1)whenevent_typeispurchase, and nothing otherwise; reduce sums. Filtering in the map is the most efficient option: whatever is not emitted does not travel in the shuffle.
Exercise 2
#!/usr/bin/env python3
import json
import sys
for line in sys.stdin:
line = line.strip()
if not line:
continue
event = json.loads(line)
device = event.get("device") or "unknown"
print(f"{device}\t1")head -n 10000 data/web_events.json | python mapreduce/mapper_device.py | sort | python mapreduce/reducer.pyThe expression event.get("device") or "unknown" returns the fallback text when the field is null (in Python, None). The reducer does not change: it sums values by key, whatever the key is. That kind of reuse is common in MapReduce.
Common mistake: printing event["device"] directly. Python would write the word None and the resulting key would be mistaken for a real value.
Exercise 3
- 30 × 7.6 GB = 228 GB. Divided by 128 MB per block, about 1,800 map tasks (with 1 GB = 1,024 MB it comes to 1,824).
- The ApplicationMaster detects that the tasks on that node are not responding and relaunches them on other nodes. The blocks they needed are still available in their other two replicas (replication factor 3). The job takes a little longer, but finishes properly and without human intervention.
- Without a combiner, one pair travels per event: 1,200 million pairs in a month. With a combiner, each map task sends at most 4 pairs (one per event type): about 7,300 pairs in total. The result is identical; the network traffic, hundreds of thousands of times smaller.
Conclusion
MapReduce solves distributed data processing with a very simple division of labour: the programmer writes a map function, which turns each record into key-value pairs, and a reduce function, which combines all the values for each key; the framework does the rest, including the shuffle & sort that takes each key to its destination and is the most expensive phase. Hadoop turned it into an open platform with three pieces: HDFS to store, YARN to share out the cluster's resources in containers and MapReduce to compute, all of it guided by data locality. You have checked this by simulating the three phases in Python and testing a Hadoop Streaming job with plain pipes.
You have also seen why the MapReduce engine has been left behind: it writes to disk between phases, chains several steps badly, is slow for iterative algorithms and interactive queries, and forces you to express everything with two functions. The ideas, by contrast, live on. In the next lesson, Apache Spark, you will finally open the black box you have been using since Module 2: you will see how Spark keeps data in memory, how it plans a complete computation before running it and how the count that took you two scripts here fits on one line.
