AlgoViz

MapReduce

medium 30 min

MapReduce 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

Split 1hello worldSplit 2hello mapreduceSplit 3world of dataMap task 1Map task 2Map task 3Reduce task 1Reduce task 2

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

Input filesCount jobmap, reduceHDFS3 copiesRank jobwaiting

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

    critical

    Small groups count as much as large ones.

    Wrong
    return mean(partial_means)
    Right
    return sum(sums) / sum(counts)
  • Side effects in a task

    critical

    A rerun or a backup copy repeats them.

    Wrong
    def reducer(user, orders):    send_email(user)
    Right
    def reducer(user, orders):    yield user, total(orders)  # send later, once
  • More reducers against a hot key

    major

    One key always lands on one reducer.

    Wrong
    job.reducers = 1000
    Right
    key = f"{key}-{randrange(10)}"  # then add up
  • A hash that changes

    major

    Python's hash of a string differs between processes, so equal keys could go to different reducers.

    Wrong
    hash(key) % reducers
    Right
    crc32(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.