SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
  • Batch vs Stream Processing
  • Change Data Capture (CDC)
  • MapReduce
  • ETL Pipelines
  • Data Lakes
  • Data Warehousing
  • Data Lakehouse
  • Lambda Architecture
  • Kappa Architecture
  • Streaming Engines
  • Spark and Hadoop
  • Workflow Orchestration (Airflow)
  • Parquet and Columnar File Formats
  • Data Governance and Feature Stores
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Advanced Data Topics/Big Data Processing

MapReduce

Split a huge job into small map tasks and then combine the results with reduce tasks.

⏱ 14 min readIntermediateInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

MapReduce is a way to process a huge amount of data by cutting the job into small pieces that run on many machines at the same time, and then combining the results.

  • Map: each machine reads its own piece of the data and turns every record into (key, value) pairs.
  • Shuffle: the framework sends all pairs with the same key to the same machine.
  • Reduce: each machine combines the values of each key into one result (a sum, a count, a list).

02Concept: What is it?

Imagine a file so big that one computer would need days to read it. The idea of MapReduce is simple: split the file, let many computers each work on a piece, and then merge what they found. The hard parts (splitting, moving data, restarting a failed machine) are handled by the framework, so the programmer writes only two small functions.

The classic example is a word count. The map function reads a line and emits (word, 1) for every word. The framework then groups the pairs by word (shuffle and sort). The reduce function receives a word and the list of its 1s, and adds them up.

MapReduce: word count
📚Inputsplit in pieces
→↓
🗺️Map(word, 1)
→↓shuffle by key
🧩Groupword → [1, 1, 1]
→↓
➕Reduceadd up
→↓
📄Outputword = count
Mappers work alone. The shuffle is the only step where data moves between machines.

The model was made well known by a Google paper, and the open-source Hadoop brought it to everyone. Today newer engines (such as Spark) are used more often, but they keep the same core idea: move the computation to the data, process pieces in parallel, and group by key.

🧠Why only map and reduce?
Because these two steps have no shared state, the framework can run them on any machine, run a slow task again somewhere else, and add machines to go faster. The simple model is what makes the scale possible.

03Real-Life Example

🍵Counting Votes Across a Country
A country wants to count votes from 10,000 polling stations. One person counting all the ballots would take months. So each station counts its own ballots and writes a small tally: "Anna 120, Ben 85". These tallies are sent to regional offices, where all tallies for the same candidate go to the same office, and the office adds them up. The national total is the sum of the regional totals. Nobody ever had to move all ballots to one place.
Counting votes
MapReduce
A polling station counting its own ballots
A mapper working on its own split of the data
A tally line: candidate and count
A (key, value) pair
Sending tallies to the right regional office
The shuffle, grouped by key
The regional office adding up one candidate
A reducer for that key
The national total
The final output
A station adds up its tally before sending
A combiner (a mini reduce on the mapper)
One station is very slow, so another counts it again
Speculative re-execution of a slow task
A region gets most of the votes
Data skew: one reducer gets too much
Where the work happens
Near the data
🗺️Mapparallel, no talking
➕Combine (optional)shrinks the data
Across the network
🔀Shuffle and sortthe costly step
Per key
🧮Reduceone group at a time

04Why Do We Need It?

📈Scale by adding machines
Ten times more data? Use roughly ten times more machines, with no change to the code.
🚚Move code, not data
The mapper runs on the machine that already holds the data, so huge files do not cross the network.
🧯Survives failures
If a machine dies, its task is simply run again somewhere else. The programmer does not handle this.
🧠Simple to program
You write a map and a reduce function. Splitting, scheduling and retrying are done for you.
💸Cheap hardware
It works on a cluster of ordinary machines that are expected to fail now and then.
🌙Great for big batch jobs
Nightly reports, log analysis and index building over terabytes of data.
Break a giant job into independent pieces, group the partial results by key, and combine them. That is the whole idea.

05Where Do We Use It?

📝Log analysis
Count errors, page views or unique users from huge sets of log files.
🔎Building indexes
Create a search index from billions of documents.
🔗Joins and group-bys
Large SQL-style grouping and joining runs on this model under the surface in many big-data tools.
🏢Data warehouse jobs
Heavy nightly transformations in a data lake or warehouse.
🧬Science and statistics
Process large datasets such as genomes or sensor readings in parallel.
🤖Preparing data for ML
Clean and group large training data before a model sees it.

06Types / Parts / How It Works

The steps in a MapReduce job

StepWhat it doesWhere it runs
Input splitCut the input into pieces, usually matching file blocksFramework
MapTurn each record into zero or more (key, value) pairsOn many machines, near the data
Combine (optional)A reduce that runs on one mapper's output, to cut data before the shuffleOn the mapper machine
PartitionChoose the reducer for each key, often hash(key) modulo the number of reducersOn the mapper machine
Shuffle and sortMove pairs across the network and group them by keyBetween machines
ReduceCombine all values of one key into a resultOn many machines, one key group at a time
OutputWrite the result, often to a distributed file systemReducers

More than word count

JobMap emitsReduce does
Word count(word, 1)Sum the 1s
Page views per URL(url, 1) from each log lineSum per URL
Maximum temperature per city(city, temperature)Keep the largest value
Inverted index(word, document id)Collect the list of documents
Join two tables(join key, row tagged with its table)Pair rows from both tables for the same key
💡When can you use a combiner?
Only when the reduce operation can be done in parts and in any order (a sum, a count, a maximum). It is wrong for an average unless you carry the sum and the count, because an average of averages is not the average.
VisualizerA real word count: map, shuffle, reduceStep through the five stages. Then switch the combiner on and watch the shuffled pairs shrink, and change the number of reducers to see how words are spread.
Input data
Combiner (pre-add on each mapper)
Split 1 → Mapper 1
"apple banana apple"
Split 2 → Mapper 2
"banana cherry apple"
Split 3 → Mapper 3
"cherry banana banana"
Step 1 of 5
Input: the data is split
The input is cut into 3 splits. Each split goes to its own mapper, which can run on a different machine, next to the data it reads.
Pairs from map
9
(word, 1) records
Pairs shuffled
9
cross the network
Different words
3
keys in the result
Busiest reducer
2
keys of 3
Try switching the combiner on and watch the shuffled pairs drop, then change the number of reducers to see how the words are spread (and sometimes spread unevenly).

A teaching model: tiny inputs, a simple hash for the partition, and no failures or disk. A real framework also writes map output to local disk, retries failed tasks and moves the code to the data.

07How to Use It / Steps / Implementation

Designing a MapReduce job

  1. 1
    Choose the key
    Ask: what do I want one answer per? A word, a user, a day. The key decides what is grouped together.
  2. 2
    Write the map function
    Read one record and emit (key, value) pairs. Keep it free of state, so it can run anywhere.
  3. 3
    Write the reduce function
    Take one key and all its values, and produce the result. It should not depend on the order of the values.
  4. 4
    Add a combiner if it is safe
    If the reduce is a sum, count or max, run it on the mapper too. It cuts the shuffle a lot.
  5. 5
    Pick the number of reducers
    Too few and the reduce step is a bottleneck. Too many and you get many tiny output files.
  6. 6
    Watch for skew
    If one key has most of the data, one reducer does most of the work and the job waits for it. Split hot keys, for example by adding a random suffix and merging after.
  7. 7
    Chain jobs for hard problems
    Complex work becomes several jobs where one job's output feeds the next. Each one writes to disk, which is slow.
  8. 8
    Consider a newer engine
    For iterative work or interactive queries, engines that keep data in memory (such as Spark) are usually faster than classic disk-based MapReduce.
⚠️The shuffle is the cost
Most of the time of a MapReduce job goes to moving, sorting and writing data in the shuffle. Anything that sends fewer pairs through it (combiners, filtering early, a good key) makes the job faster.

08Key Terms to Know

TermMeaning in easy words
MapA step that turns each input record into (key, value) pairs
ReduceA step that combines all values for one key into a result
ShuffleMoving pairs across the network so that all pairs of one key meet
CombinerA mini reduce on the mapper side that shrinks data before the shuffle
PartitionerThe rule that picks the reducer for a key, often a hash
SplitA piece of the input that one mapper works on
Mapper / ReducerA task (or the machine slot) running the map or reduce function
Data skewOne key has much more data than the others, so one reducer is overloaded
StragglerA task that runs much slower than the rest and delays the job
Speculative executionStarting a copy of a slow task on another machine and using whichever finishes first
HadoopAn open-source system with a distributed file system (HDFS) and a MapReduce engine

09Pros, Cons and Trade-offs

✅ Pros
  • Scales to very large data by adding machines
  • Failures are handled by re-running tasks
  • Simple model: only map and reduce to write
  • Computation moves to where the data is
  • Works on cheap, ordinary machines
  • Very good for large batch jobs
⚠️ Cons
  • High delay: it is not for real-time answers
  • Each stage writes to disk, so it is slow for iterative work
  • Many problems are awkward to express as map and reduce
  • The shuffle is expensive
  • Data skew can ruin the speed
  • Newer engines are often easier and faster

Trade-offs

ChoiceWe gainWe lose
Disk-based MapReduceStrong fault tolerance on huge jobsSlow, especially for jobs with many stages
In-memory engine (Spark style)Much faster for iterative and interactive workMore memory needed, and recovery needs more care
More reducersMore parallel work in the final stepMore small output files and more tasks to manage
Using a combinerMuch less data in the shuffleOnly valid for operations that can be done in parts
Batch MapReduceSimple, cheap, handles any sizeResults are late: minutes or hours old
Stream processing insteadResults within secondsA harder system to build and run

10Common Problems and Mistakes

Common mistakes

  1. A bad key. Using a key with only a few values, for example a country code, sends most of the data to a few reducers.
  2. A reduce that depends on order. The values for a key can arrive in any order.
  3. A wrong combiner. Using an average as a combiner gives a wrong answer.
  4. Too many small files. Thousands of tiny inputs mean thousands of tiny mappers, and the start-up cost dominates.
  5. Hidden side effects. A task can be run twice. If it writes to an outside database, you get duplicate writes.
  6. Choosing MapReduce for a small or real-time problem. One machine or a stream engine would do better.
  7. Ignoring the shuffle size. Sending whole records instead of small keys and values makes the job slow.

Things to watch

🐌Stragglers
One slow task holds the whole job. Speculative execution helps.
⚖️Skew
One reducer gets most of the data. Look at the sizes of the task inputs.
💾Disk and network
The shuffle writes and reads a lot. Watch both.
🔁Re-runs
Tasks may run more than once, so make the outputs safe to repeat.

11Real-World Examples

🔍Web-scale indexing
The model was introduced for building search indexes over huge collections of web pages.
🐘Hadoop clusters
Many companies ran their nightly data jobs on Hadoop MapReduce for years.
⚡Spark
Spark keeps the map, shuffle and reduce ideas but keeps data in memory between steps, which is often much faster.
🐝SQL on big data
Tools such as Hive began by turning SQL queries into MapReduce jobs, and later moved to faster engines.
☁️Managed big-data services
Cloud services run these jobs for you, so you do not manage the cluster.
📝Log processing
Counting errors or users across days of logs is the classic use.
📝Note
Classic disk-based MapReduce is used less today for new work. It is still taught because the same ideas (partition, shuffle, group by key, retry tasks) sit inside newer tools.
Mini case: page views per URL
📝1 TB of logsin 8,000 blocks
→↓
🗺️8,000 map tasks(url, 1) + combine
→↓shuffle
➕50 reduce taskssum per url
→↓
📊Reportviews per URL
Parallel near data Network Final result
One day of logs, spread over many machines.

12Related Topics to Read Next

Batch vs Stream Processing→

MapReduce is the classic batch model.

Distributed File Systems→

The data MapReduce reads and writes lives in one.

Lambda Architecture→

Uses a batch layer, often a MapReduce-style job, next to a speed layer.

Sharding→

Both split data by key across machines.

Consistent Hashing→

Another way to decide which machine a key goes to.

ETL Pipelines→

Big ETL jobs often run as MapReduce-style jobs.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔What: process huge data in parallel: map, shuffle, reduce.
  • ✔Map: record → (key, value) pairs. Reduce: one key and its values → result.
  • ✔Shuffle: groups by key across the network. It is the costly step.
  • ✔Combiner: mini reduce on the mapper. Only for sum, count, max (not plain average).
  • ✔Fault tolerance: re-run failed tasks. Make tasks safe to repeat.
  • ✔Watch: skew, stragglers, too many small files.
  • ✔Today: Spark and similar engines keep the idea but use memory.
  • ✔One line: “Cut the job into pieces, group by key, add it up.”
← Previous
Change Data Capture (CDC)
Next →
ETL Pipelines