MapReduce - Word Count Example
ไ## "Hello World": Word Count
The Problem
Count how many times each word appears in a document
Map Function (Pseudocode)
Map(String docid, String text):
for each word w in text:
Emit(w, 1);Reduce Function (Pseudocode)
Reduce(String term, Iterator<Int> values):
int sum = 0;
for each v in values:
sum += v;
Emit(term, sum);Complete Example Walkthrough
Input text:
"hello world hello"
Step 1 - Map outputs:
(hello, 1)
(world, 1)
(hello, 1)
Step 2 - After shuffle (framework groups by key):
hello → [1, 1]
world → [1]
Step 3 - Reduce outputs:
(hello, 2)
(world, 1)
Simple Analogy: Like sorting candy by color, then counting each color pile. Map = putting each candy in its color pile. Reduce = counting candies in each pile.
Key Takeaways About MapReduce
1. Solves Parallel Processing Problem
Provides simple abstraction for complex distributed computing
2. Framework Handles Hard Parts
Automatically manages:
- Data distribution
- Fault tolerance
- Load balancing
- Synchronization
3. Programmers Focus on Business Logic
Just write map() and reduce() - framework does everything else
4. Scales Horizontally
Want to process more data? Just add more machines!
5. Fault-Tolerant by Design
If a machine dies, framework automatically re-runs failed tasks elsewhere
Final Orchestra Analogy: MapReduce is like conducting an orchestra. The conductor (framework) doesn't play instruments but coordinates all musicians (workers) to create beautiful music (processed data). Each musician only needs to know their own part (map/reduce function), not how to coordinate with everyone else.
Important Concepts and Clarifications
Batch Processing
- Processing accumulated data all at once
- Opposite of stream processing (handles data as it arrives)
- Example: Processing yesterday's logs vs. processing logs in real-time
Distributed File System (DFS)
- File system that stores data across multiple machines
- Provides redundancy and parallel access
- Examples: GFS (Google), HDFS (Hadoop)
Intermediate Data
- Output of map tasks that becomes input to reduce tasks
- Stored temporarily on local disks
- Gets shuffled and sorted before reduce
Shuffle and Sort
- Automatic process of:
- Grouping all values for same key together
- Sorting keys
- Delivering to correct reducers
Word Count Execution Flow Visual
Complete Example:
Input files:
File 1: "the quick brown fox"
File 2: "the fox ate the mouse"
File 3: "how now brown cow"
Map outputs (from all mappers):
(the, 1), (quick, 1), (brown, 1), (fox, 1)
(the, 1), (fox, 1), (ate, 1), (the, 1), (mouse, 1)
(how, 1), (now, 1), (brown, 1), (cow, 1)
After Shuffle & Sort (grouped by key):
ate → [1]
brown → [1, 1]
cow → [1]
fox → [1, 1]
how → [1]
mouse → [1]
now → [1]
quick → [1]
the → [1, 1, 1]
Final Output (after reduce):
(ate, 1)
(brown, 2)
(cow, 1)
(fox, 2)
(how, 1)
(mouse, 1)
(now, 1)
(quick, 1)
(the, 3)
Important Note: The 1 in (word, 1) is a counter, not the word position!
Library Analogy: MapReduce word count is like cataloging books. Map phase = different librarians scan sections and create cards for each word they find. Shuffle phase = collect all cards and sort by word. Reduce phase = count how many cards exist for each word to create the final catalog.
The Combiner Optimization
What is a Combiner?
A local mini-reducer that runs after map but before shuffle
Purpose: Reduce amount of data sent over network
Key requirement: Must work with associative operations like:
- Sum
- Count
- Max/Min
How Combiner Works
def combiner(key, values):
output(key, sum(values))Example: Word Count With vs. Without Combiner
Scenario: One mapper processes text with word "the" appearing 1000 times
Without combiner:
- Map outputs: 1000 pairs of (the, 1)
- Network transfer: 1000 key-value pairs
- Sent to reducer: (the, [1, 1, 1, ... 1000 times])
With combiner:
- Map outputs: 1000 pairs of (the, 1)
- Combiner locally sums: (the, 1000)
- Network transfer: 1 key-value pair
- Sent to reducer: (the, [1000])
Result: 1000× reduction in network traffic!
Visual: Combiner in Action
Without Combiner:
Mapper 1 outputs:
(the, 1), (fox, 1), (the, 1), (the, 1)
↓
Network: Send all 4 pairs
↓
Reducer receives: the → [1, 1, 1], fox → [1]
With Combiner:
Mapper 1 outputs:
(the, 1), (fox, 1), (the, 1), (the, 1)
↓
Combiner locally aggregates:
(the, 3), (fox, 1)
↓
Network: Send only 2 pairs
↓
Reducer receives: the → [3], fox → [1]
Real-World Impact: In production systems processing log files, combiners typically reduce network traffic by 50-90%. For a job processing terabytes of data, this saves hours of network transfer time!
Recycling Analogy: Combiner is like crushing aluminum cans before taking them to the recycling center. Instead of driving 100 full cans, you crush them into one bag. Same amount of aluminum, way less space, fewer trips!
Word Count Implementation (Python Style)
Simple Python-Like Pseudocode
def map(input_key, input_value):
# input_key: document name
# input_value: document contents
for word w in input_value:
EmitIntermediate(w, "1")
def reduce(output_key, intermediate_values):
# output_key: a word
# intermediate_values: a list of counts (all "1"s)
result = 0
for v in intermediate_values:
result += ParseInt(v)
Emit(AsString(result))Key Points:
- Map emits word with count of "1" (as string)
- Reduce sums all the "1" strings
- Framework handles everything between map and reduce
Practice Exercises
Exercise 1: Inverted Index
Problem: Create search engine index showing which documents contain each word
Input documents:
DocA: "cloud security cloud"
DocB: "security privacy"
DocC: "cloud privacy"
Goal: For each word, list which documents contain it (unique docs only)
Solution Process
Step 1 - Map Phase:
Emit (word, docID) for every word in every document
| Document | Emitted Pairs |
|---|---|
| DocA | (cloud, DocA), (security, DocA), (cloud, DocA) |
| DocB | (security, DocB), (privacy, DocB) |
| DocC | (cloud, DocC), (privacy, DocC) |
Step 2 - Shuffle/Group by Key:
Framework automatically groups same keys together
cloud → [DocA, DocA, DocC]
security → [DocA, DocB]
privacy → [DocB, DocC]
Step 3 - Reduce Phase:
Remove duplicate document IDs for each word
cloud → [DocA, DocC]
security → [DocA, DocB]
privacy → [DocB, DocC]
Step 4 - Final Output (Inverted Index):
cloud → {DocA, DocC}
security → {DocA, DocB}
privacy → {DocB, DocC}
Real-World Usage: This is exactly how Google builds its search index! When you search "cloud", it knows which web pages contain that word.
Exercise 2: Average Score per Student
Problem: Calculate average score for each student
Input data (student, score):
(Ann, 80)
(Bob, 70)
(Ann, 90)
(Bob, 100)
(Cat, 60)
Goal: Compute average score per student
Solution Process
Step 1 - Map Phase:
Emit (student, score) as-is (pass through)
Ann → 80
Bob → 70
Ann → 90
Bob → 100
Cat → 60
Step 2 - Shuffle/Group by Key:
Framework groups all scores for same student
Ann → [80, 90]
Bob → [70, 100]
Cat → [60]
Step 3 - Reduce Phase:
Calculate average for each student
Ann → (80 + 90) / 2 = 85
Bob → (70 + 100) / 2 = 85
Cat → 60 / 1 = 60
Step 4 - Final Output:
(Ann, 85)
(Bob, 85)
(Cat, 60)
Class Grade Analogy: Like calculating final course grades. Map = recording each quiz/exam score. Reduce = computing final average for each student.
More MapReduce Example Applications
MapReduce is versatile! Here are common use cases:
1. Distributed Grep (Text Search)
- Map: If line matches pattern, emit the line. Otherwise emit nothing.
- Reduce: Identity function (just pass through)
- Use case: Finding error messages in billions of log files
2. Count of URL Access Frequency
- Map: For each web request, emit (URL, 1)
- Reduce: Sum counts for each URL
- Use case: Finding most popular web pages
3. Reverse Web-Link Graph
- Map: For each link on page A to page B, emit (B, A)
- Reduce: Collect all pages linking to B
- Use case: Finding which pages link to your page (Google PageRank uses this!)
4. Inverted Index
- Map: For each word in document, emit (word, docID)
- Reduce: Collect list of documents for each word
- Use case: Search engines (shown in Exercise 1)
5. Distributed Sort
- Map: Extract sort key, emit (key, record)
- Reduce: Identity function
- Use case: Sorting petabytes of data
- Note: Shuffle phase does the actual sorting!
Grep Note:
grepis a command for searching text. Name = "globally search for regular expression and print matching lines"
MapReduce Infrastructure and Implementation
Google's Infrastructure (circa 2004)
Hardware Setup:
- Large clusters of commodity PCs (not expensive supercomputers!)
- Connected via switched Ethernet
- Typical machine:
- Dual-processor x86 CPUs
- Running Linux
- 2-4 GB RAM (considered a lot in 2004!)
- IDE hard drives
Design Philosophy:
- Use cheap commodity hardware in large quantities
- Assume failures will happen (machines die regularly)
- Software handles failures automatically
Storage: Google File System (GFS)
Key Characteristics:
-
Files divided into chunks
- Typically 64 MB per chunk (large!)
-
Replication for reliability
- Each chunk stored on 3 different machines
- Provides fault tolerance and availability
-
Distributed across cluster
- Data spread across hundreds/thousands of machines
Scheduling System
How jobs run:
- Users submit jobs to cluster
- Each job contains multiple tasks (map and reduce)
- Master scheduler assigns tasks to available worker machines
- Workers execute tasks and report back to master
Visual:
User → Submit Job → Master Scheduler
↓
Assign Tasks
↓
┌──────────┼──────────┐
↓ ↓ ↓
Worker 1 Worker 2 Worker 3
Factory Analogy: Think of MapReduce like a factory. Master = factory manager assigning work orders. Workers = assembly line stations. GFS = warehouse storing parts across multiple buildings for safety.
Google File System (GFS) Deep Dive
GFS Architecture Components
1. Master Server
- One master (with replicated backups for fault tolerance)
- Stores all file system metadata
- Manages chunk locations
- Coordinates all file system operations
2. Chunk Servers
- Hundreds to thousands of chunk servers
- Each stores actual file data (chunks)
- Spread across different racks in data center
- Note: Intra-rack bandwidth > Inter-rack bandwidth (faster within same rack)
3. Chunks
- Files divided into 64 MB chunks
- Each chunk has globally unique 64-bit ID
- Each chunk replicated 3 times on different chunk servers
4. Clients
- Applications that read/write files
- Communicate with master for metadata
- Communicate directly with chunk servers for data
GFS Design Assumptions
What GFS optimizes for:
-
Failures are normal, not exceptional
- Detect, tolerate, and recover automatically
- Machines and disks fail regularly
-
Large files (>= 100 MB)
- Not optimized for many tiny files
-
Large streaming reads (>= 1 MB)
- Read data sequentially, often only once
- Don't seek around file randomly
-
Large sequential writes that append
- Write data once at end of file
- Rarely overwrite existing data
-
Concurrent appends by multiple clients
- Many producers writing to same file simultaneously
- Need atomicity without complex synchronization
Atomic: Operation either completely succeeds or completely fails, no partial states
How GFS Actually Works
Client Read Operation
Steps:
- Client → Master: "I want to read file X at byte offset Y"
- Master → Client: "Here's the chunk_handle and locations (chunk servers that have this chunk)"
- Client caches this information temporarily
- Client → Nearest Chunk Server: "Send me chunk_handle data"
- Chunk Server → Client: Sends actual file data
Why this is efficient:
- Client only contacts master once for metadata
- Then reads directly from chunk server (no master bottleneck)
- Client picks nearest chunk server (minimizes network latency)
Client Write Operation
Steps:
- Client → Master: "Where should I write this data?"
- Master → Client: "Write to these 3 chunk servers (chunk_handle + locations)"
- Client → All 3 Chunk Servers: Sends data simultaneously
- Chunk servers coordinate among themselves to ensure consistency
- Important: Must ask master again when crossing 64 MB boundary (new chunk)
Why 3 chunk servers?
- Data survives even if 2 machines fail
- Balance between reliability and storage cost
- Can serve reads from 3 different locations (load balancing)
GFS Architecture Visual
┌─────────────┐
│ Master │ (One, with backups)
│ (Metadata) │
└─────────────┘
↑
┌───────────┼───────────┐
↓ ↓ ↓
┌──────────┐ ┌──────────┐ ┌──────────┐
│ Chunk │ │ Chunk │ │ Chunk │
│ Server 1 │ │ Server 2 │ │ Server 3 │
└──────────┘ └──────────┘ └──────────┘
↑ ↑ ↑
└───────────┴───────────┘
↑
┌─────────┐
│ Client │
└─────────┘
Master Server Responsibilities
Metadata it stores (all in RAM for speed):
- File namespace (directory hierarchy)
- Access control information per file
- Mapping: files → chunks
- Current locations of all chunks
Operations it performs:
- Manages consistency across replicas
- Garbage collects orphaned chunks (cleanup)
- Migrates chunks between servers (load balancing)
- Makes placement decisions for new chunks
Key optimization: All metadata in RAM → extremely fast lookups
Client Behavior in GFS
Client Characteristics
What clients do:
- Send metadata requests to master server
- Send data requests directly to chunk servers
- Cache metadata locally
- Do NOT cache data itself
Why no data caching?
- No consistency problems between clients
- Files are huge - caching doesn't help much
- Streaming reads (read once) don't benefit from cache
- Append writes (write once) don't benefit from cache
Client Read Process (Detailed)
Step-by-step:
-
Client:
read(file_name, chunk_index) -
Master replies:
- Chunk ID
- Chunk version number (for consistency)
- List of replica locations
-
Client picks "closest" chunk server
- "Closest" = same rack if possible (faster network)
- Determined by IP address and network topology
-
Client → Chunk Server:
read(chunk_ID, byte_range) -
Chunk Server → Client: Returns actual data
Efficiency note: Client caches metadata, so doesn't need to contact master for every read!
GFS Write Operations
Replica Placement Strategy
Why 3 replicas?
- 2 copies on same rack (fast access to each other)
- 1 copy on different rack (survives rack failure)
This balances:
- Access time: Most reads can stay within rack
- Safety: If whole rack fails, data still exists elsewhere
Visual:
Rack 1 Rack 2
┌──────────┐ ┌──────────┐
│ Replica 1│ │ Replica 3│
└──────────┘ └──────────┘
┌──────────┐
│ Replica 2│
└──────────┘
Home Backup Analogy: Like keeping important documents. 2 copies in your office (same rack = fast access). 1 copy at home in safe (different rack = survives office fire).
Atomic Record Appends
The problem: Multiple clients want to append to same file simultaneously
GFS solution:
Step 1: Client pushes data to all replicas
Step 2: Client sends append request to primary replica
Step 3: Primary checks if record fits in current chunk
- If YES: Writes data, tells other replicas to write at same offset
- If NO: Pads current chunk, tells client to retry with new chunk
Step 4 - If any replica fails:
- Client retries entire operation
- May result in duplicates or inconsistencies
- Application must handle this!
On success: Data written to all replicas at exact same position
Important: Applications using GFS must be designed to handle potential duplicate records or inconsistencies!
MapReduce Parallel Execution
User Specifies Parallelism Level
When submitting MapReduce job, user specifies:
- M: Number of map tasks
- R: Number of reduce tasks
Want high parallelism? → Specify large M and R!
Map Phase Parallelism
How it works:
- MapReduce library splits input file into M pieces
- Typical split size: 16-64 MB per piece
- Each piece becomes one map task
- Map tasks distributed across available machines in cluster
- Many map tasks run simultaneously in parallel
Example:
- 1 TB input file
- Split into 64 MB pieces
- M = 16,000 map tasks
- Run 2000 at a time on 2000 machines
Reduce Phase Parallelism
How partitioning creates parallelism:
- Intermediate key space divided into R pieces
- Default:
- Each partition becomes one reduce task
- R reduce tasks assigned to different machines
- All reducers run in parallel
Example:
- R = 5000 reduce tasks
- Intermediate keys partitioned into 5000 groups
- 5000 machines each process one group
Typical Production Settings
Example configuration:
- Cluster: 2,000 machines
- M (map tasks): 200,000
- R (reduce tasks): 5,000
Why so many tasks?
- Much more tasks than machines
- Load balancing: If one machine is slow, others pick up slack
- Fault tolerance: Easy to reschedule failed tasks
- Flexibility: Tasks are small units of work
Restaurant Analogy: Like having 200,000 orders (M) cooked by 2,000 chefs, then 5,000 delivery routes (R) handled by 2,000 delivery drivers. More orders than workers = better work distribution, no one sits idle.
MapReduce Execution Flow (Complete Picture)
Full Execution Steps
Step 1: User program forks Master process
- One master coordinates everything
Step 2: Master assigns tasks to workers
- Some workers get map tasks
- Some workers get reduce tasks
- Assignment based on data locality when possible
Step 3: Map workers read assigned input splits
- Each worker reads its assigned piece of input file
Step 4: Map phase executes
- Workers run user's map() function
- Produce intermediate key-value pairs
Step 5: Intermediate data written to local disks
- Partitioned into R regions
- NOT written to distributed file system (just local disk)
Step 6: Master tells reduce workers where intermediate data is
Step 7: Reduce workers read intermediate data
- Read remotely from map workers' local disks
- Sort by key (shuffle phase)
Step 8: Reduce phase executes
- Workers run user's reduce() function
- For each unique key, process all its values
Step 9: Final output written to distributed file system
- R output files produced (one per reduce task)
Key Phases Visual
Input Files (on HDFS)
↓
Split 0, Split 1, Split 2, Split 3, Split 4
↓
MAP PHASE (parallel on many workers)
↓
Intermediate Files (on local disks)
↓
SHUFFLE & SORT
- Read remote data
- Group by key
- Sort by key
↓
REDUCE PHASE (parallel on many workers)
↓
Output Files (on HDFS)
Important locations:
- Input files: Distributed file system (HDFS/GFS)
- Intermediate files: Local disks (not distributed FS!)
- Output files: Distributed file system (HDFS/GFS)
Why intermediate on local disks?
- Temporary data
- Faster to write locally
- Reduces network traffic
- If machine fails, just recompute (don't need permanent storage)
HDFS-MapReduce Integration
How They Work Together
HDFS provides:
- Distributed storage for input files
- Distributed storage for output files
- Data locality information (which machine has which data)
MapReduce uses HDFS to:
- Read input splits from where they're stored
- Write final output back to HDFS
- Schedule map tasks near their input data
Data Flow Visual
Input Files (stored on HDFS)
↓
Split into chunks
↓
┌────────┼────────┐
Split 0 Split 1 Split 2 Split 3 Split 4
↓ ↓ ↓ ↓ ↓
MAP MAP MAP MAP MAP
↓ ↓ ↓ ↓ ↓
Intermediate key-value pairs
↓
SHUFFLE & SORT
- Send data across network
- Group by key
- Sort keys
↓
Key-1: [values]
Key-2: [values]
Key-3: [values]
↓
┌─────┼─────┐
REDUCE REDUCE REDUCE
↓ ↓ ↓
Output Files (stored on HDFS)
Intermediate Files (on local disks):
- Not stored in HDFS
- Temporary working data
- Deleted after job completes
Warehouse Analogy: HDFS = main warehouse storing inventory. MapReduce workers = delivery trucks. Intermediate files = temporary loading docks. Input/output in main warehouse, but sorting/processing happens at temporary docks.
Word Count MapReduce: Complete Visual Example
Input Text
"Deer Bear River Car Car River Deer Car Bear"
Step 1: Splitting
Framework splits into 3 parts for 3 mappers:
Mapper 1: "Deer Bear River"
Mapper 2: "Car Car River"
Mapper 3: "Deer Car Bear"
Step 2: Mapping
Each mapper emits (word, 1) pairs:
Mapper 1 output:
(Deer, 1)
(Bear, 1)
(River, 1)
Mapper 2 output:
(Car, 1)
(Car, 1)
(River, 1)
Mapper 3 output:
(Deer, 1)
(Car, 1)
(Bear, 1)
Step 3: Shuffling
Framework groups all values for same key:
Bear → [1, 1]
Car → [1, 1, 1]
Deer → [1, 1]
River → [1, 1]
Step 4: Reducing
Each reducer sums values for its keys:
Bear → 2
Car → 3
Deer → 2
River → 2
Step 5: Final Output
List of (Key, Value) pairs:
(Bear, 2)
(Car, 3)
(Deer, 2)
(River, 2)
Counting Votes Analogy: Like counting election votes. Split ballots among counters (map), each counter tallies their stack, central office collects all tallies for same candidate (shuffle), final tally computed (reduce).
Combiner in Action - Visual Example
Without Combiner
Input: "Deer Bear River Car Car River Deer Car Bear"
↓
MAPPING (3 mappers)
↓
Mapper outputs (9 pairs total):
(Deer,1) (Bear,1) (River,1)
(Car,1) (Car,1) (River,1)
(Deer,1) (Car,1) (Bear,1)
↓
SHUFFLING (send all 9 pairs over network)
↓
Bear(1,1), Car(1,1,1), Deer(1,1), River(1,1)
↓
REDUCING
↓
Bear:2, Car:3, Deer:2, River:2
Network traffic: 9 key-value pairs sent
With Combiner
Input: "Deer Bear River Car Car River Deer Car Bear"
↓
MAPPING (3 mappers)
↓
Mapper 1: (Deer,1) (Bear,1) (River,1)
↓ COMBINER (local reduce)
Mapper 1: (Deer,1) (Bear,1) (River,1)
Mapper 2: (Car,1) (Car,1) (River,1)
↓ COMBINER (local reduce)
Mapper 2: (Car,2) (River,1)
Mapper 3: (Deer,1) (Car,1) (Bear,1)
↓ COMBINER (local reduce)
Mapper 3: (Deer,1) (Car,1) (Bear,1)
↓
SHUFFLING (send only 7 pairs over network)
↓
Bear(1,1), Car(2,1), Deer(1,1), River(1,1)
↓
REDUCING
↓
Bear:2, Car:3, Deer:2, River:2
Network traffic: 7 key-value pairs sent
Savings: 22% reduction in this small example. In real jobs with billions of records, savings can be 80-90%!
Packaging Analogy: Without combiner = ship each item individually. With combiner = bundle items in same box before shipping. Same items delivered, much less shipping cost!
Movie Ratings MapReduce Example
The Problem
Given user movie ratings, count how many times each rating appears
Input Data Format
USER_ID | MOVIE_ID | RATING | TIMESTAMP
196 242 3 881250949
186 302 3 891717742
196 377 1 878887116
244 51 2 880606923
166 346 1 886397596
186 474 4 884182806
186 265 2 881171488
Step 1: Map Phase
Extract rating and emit (rating, 1):
3 → 1
3 → 1
1 → 1
2 → 1
1 → 1
4 → 1
2 → 1
Step 2: Shuffle & Sort
Group by rating:
1 → [1, 1]
2 → [1, 1]
3 → [1, 1]
4 → [1]
Step 3: Reduce Phase
Count occurrences:
1 → 2
2 → 2
3 → 2
4 → 1
Python Implementation
def mapper_get_ratings(self, _, line):
(userID, movieID, rating, timestamp) = line.split('\t')
yield rating, 1
def reducer_count_ratings(self, key, values):
yield key, sum(values)Complete MRJob Program
from mrjob.job import MRJob
from mrjob.step import MRStep
class RatingsBreakdown(MRJob):
def steps(self):
return [
MRStep(mapper=self.mapper_get_ratings,
reducer=self.reducer_count_ratings)
]
def mapper_get_ratings(self, _, line):
(userID, movieID, rating, timestamp) = line.split('\t')
yield rating, 1
def reducer_count_ratings(self, key, values):
yield key, sum(values)
if __name__ == '__main__':
RatingsBreakdown.run()Result: Histogram showing distribution of ratings (how many 1-star, 2-star, 3-star, etc.)
Master's Data Structures
What Master Tracks
For each Map/Reduce task:
-
State status:
idle(not started yet)in-progress(currently running)completed(finished successfully)
-
Worker machine identity:
- For non-idle tasks: which machine is running it
- For idle tasks: not assigned yet
How Information Flows
Critical job of master:
- Track location of intermediate file regions produced by completed map tasks
- Push this location information to reduce workers incrementally
- Don't wait for all maps to finish
- Send info as each map completes
- Reduces waiting time for reducers
Example flow:
Map Task 1 completes
↓
Master records: "Intermediate data on Machine A"
↓
Master tells Reducer 1: "Read from Machine A"
↓
Reducer 1 starts reading while other maps still running
Package Tracking Analogy: Master = postal service tracking system. Tracks each package status (idle/in-transit/delivered) and tells recipients where to pick up their packages as soon as they arrive, doesn't wait for all packages to be delivered.
Fault Tolerance
MapReduce automatically handles two types of failures:
1. Worker Failures
How master detects failures:
- Master sends periodic heartbeat messages to workers
- If no response within timeout → worker is dead
How master recovers from worker failure:
For map tasks:
- In-progress map tasks → reset to
idle, reschedule on different machine - Completed map tasks → reset to
idle, reschedule on different machine
For reduce tasks:
- In-progress reduce tasks → reset to
idle, reschedule on different machine - Completed reduce tasks → do nothing (output already in distributed FS)
Why re-run completed map tasks?
- Map output stored on local disk of worker machine
- If machine dies, local disk data is lost!
- Must recompute to regenerate intermediate data
Why NOT re-run completed reduce tasks?
- Reduce output stored in distributed file system (GFS/HDFS)
- Replicated across multiple machines
- Survives individual machine failure
Notifications:
- Workers running reduce tasks are notified if their input map tasks are rescheduled
- They'll read from new location
2. Master Failure
How it's handled:
- Master failure is rare (only one master vs thousands of workers)
- Can recover from periodic checkpoints
- Common solution: Abort entire MapReduce job and restart from beginning
Why rare is acceptable:
- With only one master, failure probability is low
- Restarting entire job is acceptable for rare event
- Simpler than complex master recovery
Factory Analogy: Worker failure = assembly line worker gets sick → manager assigns their work to someone else. Completed assemblies stored in warehouse (distributed FS) are safe. Work-in-progress on failed worker's desk must be redone. Manager failure = extremely rare, factory temporarily shuts down and restarts.
Data Locality Optimization
The Problem
Network bandwidth is expensive:
- Limited resource in data center
- Increases latency
- Can become bottleneck with petabytes of data
Goal: Minimize data movement over network
The Solution: Move Computation to Data
Instead of: Moving terabytes of data to where computation is
Do this: Move small computation programs to where data already is
How It Works with GFS/HDFS
GFS/HDFS stores 3 copies of each data block on different machines
MapReduce master schedules map tasks:
-
Best case: Schedule on machine that has input data locally
- Zero network transfer!
- Read from local disk
-
Good case: Schedule on machine in same rack as data
- Small network transfer within rack
- Intra-rack bandwidth is high
-
Acceptable case: Schedule on machine in different rack
- Must transfer over network
- Only used when no better option
Result: Most map tasks read input from local disk, avoiding network entirely!
Visual Example
Data Block X stored on: Machine 1, Machine 5, Machine 7
Master scheduling map task for Block X:
1. Try Machine 1 → Available? → Schedule there! (local)
2. Machine 1 busy → Try Machine 5 → Available? → Schedule there!
3. Both busy → Try Machine 7 → Available? → Schedule there!
4. All 3 busy → Try nearby machine in same rack
5. Rack full → Use machine in different rack
Library Analogy: Instead of having librarians walk to central office to get books, then walk back to read them (expensive, slow), give each librarian books already at their desk. Much faster! Only walk to get books when absolutely necessary.
Impact: At scale, data locality reduces network traffic by 90%+ in typical MapReduce jobs!
Task Granularity
What is Granularity?
Granularity = Number of tasks relative to number of worker machines
Goal: Have MORE tasks than workers
Why More Tasks Than Workers?
Benefits:
-
Better load balancing
- If one worker finishes early, it can pick up more tasks
- Keeps all workers busy (no idle machines)
-
Better recovery from failures
- Failed task is smaller unit of work
- Faster to re-run small task than large task
- Other workers can help complete failed worker's tasks
-
Better handling of stragglers
- Can reassign tasks from slow workers
Example:
- 100 workers
- 10,000 map tasks
- Average: 100 tasks per worker
- Fast worker might do 120 tasks, slow worker does 80
- All finish around same time
The Tradeoff
BUT having too many tasks increases master overhead:
- More scheduling decisions
- More state to track
- More memory usage
- More coordination
Master must track: M + R tasks and worker states
Choosing M and R
M (number of map tasks):
- Choose based on input file block size
- Typical: 16-64 MB per map task
- Example: 1 TB file, 64 MB blocks → M = 16,384
R (number of reduce tasks):
- Usually specified by user
- Consider: Each reduce task produces one output file
- Too few R → each output file is huge
- Too many R → too many small files
Typical values:
- M = much larger than number of workers (10x - 100x)
- R = smaller multiple of workers (1x - 2x)
Example production setting:
- 2,000 worker machines
- M = 200,000 (100x workers)
- R = 5,000 (2.5x workers)
Restaurant Analogy: Task granularity is like portion sizes. Many small portions (high granularity) = easier to distribute work evenly among diners, easier to share if someone eats slowly. But too many tiny portions = waiter spends all time coordinating instead of serving.
The Straggler Problem
What are Stragglers?
Straggler = A machine that takes unusually long time to complete one of the last few tasks
Problem: One slow task delays entire job completion
- Job only completes when ALL tasks finish
- Last 1% of tasks can take as long as first 99%
Why Do Stragglers Happen?
Common causes:
-
Bad disk with soft errors
- Disk works but reads slowly
- Correctable errors slow down reads
-
Other processes using resources
- Another program competing for CPU/memory/disk
- Reduces resources available for MapReduce
-
Machine configuration problems
- Older/slower hardware in heterogeneous cluster
- Network issues
- Cache disabled
-
Simply bad luck
- Random performance variations
Solution: Backup Tasks
How it works:
-
Job is close to completion (e.g., 95% done)
-
Master identifies in-progress tasks that haven't finished
-
Master schedules backup executions of these tasks
- Run same task on different machine
- Both primary and backup run simultaneously
-
Task marked complete when EITHER finishes
- Whichever finishes first wins
- Other execution is killed
Example:
Task 1234 running on Machine A (slow, straggling)
↓
Master notices Task 1234 taking too long
↓
Master starts backup of Task 1234 on Machine B
↓
Machine B finishes first
↓
Task 1234 marked complete, Machine A execution killed
Impact of Backup Tasks
Google's measurement:
- Sort operation with backup tasks: 960 seconds
- Sort operation WITHOUT backup tasks: 1,283 seconds
- Difference: 44% longer without backup tasks!
In production:
- Backup tasks typically add <10% extra computation
- But reduce job completion time by 30-40%
- Great tradeoff!
Race Analogy: Like marathon runners. When race is almost over, you're waiting for the last few runners to finish. Backup tasks = having each slow runner race against a backup runner. Whoever crosses finish line first counts. Ensures one slow runner doesn't delay the entire race results.
Production Insight: At Netflix scale, backup tasks reduced job completion time by 30-40%. The small cost of running duplicate tasks is worth avoiding delays from stragglers.
Refinements: Custom Partitioning Function
Review: What is Partitioning?
Partition function decides which reducer handles which keys
Default Partitioning
Where R = number of reducers
Works well for most cases - distributes keys evenly
Why Custom Partitioning?
Sometimes default partitioning isn't optimal:
- Domain-specific knowledge can improve distribution
- Related keys should go to same reducer for efficiency
- Balance load better for skewed data
Example: URL Processing
Problem: Processing web logs where keys are URLs
Bad default partitioning:
hash("http://example.com/page1") mod R
hash("http://example.com/page2") mod R
hash("http://other.com/page1") mod R
Result: URLs from same website scattered across different reducers
Good custom partitioning:
hash("example.com") mod R → All example.com URLs to same reducer
hash("other.com") mod R → All other.com URLs to same reducer
Benefits:
- All URLs from same website processed together
- Can do per-website analytics
- Better for sorting by website
- More efficient reduce operations
When to Use Custom Partitioning
Use custom partition function when:
- You want related keys grouped together
- Default hash creates imbalanced load
- Domain knowledge suggests better grouping
Examples:
- URLs → partition by hostname
- Timestamps → partition by date/hour
- User IDs → partition by geographic region
- IP addresses → partition by subnet
Mail Sorting Analogy: Default partitioning = sorting mail by random hash of full address. Custom partitioning = sorting by ZIP code or city first. Much more efficient because related addresses stay together!
Refinements: Combiner Function (Deep Dive)
Purpose of Combiner
Combiner = Mini-reduce that runs locally after map phase
Goal: Reduce network traffic before shuffle phase
When to Use Combiners
Use combiner when:
- Significant repetition of intermediate keys
- Associative and commutative operations
- Can apply operation multiple times
- Order doesn't matter
Good examples:
- Sum (word count)
- Count
- Max/Min
- Multiplication
Bad examples:
- Median (not associative)
- Average (requires count + sum, not just one value)
Combiner Properties
Must have same signature as reducer:
- Input: (key, list of values)
- Output: (key, reduced value)
Often combiner = same code as reducer!
- Example: For sum operation, combiner and reducer do the same thing
Example: Word Count with Combiner
Without combiner:
Mapper 1 processes 1000 lines
Outputs 50,000 pairs: (word, 1) for each word
Network sends 50,000 pairs
With combiner:
Mapper 1 processes 1000 lines
Outputs 50,000 pairs: (word, 1)
Combiner locally aggregates:
"the" appears 2000 times → (the, 2000)
"and" appears 1500 times → (and, 1500)
...500 unique words total
Network sends 500 pairs instead of 50,000!
Network savings: 99% reduction!
Visual: Data Flow with Combiner
MAP OUTPUT (large)
100,000 (word, 1) pairs
↓
COMBINER (local aggregation)
↓
COMBINER OUTPUT (small)
1,000 (word, count) pairs
↓
NETWORK TRANSFER (reduced!)
↓
SHUFFLE & SORT
↓
REDUCE
↓
FINAL OUTPUT
Real-World Impact: In log processing systems at scale, combiners typically reduce intermediate data by 80-95%. For a job processing 10 TB, combiner might reduce network transfer to 500 GB. Saves hours of network transfer time!
Supermarket Analogy: Without combiner = customers bring each item to checkout separately (100 trips for 100 items). With combiner = customers use shopping cart to collect all items first, then one trip to checkout. Same items purchased, much less walking!
Modern MapReduce Evolution and Cloud Services
Evolution of MapReduce
Traditional MapReduce (Hadoop) limitations:
- Disk-based (slow)
- Batch processing only
- High latency
Modern alternatives (based on MapReduce principles):
1. Apache Spark
- In-memory processing (100x faster than Hadoop)
- Still uses map-reduce-like operations
- Better for iterative algorithms (machine learning)
- Example: Netflix uses Spark for real-time recommendations
2. Apache Flink
- Stream processing with batch capabilities
- Low-latency real-time analytics
- Example: Uber uses Flink for real-time pricing
3. Google Cloud Dataflow
- Unified stream and batch processing
- Serverless (no cluster management)
- Based on Google's internal Flume system
4. AWS Services
- AWS Glue: Serverless ETL using Spark
- AWS EMR: Managed Hadoop/Spark clusters
- AWS Athena: Serverless SQL queries (MapReduce under hood)
5. Azure HDInsight
- Managed Hadoop/Spark on Azure
- Integration with Azure ecosystem
Real-World Applications Today
1. E-commerce: Product Recommendations
- Map: Analyze each user's browsing/purchase history
- Reduce: Aggregate patterns → suggest products
- Example: Amazon's "customers also bought"
2. Social Media: Trend Analysis
- Map: Process individual posts/tweets
- Reduce: Aggregate hashtags, mentions
- Example: Twitter trending topics
3. Healthcare: Genomic Analysis
- Map: Process DNA sequences in parallel
- Reduce: Identify patterns and mutations
- Example: Cancer genome research
4. Finance: Fraud Detection
- Map: Analyze individual transactions
- Reduce: Detect suspicious patterns
- Example: Credit card fraud detection
5. IoT: Sensor Data Processing
- Map: Process data from millions of devices
- Reduce: Aggregate for monitoring and alerts
- Example: Smart city traffic management
Modern Scale: Companies like Facebook process 300+ petabytes of data daily. LinkedIn runs 10,000+ MapReduce jobs per day. These wouldn't be possible without MapReduce principles!
Summary and Key Takeaways
MapReduce is Powerful and Expressive
Key strengths:
- Simple abstraction: Just write map() and reduce()
- Handles complexity: Framework manages distribution, failures, coordination
- Scalable: Add more machines → process more data
- Fault-tolerant: Automatic recovery from failures
- Efficient: Optimizations like combiner, data locality, backup tasks
Performance Depends on Implementation Details
Critical factors:
- Data locality (minimize network traffic)
- Load balancing (avoid stragglers)
- Fault tolerance (handle failures quickly)
- Partitioning (distribute work evenly)
- Combiners (reduce intermediate data)
Original Paper
Reference:
- Title: "MapReduce: Simplified Data Processing on Large Clusters"
- Authors: Jeffrey Dean and Sanjay Ghemawat (Google)
- Published: USENIX OSDI Conference, 2004
Impact: This paper revolutionized big data processing and inspired entire ecosystem of tools!
Best Practices and Common Pitfalls
Best Practices
1. Design for Idempotency
- Map and reduce functions should produce same output for same input
- Important for fault tolerance (tasks may be re-run)
2. Minimize Data Shuffle
- Use combiners whenever possible
- Choose good partition functions
- Reduces network traffic = faster jobs
3. Optimize Partitioning
- Ensure balanced distribution across reducers
- Avoid data skew (some reducers overloaded)
- Use custom partitioning for domain-specific needs
4. Monitor Stragglers
- Identify slow tasks
- Use backup tasks
- Investigate root causes
5. Consider Data Locality
- Schedule tasks near their data
- Minimizes network latency
- Crucial for performance at scale
Common Pitfalls
1. Small Files Problem
Problem: Too many tiny input files creates overhead
- More scheduling overhead
- Less efficient data processing
Solution: Combine small files before processing
2. Data Skew
Problem: Some keys have WAY more values than others
- One reducer processes most data
- Other reducers sit idle
- Job takes as long as slowest reducer
Solution:
- Better partitioning function
- Handle "hot keys" specially
- Split large keys across multiple reducers
3. Memory Issues
Problem: Reduce tasks run out of memory
- Too many values for one key
- Trying to hold all values in memory
Solution:
- Increase reducer memory
- Use secondary sorting (process in batches)
- Stream processing instead of loading all at once
4. Not Using Combiners
Problem: Sending too much data over network
Solution: Add combiner for associative operations
5. Too Few or Too Many Tasks
Problem: Poor load balancing or excessive overhead
Solution: Choose M and R based on cluster size and data size
Performance Tuning Tips
-
Adjust M (map tasks):
- Based on input size and cluster size
- Typical: 10-100x number of workers
-
Set R (reduce tasks):
- Balance parallelism and output files
- Typical: 1-2x number of workers
-
Enable compression:
- Compress intermediate data
- Trade CPU for network bandwidth
-
Use speculative execution:
- Run backup tasks for stragglers
- Usually enabled by default
-
Profile and identify bottlenecks:
- Monitor: network, disk I/O, CPU, memory
- Optimize the slowest component
Glossary of Terms
Core Concepts
- Chunk: Fixed-size portion of file (typically 64 MB)
- Combiner: Local aggregation function after map, before reduce
- GFS: Google File System - Google's distributed file system
- HDFS: Hadoop Distributed File System - open-source version of GFS
- Intermediate data: Output from map phase, input to reduce phase
Operations
- Partition: Subset of intermediate data assigned to specific reducer
- Shuffle: Process of redistributing data between map and reduce phases
- Replica: Copy of data stored on different machine for fault tolerance
- Straggler: Slow worker that delays job completion
Components
- Master: Coordinator that assigns tasks and tracks progress
- Worker: Machine that executes map or reduce tasks
- Chunk Server: Machine that stores data chunks in distributed file system
Properties
- Atomic: Operation either completely succeeds or completely fails
- Associative: Operation where (a op b) op c = a op (b op c)
- Commutative: Operation where a op b = b op a
- Idempotent: Operation that produces same result if applied multiple times
Final Comprehensive Analogy
MapReduce = Organizing a Global Census
Problem: Count population of entire country
Traditional approach (one computer):
- One person visits every household
- Takes years to complete
- If person gets sick, start over
MapReduce approach:
-
Split data (Input splitting):
- Divide country into regions (counties)
- Each region = one map task
-
Map phase:
- Send census worker to each region
- Each worker counts people in their region
- Worker creates: (age_group, count) for their region
- Example: (0-18, 1000), (19-65, 2500), (65+, 500)
-
Combiner (optional):
- Regional office combines counts from nearby areas
- Reduces data sent to central office
-
Partition:
- Route all "0-18" counts to Counter 1
- Route all "19-65" counts to Counter 2
- Route all "65+" counts to Counter 3
-
Shuffle & Sort:
- Central office collects all regional reports
- Groups by age group
- Sorts in order
-
Reduce phase:
- Counter 1 sums all "0-18" counts → total children
- Counter 2 sums all "19-65" counts → total adults
- Counter 3 sums all "65+" counts → total elderly
-
Fault tolerance:
- If census worker gets sick → send replacement
- If regional office burns down → recount that region
- If central coordinator fails → restart (rare)
-
Backup tasks:
- If one region is slow (straggler) → send backup worker
- First to finish wins
Result: Complete census in weeks instead of years, automatically handles failures, scales to any country size!
This completes your comprehensive MapReduce cheat sheet! Every concept from your document is included with clear explanations, examples, and analogies. Good luck with your exam! 🚀