MapReduce
medium 30 minMapReduce processes very large data on many machines with two small functions.
See it run
Two small functions, and a framework that splits, moves, sorts and retries.
Operations
Word count
The six phases of one job, with three lines of text and two reduce tasks.
Step 1 of 6
Input splits
Three lines are three splits, so that they can be read in parallel.
Step 1: Input splits
def mapper(line): for word in line.split(): yield word, 1def reducer(word, counts): return sum(counts)def job(splits, reducers): pairs = [p for s in splits for p in mapper(s)] for key, values in shuffle(pairs, reducers): write(key, reducer(key, values))- Moves
- 7 pairs
- Runs on
- Splits, then keys
You write mapper and reducer. The framework is the rest.
In the real world
The same mapreduce doing real jobs. Pick one and step through it.
Top ten words: count in one job, rank in a second.
Step 1 of 3
Job 1 counts
The first job maps, shuffles and reduces to counts.
Step 1: Job 1 counts
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Averaging averages
criticalSmall groups count as much as large ones.
Wrongreturn mean(partial_means)Rightreturn sum(sums) / sum(counts)Side effects in a task
criticalA rerun or a backup copy repeats them.
Wrongdef reducer(user, orders): send_email(user)Rightdef reducer(user, orders): yield user, total(orders) # send later, onceMore reducers against a hot key
majorOne key always lands on one reducer.
Wrongjob.reducers = 1000Rightkey = f"{key}-{randrange(10)}" # then add upA hash that changes
majorPython's hash of a string differs between processes, so equal keys could go to different reducers.
Wronghash(key) % reducersRightcrc32(key.encode()) % reducers
Interview tips
How to explain it
- Map emits pairs.
- Shuffle brings equal keys together.
- Reduce finishes each key.
Memory trick: MSR
- Map transforms.
- Shuffle groups.
- Reduce aggregates.
Make it faster
- Combine before the network.
- Compress map output.
- Drop fields early.
Watch
- The largest key.
- Tasks that run long after the rest.
- Many tiny output files.