MapReduce From the Ground Up, Then in Rust

The problem

Say you have a folder of text files and you want to know how many times each word appears. On your laptop this is a ten-line program: read every file, keep a hash map from word to count, print the map.

Now make the folder a few thousand times bigger. The program is still correct, but two things break:

  • It takes too long. One machine reads one disk at one speed. If the data takes a week to read, no clever loop will fix that.
  • It does not fit. At some point the hash map itself is bigger than your memory.

The obvious fix is to use many machines. Give each one a slice of the files and let them count in parallel. That gets you most of the way, and then you run into the two questions that make this hard:

  1. How do the partial answers get combined? Machine A counted “the” 4,000 times and machine B counted it 3,500 times. Somebody has to add those up, and if that somebody is a single machine, you have moved the bottleneck instead of removing it.
  2. What happens when a machine misbehaves? With enough machines, one of them is always slow, rebooting, or dead. If one failure means starting over, a big job never finishes.

MapReduce is an answer to both questions. It comes from a 2004 Google paper, MapReduce: Simplified Data Processing on Large Clusters, and the idea is small enough to work out by hand. So let us do that first, and only then look at the Rust implementation I built to understand it properly.

Doing it by hand

Forget computers for a minute. You have a thousand books, a room full of friends, and the same task: count every word.

Step 1: hand out the books. Each friend takes one book and writes a slip of paper for every word they read: the, 1, cat, 1, the, 1. Nobody talks to anybody else. Nobody keeps a running total. They just produce slips.

Step 2: sort the slips into buckets. Put a few buckets in the middle of the room and agree on one rule that decides which bucket a word belongs to. For example: words starting with A to M go in bucket 0, the rest in bucket 1. The rule itself is not important. What matters is that everybody uses the same one, so every slip for “the” lands in the same bucket no matter who wrote it.

Step 3: count each bucket. When all the books are done, one friend takes each bucket, groups the slips by word, and adds them up. Because of the bucket rule, the person holding bucket 1 has every slip for “the” that exists. Their total is the final total. Nobody needs to merge anything afterwards.

That is the whole algorithm. Step 1 is map, step 3 is reduce, and step 2 is the quiet piece in the middle that makes it work, usually called the shuffle or the partition step.

Look at how it answers the first question. There is no single person combining everyone’s results. The combining is spread over the buckets, and you can have as many buckets as you like.

It also has a useful property for the second question. If a friend walks out halfway through a book, you hand that book to someone else and they start it again from page one. Nothing the rest of the room did is wasted, because nobody depended on anybody else’s progress.

The two functions

The reason the paper mattered is that it turned this into a contract. You, the programmer, write two functions:

  • map takes one piece of input and emits key/value pairs.
  • reduce takes one key and all the values emitted for it, and returns one result.

Everything else (handing out books, the buckets, noticing who walked out) is the runtime’s job. For word count, the two functions look roughly like this:

fn map(contents: &str) -> Vec<(String, String)> {
    contents
        .split_whitespace()
        .map(|word| (word.to_lowercase(), "1".to_string()))
        .collect()
}

fn reduce(_key: &str, values: &[String]) -> String {
    values.len().to_string()
}

Change those two functions and the same runtime does a different job. Emit (word, file name) from map and join the file names in reduce, and you have an inverted index, which is the data structure behind a search engine. The paper lists several more: distributed grep, counting URL hits, sorting.

One tiny job, start to finish

Three input files, two buckets. In the runtime’s terms that is three map tasks and two reduce tasks.

a.txt: the cat sat
b.txt: the dog sat
c.txt: the cat ran

Each map task reads one file and writes one intermediate file per bucket. The bucket is chosen by hashing the key and taking the remainder by the number of reduce tasks. Suppose the hash sends the and dog to bucket 0 and everything else to bucket 1. The files are named mr-X-Y, where X is the map task and Y is the bucket:

map 0 (a.txt)   mr-0-0: the 1          mr-0-1: cat 1, sat 1
map 1 (b.txt)   mr-1-0: the 1, dog 1   mr-1-1: sat 1
map 2 (c.txt)   mr-2-0: the 1          mr-2-1: cat 1, ran 1

Each reduce task then reads one column of that table. Reduce 0 reads mr-0-0, mr-1-0, and mr-2-0, groups by key, and calls reduce once per key:

reduce 0   the [1, 1, 1] -> 3     dog [1] -> 1          writes mr-out-0
reduce 1   cat [1, 1] -> 2        ran [1] -> 1
           sat [1, 1] -> 2                              writes mr-out-1

The answer is the two output files taken together. Three maps and two reduces gave us six intermediate files, and in general it is always maps times reduces.

One detail in that walk-through turns out to matter a lot. Reduce 0 needs a file from every map task. Hold on to that; it comes back as the first bug below.

Who is in charge?

In the room full of friends, somebody has to stand at the front with a clipboard: which books are handed out, which are finished, which buckets are ready. That is the coordinator. Everyone else is a worker.

I built this in Rust in the shape of the MIT 6.824 lab: one coordinator process, many worker processes, all on one machine, talking over a Unix socket and sharing a directory for files.

The first real design decision is who speaks first. I went with the rule that the coordinator never contacts a worker. Workers ask for work, do it, and report back. That is the entire protocol:

Back in the room, this is the difference between you walking around checking on each friend and your friends coming up to the desk when they are free. The second way is much less work for you. The coordinator needs no list of workers, no heartbeats, and no open connections to keep track of. A dead worker is just a worker that stops showing up at the desk.

The coordinator also never touches the data. It checks that the input files exist and are readable, and from then on it only does bookkeeping. Workers do all the reading and writing, so a slow disk can never hold up the clipboard.

Where it goes wrong

Everything so far is the happy path, and the happy path is about a page of code. The rest of the project is what happens when workers stop behaving. There are four cases worth walking through, and each one has a small fix.

1. Reducing too early

Remember that reduce 0 needs a file from every map task. Suppose map 2 is still running when reduce 0 starts. Reduce 0 reads the two files that exist and reports the 2.

Nothing crashes and there is no error message. The output is well formed and wrong, which is the worst kind of bug because it will pass a quick demo.

The fix is a hard wall between the two phases. The coordinator keeps a count of unfinished map tasks and hands out no reduce task until that count is zero. The count only goes down when a worker reports a map as successful, and a worker only reports success after every one of its bucket files is fully written.

2. Two workers, one file

How does the coordinator know a worker died? It does not. All it can see is that a task was handed out and nobody has reported back for too long. So each task is given out on a lease: finish within the time limit, or the task goes to someone else.

A lease is a guess. Sometimes the worker is not dead, only slow, and it is still writing mr-3-7 at the moment its replacement starts writing mr-3-7 too. If their writes interleave, the file is garbage.

The fix is to never write to the real file name. A worker writes to a temporary file in the same directory and renames it when the whole thing is on disk:

let mut temp = tempfile::Builder::new()
    .prefix(".mr-tmp-")
    .tempfile_in(directory)?;

// write and flush the complete payload, then:
temp.persist(final_path)?; // a rename, atomic on POSIX

A rename is atomic, so a reader sees either one complete file or the other, never a mix. And since map and reduce are required to be deterministic, both workers produce the same contents, so it makes no difference whose rename lands last.

This pairing is what the rest of the design leans on. Atomic rename plus deterministic functions makes it safe to run a task twice. Once running a task twice is safe, the coordinator can afford a crude timeout instead of trying to truly detect failure, which is not possible anyway.

3. The worker that comes back late

Worker A takes task 3 and stalls. The lease runs out and task 3 goes to worker B. Then A wakes up, finishes, and reports success.

If the coordinator believes A, it marks the task done while B is still in the middle of it, and its bookkeeping no longer matches reality. So every time a task is handed out it gets a new number, called an epoch, and every report has to quote the epoch it was given.

Think of the epoch as a numbered ticket for the task. Only the most recent ticket is honoured.

There is one deliberate exception. If A’s lease has run out but nobody else has picked the task up yet, A’s late success is accepted. The files are complete and correct, and there is no newer ticket to conflict with, so throwing the work away would only waste time.

4. The reply that got lost

The coordinator assigns a task, but the reply never reaches the worker. The coordinator now thinks the worker is busy. The worker thinks it has nothing to do, so it polls again.

Without a fix, the task sits idle until its lease expires. Instead, when a worker that already owns a task polls again, the coordinator hands back the same task with the same epoch. If the worker had in fact started it, running it again does no harm, for the reason we saw in case 2. It also means a worker can never end up holding two tasks.

How it looks in Rust

One owner for the clipboard

Many workers talk to the coordinator at once, so its state needs protecting. The usual move is to put a mutex around it. I went the other way: the state belongs to exactly one thread, and nobody else can touch it.

Each connection gets a thread that reads a request and pushes it onto a bounded queue, together with a channel to reply on. A single state thread takes requests off the queue one at a time, updates the coordinator, and sends the answer back.

This is the clipboard again. One person holds it, and everyone else queues at the desk. Because requests are handled strictly one after another, there are no locks and no lock ordering to get wrong, and the state machine can be tested as plain single-threaded code. The whole implementation has no Mutex, no Arc, no async, and no unsafe, and none of that took any effort. It just follows from having a single owner.

What a job looks like

A job is anything that implements this trait:

pub trait Job: Send + Sync {
    fn name(&self) -> &'static str;

    fn map(&self, input: MapInput<'_>) -> Result<Vec<KeyValue>, JobError>;

    fn reduce(&self, key: &str, values: &[String]) -> Result<String, JobError>;

    fn combines(&self) -> bool { false }

    fn combine(&self, _key: &str, _values: &[String])
        -> Result<Option<String>, JobError> { Ok(None) }
}

map and reduce are the two functions from earlier. combine is an optional shortcut. In the by-hand version, a friend who reads “the” 400 times in one book could write a single slip saying the, 400 instead of 400 separate slips. That is a combiner: a small reduce that runs on the map side, so less data has to be written and read back.

Word count uses it because counts can be added in any order. The inverted index does not, because its values are locations, and there is nothing to add up.

Jobs are compiled into the binary and picked by name from a small registry. There is no plugin loading. Every poll and report also carries the job name, so a worker built for a different job is turned away instead of quietly corrupting the output.

Does it actually work?

The check I trust most is the simplest one. Alongside the distributed version there is a sequential one: a single process that does the whole job in memory, the ten-line program from the top of this post. The end-to-end test runs both on the same input and compares the sorted results byte for byte.

With one coordinator, four worker processes, eight input files, and four reduce tasks:

verified 157 distinct keys against mrsequential
intermediate files: 32 (8 maps x 4 reduces)
leftover temporary files: 0

That is not a proof, but it catches the mistakes unit tests tend to miss: a wrong file name, a key sent to the wrong bucket, a temporary file left behind. The awkward orderings from the previous section (stale epochs, late successes, duplicate reports, redelivery, concurrent writers on the same file) are pinned down by tests against the state machine directly, 65 in total.

What it does not do yet

This is a solid MapReduce for one machine. It is not a cluster system, and here is where the gaps are.

  • Runs are not isolated. Workers write into a shared directory. Output files left over from an earlier run can sit next to the new ones, and nothing tells a reader “this run is complete”. Each run needs its own ID, its own directory, and a marker file written at the very end.
  • A broken task retries forever. If an input is bad or the disk is full, the task fails, gets handed out again, and fails again. The coordinator counts attempts but never acts on the count. It needs a retry limit and a way to say “this job has failed”.
  • One file is one map task. A single huge file cannot be split across workers, and each worker reads its whole input into memory. Reduce also holds a whole bucket in memory. Splitting files by byte range and merging sorted map output would lift both limits.
  • It runs on one machine. Swapping the Unix socket for TCP would not be enough to fix that. Reduce workers read the files that map workers wrote, so with several machines you need either a shared file system or a service that ships those files around.
  • The coordinator is a single point of failure. If it crashes, the job starts again from zero.

If I had a week, I would do the first two. They are the least exciting items on the list, and they are the ones that decide whether you can leave the thing running unattended.

Wrapping up

The idea behind MapReduce fits in a room: hand out the books, sort the slips into buckets by one shared rule, count each bucket. Map, shuffle, reduce.

What took the effort was the person with the clipboard. Nearly every interesting decision in this project came from one question: what if a worker is slow, dead, or late? And the answers kept coming back to the same few moves:

  • Workers ask for work, so a dead worker needs no special handling.
  • No reduce task starts until every map task is done.
  • Files appear by atomic rename and tasks are deterministic, so running a task twice is harmless.
  • Every assignment carries an epoch, so a late report can be recognised and ignored.

None of these makes map any faster. What they do is turn a duplicate attempt, a dead worker, and a stale report into routine events, and the runtime is mostly that.

Citation

Please cite this work as:

Makonda, Barnabas, "MapReduce From the Ground Up, Then in Rust", Barnabas Makonda's blog, Oct 2026.

Or use the BibTeX citation:

bibtex
@misc{makonda2026mapreduce,
  author = {Barnabas Makonda},
  title = {MapReduce From the Ground Up, Then in Rust},
  howpublished = {Barnabas Makonda's blog},
  year = {2026},
  month = {oct},
  url = {https://blog.barnabasmakonda.workers.dev/posts/map-reduce/},
}