Hadoop: HDFS and MapReduce
Hadoop Distributed File System (HDFS) stores large files across many machines with replication; MapReduce is a programming model that runs parallel data processing (map then reduce) on that data.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
HDFS and MapReduce are used when engineers must store and process very large datasets that do not fit on one machine. HDFS gives reliable, distributed storage; MapReduce provides a simple, scalable way to write parallel jobs that run close to that data.
Key ideas
Start from first principles and definitions.
- Big data: data whose size or speed requires distributed storage or processing beyond a single server. Defined before use because Hadoop targets big data.
- Hadoop Distributed File System (HDFS): a distributed file system designed to store very large files across commodity servers, providing fault tolerance by replicating data. HDFS assumes streaming reads and large files; it is not optimized for many small files.
- NameNode: the master process that stores the filesystem metadata (directory tree, block locations). Exact responsibility: maintain namespace image and map from file -> block IDs -> DataNode addresses. NameNode does NOT store the actual file data. SecondaryNameNode (Checkpoint Node) periodically merges the fsimage and edit logs to create a new checkpoint; it is not a standby NameNode or a backup.
- DataNode: the worker process that stores block files on local disk and serves read/write requests for blocks. DataNodes also send periodic heartbeats and block reports to the NameNode.
- Block: a contiguous chunk of a file up to the configured block size (the last block may be smaller) stored on a DataNode. HDFS breaks a file into blocks; default block size is a configured cluster parameter (commonly 128 MB in modern Hadoop, formerly 64 MB).
- Replication factor: the number of copies HDFS keeps of each block to tolerate node failures. Default is configurable (often 3).
- Write-once-read-many: HDFS file access model: files are written once and then read many times. HDFS supports append but not arbitrary random writes.
- Rack awareness: HDFS places replicas considering physical rack layout to survive rack failure and reduce cross-rack network traffic.
- Small files problem: many small files cause NameNode memory pressure because metadata per file must be stored in NameNode RAM.
MapReduce model (formal):
- MapReduce: a programming model and runtime for processing large datasets with a parallel, distributed algorithm on a cluster. A MapReduce job has two core user functions:
- Mapper: function signature map(k1, v1) -> list(k2, v2). The mapper processes input key-value pairs to produce intermediate key-value pairs.
- Reducer: function signature reduce(k2, list(v2)) -> list(k3, v3). The reducer aggregates all values that share the same intermediate key to produce final key–value outputs.
- Shuffle and sort: the phase between map and reduce where the system groups intermediate pairs by key and transfers them across the network to reducers. The intermediate keys are sorted before they reach a reducer.
- Combiner: an optional mini-reducer run on mapper node to pre-aggregate mapper outputs (helps reduce network traffic). It must be commutative and associative (same effect as local reduction) to be correct. Its execution is not guaranteed; it may run zero, one, or multiple times.
System/implementation facts and consequences (exact statements):
- Number of mappers = number of input splits. By default an input split is aligned with block boundaries but is a logical unit defined by InputFormat; so a large file with N blocks typically yields N mappers (unless the InputFormat combines splits).
- Reducer keys partitioning: the framework uses a partition function (by default hash(key) mod R) to send each intermediate key to one of R reducers. Therefore all values for a key end up at the same reducer.
- Fault tolerance: if a mapper or reducer task fails, the JobTracker (MRv1) or ApplicationMaster (YARN/MRv2) re-runs the task, possibly on another node. HDFS tolerates DataNode failures as long as for each block at least one replica remains available (i.e., replication factor >= 1 for that block).
What to draw (diagrams for an exam):
- HDFS architecture: draw one large box labelled "Cluster"; inside draw one box labelled "NameNode (master)" at top; draw three boxes labelled "DataNode A/B/C" below. From NameNode draw arrows to each DataNode labelled "block metadata, heartbeats". Inside each DataNode box draw small rectangles labelled "block 1, block 2, ...". Show replication by drawing same block id appearing on multiple DataNodes. Label a rack boundary if showing rack awareness.
- MapReduce flow: draw input files on HDFS at left, arrows to multiple boxes labelled "Mapper 1..M". From each Mapper draw arrows to a central stage labelled "Shuffle & Sort" (show network arrows), then to right-side boxes labelled "Reducer 1..R", and finally to HDFS output. Label phases: Map -> Shuffle/Sort -> Reduce.
Assumptions behind statements: NameNode is a single point of metadata (unless HA configured). For reproducibility, mappers and reducers should be deterministic; the framework does not require this. Combiner correctness assumes associative and commutative aggregation.
Formulas
#blocks = ceil(file_size_bytes / block_size_bytes) — where file_size_bytes is the file size in bytes and block_size_bytes is HDFS block size (SI unit: byte). Applies when file is broken into fixed-size blocks.
total_storage_used ≈ file_size_bytes × replication_factor — approximate data bytes stored across replicas (ignores metadata); an upper bound is #blocks × block_size_bytes × replication_factor because the last block may be partially filled.
#mappers = #input_splits — number of mapper tasks equals number of logical input splits determined by InputFormat (unitless).
partition = hash(key) mod R — default reducer partitioning function, where R is number of reducers (unitless).
Important shell syntax to remember (HDFS and streaming):
hdfs dfs -put localfile /hdfs/path — put a file to HDFS.
hdfs dfs -ls /hdfs/path — list HDFS directory.
hdfs dfs -cat /hdfs/path/file — print file contents from HDFS.
hdfs dfs -rm -r /hdfs/path — remove files/dirs in HDFS.
hadoop jar hadoop-streaming.jar -files mapper.py,reducer.py -input /in -output /out -mapper mapper.py -reducer reducer.py — run a streaming job (ships scripts to workers and executes them).
Worked examples
Example 1 — numeric: blocks, storage used Question: A file of size 500 MB is stored on HDFS with block size 128 MB and replication factor 3. How many blocks are used and what is the approximate total storage consumed? (1 MB = 10^6 bytes for simplicity here.) Steps:
- file_size = 500 MB; block_size = 128 MB.
- #blocks = ceil(500 / 128) = ceil(3.90625) = 4 blocks.
- total_storage_used ≈ file_size × replication_factor = 500 MB × 3 = 1500 MB. Final answer: 4 blocks; total storage ≈ 1500 MB (1.5 GB).
Example 2 — programming: Word count using Hadoop streaming (two programs that run locally on stdin/stdout). Save as mapper.py and reducer.py and run with streaming or test by piping. mapper.py:
#!/usr/bin/env python3
import sys
for line in sys.stdin:
for word in line.strip().split():
print(f"{word}\t1")
reducer.py:
#!/usr/bin/env python3
import sys
from collections import defaultdict
counts = defaultdict(int)
for line in sys.stdin:
key, val = line.rstrip('\n').split('\t')
counts[key] += int(val)
for k in sorted(counts):
print(f"{k}\t{counts[k]}")
Sample input (stdin): Hello world\nHello Hadoop\n Exact output when piping mapper -> sort -> reducer (simulate Hadoop shuffle): Hadoop\t1\nHello\t2\nworld\t1\n Explanation: Mapper emits word\t1 for each word. Sorting groups identical keys, reducer sums counts and prints sorted keys.
Notes: In real Hadoop streaming, mapper output is sorted and partitioned by Hadoop; local test uses Unix sort between mapper and reducer.
Common mistakes
- Assuming one mapper per block without noting InputFormat can combine or split splits; also ignoring that a single large record that crosses block boundary is handled by InputFormat.
- Using combiner incorrectly when function is not associative/commutative (e.g., using combiner for non-idempotent operations).
- Ignoring the small-files problem; putting millions of tiny files wastes NameNode memory.
- Forgetting network cost of shuffle: people assume MapReduce is free in network; shuffle can be the dominant cost.
For your exam
Question types:
- Definitions (e.g., define HDFS, NameNode, DataNode, replication factor).
- Short notes (e.g., explain write-once-read-many model, rack awareness, small files problem).
- Diagrams (draw HDFS architecture or MapReduce flow; label NameNode, DataNodes, blocks, replica placement).
- Derivations/numericals (compute number of blocks, storage used, number of mappers given file sizes).
- Programs (write mapper/reducer or explain shuffle process).
What full-marks answers include:
- Clear definitions with bold term usage and roles.
- Correct diagram with labels as described above.
- For numerical: show formula
ceil(file_size/block_size), show step-by-step numeric substitution, units carried through, final bold answer. - For programs: runnable mapper and reducer pseudo-code or streaming code; explain shuffle and sort steps and show sample input/output.
Quick check
- What is the role of the NameNode in HDFS?
- Write the formula for number of HDFS blocks for a file of size S and block size B.
- In MapReduce, what phase moves intermediate key-value pairs from mappers to reducers?
Answers: NameNode stores filesystem metadata (namespace and block locations);
#blocks = ceil(S / B); Shuffle (and sort) phase.
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?