BIG DATA FRAMEWORKS & ANALYTICS
Hadoop MapReduce Framework
Unit III – Detailed Lecture Notes for IV B.Tech Students
Concepts, Architecture, Working Mechanisms, Programming Examples and Examination Preparation
Syllabus Coverage
MapReduce Framework: Developing a MapReduce application, how MapReduce works, anatomy of a MapReduce job run, job scheduling, shuffle and sort, task execution, failures, MapReduce types and formats, MapReduce features, Hadoop environment and introduction to YARN.
Table of Contents
- Introduction to MapReduce
- Developing a MapReduce Application
- How MapReduce Works
- Anatomy of a MapReduce Job Run
- Job Scheduling
- Shuffle and Sort
- Task Execution
- Failures in MapReduce
- MapReduce Types and Formats
- MapReduce Features
- Hadoop Environment
- Introduction to YARN
- Real-World Applications
- Important Differences
- Important Terminology
- Important Examination Questions
- Unit Summary
1. Introduction to MapReduce Framework
MapReduce is a distributed programming model and processing framework used to process large volumes of data across multiple computers in a cluster.
It was originally introduced by Google and later implemented as an open-source framework in Apache Hadoop.
MapReduce divides a large computational problem into smaller tasks, executes these tasks in parallel across multiple nodes and combines the intermediate results to produce the final output.
Hadoop MapReduce generally uses HDFS for storing input and output data and YARN for resource management and application execution.
1.1 Need for MapReduce
Traditional data processing systems face several difficulties when processing massive datasets:
- Limited storage and processing capacity.
- High computational time.
- Difficulty in processing unstructured and semi-structured data.
- Limited scalability.
- Difficulty in recovering from hardware failures.
- High cost of powerful centralized computing systems.
MapReduce addresses these challenges through distributed storage, parallel processing, scalability, data locality and automatic failure recovery.
1.2 Basic Architecture of MapReduce
Group intermediate values by key
Figure 1: Basic Architecture of Hadoop MapReduce
MapReduce consists of two major processing functions:
- Map: Processes input data and generates intermediate key-value pairs.
- Reduce: Processes grouped intermediate values and generates final results.
Between these two functions, the framework performs an important operation called Shuffle and Sort.
1.3 Key-Value Pair Model
MapReduce processes data in the form of key-value pairs.
Map Function
Map(K1, V1) → List(K2, V2)
Reduce Function
Reduce(K2, List(V2)) → List(K3, V3)
- K1, V1: Input key and value.
- K2, V2: Intermediate key and value.
- K3, V3: Final output key and value.
For example, in a student marks dataset, the student name may represent the key and the marks may represent the value.
2. Developing a MapReduce Application
Developing a MapReduce application involves identifying the computational problem, designing the Mapper and Reducer functions, configuring the job and executing it in the Hadoop environment.
2.1 Components of a MapReduce Application
| Component | Responsibility |
|---|---|
| Driver | Configures and submits the MapReduce job. |
| InputFormat | Determines how input data is divided and read. |
| InputSplit | Represents a logical portion of input data. |
| RecordReader | Converts input data into key-value pairs. |
| Mapper | Processes input key-value pairs. |
| Combiner | Optionally performs local aggregation. |
| Partitioner | Determines the destination reducer. |
| Reducer | Processes grouped intermediate values. |
| OutputFormat | Defines how output data is written. |
| RecordWriter | Writes final key-value pairs. |
2.2 Steps in Developing a MapReduce Application
- Identify the problem to be solved.
- Identify the input dataset and its format.
- Determine input and output key-value types.
- Develop the Mapper function.
- Develop the Reducer function, if required.
- Configure the job using the Driver.
- Compile and package the application.
- Submit the application to Hadoop.
- Monitor the job execution.
- Verify the final output.
2.3 Example: Word Count Application
Word Count is a fundamental MapReduce application used to understand distributed data processing.
Sample Input
Hadoop is powerful
Hadoop is scalable
Big Data uses Hadoop
Mapper Output
(Hadoop, 1)
(is, 1)
(powerful, 1)
(Hadoop, 1)
(is, 1)
(scalable, 1)
(Big, 1)
(Data, 1)
(uses, 1)
(Hadoop, 1)
Shuffle and Sort Output
(Big, [1])
(Data, [1])
(Hadoop, [1, 1, 1])
(is, [1, 1])
(powerful, [1])
(scalable, [1])
(uses, [1])
Reducer Output
Big 1
Data 1
Hadoop 3
is 2
powerful 1
scalable 1
uses 1
2.4 Java Implementation of Word Count
A. Mapper Class – WordMapper.java
The Mapper reads each line, divides it into words and generates a key-value pair for every word.
import java.io.IOException;
import java.util.StringTokenizer;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
public class WordMapper
extends Mapper<LongWritable, Text, Text, IntWritable> {
public void map(LongWritable key, Text value,
Context context)
throws IOException, InterruptedException {
StringTokenizer tokens =
new StringTokenizer(value.toString());
while (tokens.hasMoreTokens()) {
String word = tokens.nextToken();
context.write(
new Text(word),
new IntWritable(1)
);
}
}
}
Explanation:
- LongWritable represents the byte offset of the input line.
- Text represents the contents of the input line.
- StringTokenizer divides the line into individual words.
- context.write() generates intermediate key-value pairs.
- Each word is associated with an initial count of 1.
B. Reducer Class – WordReducer.java
The Reducer receives a word and its associated list of counts and calculates the total count.
import java.io.IOException;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
public class WordReducer
extends Reducer<Text, IntWritable, Text, IntWritable> {
public void reduce(Text key,
Iterable<IntWritable> values,
Context context)
throws IOException, InterruptedException {
int sum = 0;
for (IntWritable value : values) {
sum += value.get();
}
context.write(key, new IntWritable(sum));
}
}
The Reducer receives all intermediate values associated with a particular word and adds them to generate the final word count.
C. Driver Class – WordCount.java
The Driver configures the Mapper, Reducer, input path, output path and data types.
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
public class WordCount {
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
Job job = Job.getInstance(conf, "Word Count");
job.setJarByClass(WordCount.class);
job.setMapperClass(WordMapper.class);
job.setCombinerClass(WordReducer.class);
job.setReducerClass(WordReducer.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
FileInputFormat.addInputPath(
job, new Path(args[0])
);
FileOutputFormat.setOutputPath(
job, new Path(args[1])
);
System.exit(
job.waitForCompletion(true) ? 0 : 1
);
}
}
Important Driver Methods
| Method | Purpose |
|---|---|
| Job.getInstance() | Creates a MapReduce job. |
| setJarByClass() | Identifies the application JAR. |
| setMapperClass() | Specifies the Mapper class. |
| setReducerClass() | Specifies the Reducer class. |
| setCombinerClass() | Specifies the optional Combiner. |
| setOutputKeyClass() | Defines the output key type. |
| setOutputValueClass() | Defines the output value type. |
| waitForCompletion() | Submits the job and waits for completion. |
2.5 Executing a MapReduce Application
After compiling and packaging the Java application into a JAR file, the following commands can be used.
# Create input directory
hdfs dfs -mkdir -p /wordcount/input
# Upload input file
hdfs dfs -put input.txt /wordcount/input/
# Execute application
hadoop jar wordcount.jar WordCount \
/wordcount/input /wordcount/output
# Display output
hdfs dfs -cat /wordcount/output/part-r-*
3. How MapReduce Works
MapReduce processes large datasets through a sequence of distributed processing stages.
Figure 2: Conceptual MapReduce Processing Pipeline
In practice, partitioning, sorting and optional combining are integrated into map-side processing.
3.1 Input Splitting
The input dataset is logically divided into smaller units called InputSplits. Each InputSplit is normally assigned to one Mapper.
Consider a 512 MB input file with a typical split size of 128 MB.
↓
128 MB
↓
Mapper 1
128 MB
↓
Mapper 2
128 MB
↓
Mapper 3
128 MB
↓
Mapper 4
Figure 3: Parallel Processing Using Four InputSplits
An InputSplit is a logical division of data, whereas an HDFS block is a physical storage unit. They are often similar in size but are not necessarily identical.
3.2 Mapping Phase
Each Mapper processes its assigned InputSplit independently.
- Reads input records.
- Applies user-defined processing logic.
- Generates intermediate key-value pairs.
- Stores intermediate results on local storage for jobs with reducers.
Input: Hadoop Big Data
Mapper Output:
(Hadoop, 1)
(Big, 1)
(Data, 1)
Multiple Mappers can execute simultaneously on different nodes.
3.3 Combining Phase
A Combiner is an optional component that performs local aggregation of Mapper output before it is transferred to Reducers.
Without Combiner:
(Hadoop, 1)
(Hadoop, 1)
(Hadoop, 1)
With Combiner:
(Hadoop, 3)
Advantages of Combiner
- Reduces intermediate data size.
- Reduces network traffic.
- Improves processing efficiency.
- Reduces the workload of Reducers.
3.4 Partitioning Phase
The Partitioner determines which Reducer receives a particular intermediate key. The default Hadoop Partitioner is the HashPartitioner.
Here, R represents the number of Reducers.
All intermediate records having the same key must be sent to the same Reducer.
| Key | Assigned Reducer |
|---|---|
| North | Reducer 1 |
| South | Reducer 2 |
| East | Reducer 3 |
| West | Reducer 4 |
3.5 Shuffle and Sort Phase
Intermediate data is transferred from Mappers to Reducers, sorted by key and grouped.
Mapper Output:
(B, 1)
(A, 1)
(C, 1)
(A, 1)
(B, 1)
After Shuffle and Sort:
(A, [1, 1])
(B, [1, 1])
(C, [1])
3.6 Reducing Phase
The Reducer processes each key and its associated values.
Reducer Input:
(A, [1, 1, 1])
(B, [1, 1])
Reducer Output:
(A, 3)
(B, 2)
3.7 Output Phase
The final output is written to the configured output destination, typically HDFS.
When multiple Reducers are used, each Reducer generally generates a separate output file.
part-r-00000
part-r-00001
part-r-00002
_SUCCESS
The _SUCCESS file, when generated by the configured output committer, indicates successful job completion.
4. Anatomy of a MapReduce Job Run
The anatomy of a MapReduce job run describes the complete internal execution process of a MapReduce application, starting from job submission and ending with job completion.
Modern Hadoop uses YARN to manage MapReduce job execution.
4.1 Major Components
| Component | Function |
|---|---|
| Client | Submits the MapReduce application. |
| ResourceManager | Manages cluster-wide resources. |
| NodeManager | Manages containers on an individual worker node. |
| MRAppMaster | Coordinates MapReduce application execution. |
| Container | Provides allocated resources for executing tasks or ApplicationMaster. |
| HDFS | Stores input data, application resources and final output. |
| JobHistory Server | Provides information about completed jobs. |
4.2 MapReduce Job Execution Architecture
↓ Job Submission
↕ Resource Negotiation
↓ Task Coordination
Map Task Container
Reduce Task Container
Map Task Container
Reduce Task Container
↕
Figure 4: Simplified MapReduce Job Execution under YARN
4.3 Steps in a MapReduce Job Run
Step 1: Job Submission
The user submits the application using the Hadoop command or Java API. The client prepares the configuration, calculates input splits and makes application resources available in a shared staging location.
Step 2: Application Submission to ResourceManager
The client submits an application request to the ResourceManager, which accepts the application and schedules resources for starting the ApplicationMaster.
Step 3: Starting the ApplicationMaster
The ResourceManager allocates a container on a suitable worker node. The corresponding NodeManager launches the MRAppMaster.
Step 4: Job Initialization
The ApplicationMaster retrieves the configuration and input split information. It determines the required Map and Reduce tasks and creates the corresponding task objects.
Step 5: Resource Allocation
The ApplicationMaster requests containers from the ResourceManager. For Map tasks, Hadoop attempts to allocate containers close to the input data.
Step 6: Task Execution
The ApplicationMaster communicates with NodeManagers to launch task containers that execute Mapper and Reducer code.
Step 7: Progress Monitoring
Tasks periodically report progress and status. The ApplicationMaster monitors successful tasks, failed tasks, counters and overall job progress.
Step 8: Job Completion
After all required tasks complete successfully, the ApplicationMaster finalizes the job and unregisters from the ResourceManager. The final output is available in the configured output directory.
Step 9: Job History
The JobHistory Server provides information about completed jobs, including execution time, task details, counters, diagnostics and failures.
4.4 Hadoop 1.x vs Hadoop 2.x and Later
| Hadoop 1.x | Hadoop 2.x and Later |
|---|---|
| JobTracker manages jobs and resources. | ResourceManager manages cluster resources. |
| TaskTracker executes tasks. | NodeManager manages task containers. |
| Centralized job coordination. | Application-specific coordination through ApplicationMaster. |
| Fixed Map and Reduce slots. | Flexible container-based allocation. |
| Primarily supports MapReduce. | Supports multiple processing frameworks. |
| Limited scalability compared with YARN. | Improved scalability and resource utilization. |
5. Job Scheduling in MapReduce
Job scheduling is the process of determining when and where submitted jobs and their tasks should execute in a Hadoop cluster.
5.1 Objectives of Job Scheduling
- Efficient utilization of cluster resources.
- Reduction of job waiting time.
- Fair distribution of resources.
- Support for multiple users and applications.
- Improved job throughput.
- Data locality.
- Prevention of resource starvation.
5.2 Types of Scheduling Algorithms
A. FIFO Scheduler
FIFO stands for First In, First Out. Jobs are generally processed in submission order, with priority also relevant in traditional FIFO scheduling.
Advantages: Simple implementation, easy management and low scheduling overhead.
Disadvantages: Large jobs may delay smaller jobs and increase waiting time.
B. Capacity Scheduler
The Capacity Scheduler divides cluster resources among multiple organizational queues. Each queue is configured with a guaranteed share of cluster capacity, subject to resource availability and scheduling policies.
CSE Department: 40%
AIML Department: 35%
Research Department: 25%
Unused capacity may be utilized by other queues depending on configuration.
Advantages: Multi-tenancy, guaranteed capacity, hierarchical queues and efficient resource sharing.
Disadvantages: Requires proper queue configuration and administration.
C. Fair Scheduler
The Fair Scheduler attempts to distribute resources fairly among running applications over time.
If only one job is running, it may utilize most or all available resources. When additional jobs arrive, resources are gradually shared according to configured scheduling policies and weights.
One Active Job
Two Active Jobs
Three Active Jobs
Illustrative allocation for equal-weight jobs with sufficient demand.
Advantages: Reduces waiting time for smaller jobs, promotes fairness and supports multiple users.
Disadvantages: More complex scheduling and resource management.
5.3 Comparison of Scheduling Algorithms
| Feature | FIFO | Capacity | Fair |
|---|---|---|---|
| Scheduling Basis | Submission order | Queue capacity | Fair resource share |
| Resource Sharing | Limited | Queue-based | Dynamic |
| Multi-user Support | Basic | Excellent | Excellent |
| Configuration | Simple | Complex | Moderate to complex |
| Suitable Environment | Small clusters | Large organizations | Shared clusters |
5.4 Data Locality
Data locality refers to executing computation close to the location where the input data is stored.
Instead of transferring large amounts of data to the processing node, Hadoop attempts to move computation to the data.
- Node-local: The task executes on the node containing the required data.
- Rack-local: The task executes on another node within the same rack.
- Off-rack: The task executes on a node in a different rack.
Node-local execution is generally preferred because it minimizes network communication.
6. Shuffle and Sort in MapReduce
Shuffle and Sort is one of the most important phases of MapReduce. It connects the Mapper and Reducer phases.
- Shuffle: Transferring intermediate Mapper output to the appropriate Reducers.
- Sort: Arranging intermediate records according to their keys so that associated values can be grouped together.
6.1 Shuffle and Sort Architecture
(A, 1)
(B, 1)
(A, 1)
(B, 1)
(A, 1)
(B, 1)
↓
Transfer and group identical keys
↓
(A, [1, 1, 1])
↓
(A, 3)
(B, [1, 1, 1])
↓
(B, 3)
Figure 5: Shuffle and Sort Mechanism
6.2 Map-Side Processing
A. Buffering
Intermediate key-value pairs generated by the Mapper are initially stored in an in-memory buffer.
B. Partitioning
Each intermediate record is assigned to a partition corresponding to a Reducer.
C. Sorting
Intermediate records are sorted by partition and key.
D. Spilling
When the buffer reaches a configured threshold, its contents are written to the local disk. This operation is known as spilling.
E. Combining
If a Combiner is configured, it may perform local aggregation during spilling or merging.
F. Merging
Multiple spill files are merged into a consolidated map output file with separate partitions for the Reducers.
6.3 Reduce-Side Processing
- Copy Phase: Each Reducer retrieves its corresponding partition from completed Mappers over the network.
- Merge Phase: Intermediate data received from different Mappers is merged.
- Sort and Group Phase: Records are sorted and grouped according to their keys.
- Reduce Phase: The Reducer processes each key and its associated values.
6.4 Importance of Shuffle and Sort
Shuffle and Sort ensures that all values belonging to the same key are processed together. However, it can be one of the most expensive phases because it involves network communication, disk operations, sorting, merging and memory consumption.
Performance can be improved using suitable Combiners, intermediate data compression, efficient partitioning and appropriate memory configuration.
7. Task Execution in MapReduce
A MapReduce job consists of multiple individual tasks that execute across the Hadoop cluster.
7.1 Types of Tasks
- Map Task: Processes an InputSplit and generates intermediate records.
- Reduce Task: Processes grouped intermediate records and generates final results.
7.2 Map Task Execution
- Reads the assigned InputSplit.
- Uses RecordReader to obtain input key-value pairs.
- Invokes the Mapper function for each record.
- Buffers intermediate output.
- Partitions and sorts intermediate records.
- Spills and merges data on local storage.
- Reports completion to the ApplicationMaster.
7.3 Reduce Task Execution
- Retrieves intermediate partitions from Mappers.
- Merges intermediate data.
- Sorts and groups records by key.
- Invokes the Reducer function for each key.
- Writes final results using RecordWriter.
- Reports successful completion.
7.4 Task and Task Attempt
A task represents a logical unit of work, whereas a task attempt represents a particular execution of that task.
Map Task 1
Attempt 1 - Failed
Attempt 2 - Successful
If a task fails, Hadoop can create another attempt without restarting the entire job.
7.5 Speculative Execution
Speculative execution is a mechanism used to improve job completion time by handling unusually slow-running tasks. Such tasks are commonly called stragglers.
Hadoop may launch a duplicate attempt of a slow task on another node when speculative execution is enabled and scheduling conditions permit it.
Illustrative Example
Task A – Completed in 4 minutes
Task B – Completed in 5 minutes
Original Task C – Still running
Duplicate Task C – Starts at minute 5 and finishes at minute 8
Result: The duplicate attempt completes first. The original slow attempt is cancelled.
Speculative execution is useful when a task is slow because of hardware problems, overloaded nodes or resource contention. However, unnecessary speculative execution may consume additional cluster resources.
7.6 Map-Only Jobs
Some applications do not require aggregation. Examples include data filtering, data cleaning, format conversion and extracting selected records.
job.setNumReduceTasks(0);
The Mapper output is directly written to the configured output destination.
8. Failures in MapReduce
Fault tolerance is an important feature of Hadoop MapReduce. Since Hadoop clusters may contain hundreds or thousands of computers, hardware and software failures are expected.
Hadoop provides mechanisms to detect failures and recover automatically.
8.1 Types of Failures
A. Task Failure
A task may fail because of programming errors, invalid input data, insufficient memory, runtime exceptions, disk problems or network problems.
The ApplicationMaster may restart the failed task by creating a new task attempt. If the configured maximum number of attempts is exceeded, the job may fail.
B. NodeManager Failure
A NodeManager may fail because of hardware problems, operating system crashes or network disconnection.
The ResourceManager detects unavailable NodeManagers through missing heartbeats. Affected tasks may be rescheduled on healthy nodes. Completed Map tasks may also need to execute again if their intermediate output is no longer available.
C. ApplicationMaster Failure
If the ApplicationMaster fails, the ResourceManager may launch another ApplicationMaster attempt. Depending on recovery configuration, the new ApplicationMaster may recover information about previously completed tasks.
D. ResourceManager Failure
ResourceManager failure can interrupt resource allocation and application management.
Hadoop supports ResourceManager High Availability using Active and Standby ResourceManagers. When properly configured, the Standby ResourceManager can take over if the Active ResourceManager fails.
E. Shuffle Failure
A Reducer may fail to retrieve intermediate data from a Mapper because of network or storage problems.
Hadoop attempts to retrieve the data again. If the map output is permanently unavailable, the corresponding Map task may be re-executed.
F. DataNode Failure
HDFS stores multiple replicas of data blocks according to its replication configuration. If a DataNode fails, Hadoop can retrieve input data from another available replica.
8.2 Failure Recovery Mechanism
↓
↓
↓
Reschedule Task
↓
Continue Execution
Job May Fail
Figure 6: Task Failure Recovery Process
8.3 Failure Handling Summary
| Failure | Recovery Mechanism |
|---|---|
| Map Task Failure | Re-execute Map task. |
| Reduce Task Failure | Re-execute Reduce task. |
| NodeManager Failure | Reschedule affected tasks. |
| ApplicationMaster Failure | Restart ApplicationMaster, subject to retry limits. |
| ResourceManager Failure | High Availability failover, if configured. |
| DataNode Failure | Retrieve data from available replicas. |
| Slow Task | Speculative execution, if enabled. |
9. MapReduce Types and Formats
MapReduce supports different data types and input/output formats to process various types of datasets.
9.1 MapReduce Data Types
Hadoop provides specialized serializable data types for efficient storage and network communication. These types generally implement the Writable interface. Keys used for standard sorting typically implement WritableComparable.
| Hadoop Type | Equivalent Java Type | Description |
|---|---|---|
| IntWritable | int | Integer value |
| LongWritable | long | Long integer value |
| FloatWritable | float | Floating-point value |
| DoubleWritable | double | Double-precision value |
| BooleanWritable | boolean | Boolean value |
| Text | String | UTF-8 encoded text |
| BytesWritable | byte[] | Binary data |
| NullWritable | No direct equivalent | Absent key or value |
| ArrayWritable | Array | Collection of Writable elements |
| MapWritable | Map | Collection of key-value pairs |
Why Hadoop Uses Writable Types
Hadoop uses Writable types because they support efficient serialization and deserialization.
- Serialization: Converting an object into a byte representation for storage or transmission.
- Deserialization: Reconstructing an object from its byte representation.
9.2 InputFormat
InputFormat determines how input files are divided into InputSplits and how input records are read.
It creates logical input splits and provides a RecordReader to convert input data into key-value records.
A. TextInputFormat
TextInputFormat is the default input format in Hadoop MapReduce. It treats each line of a text file as a record.
Input:
Hadoop is powerful
Big Data Analytics
Output Records:
(0, "Hadoop is powerful")
(19, "Big Data Analytics")
The key represents the byte offset and the value represents the contents of the line. The example assumes ASCII text and a single newline character.
B. KeyValueTextInputFormat
This format treats each input line as a key-value pair separated by a delimiter, which is a tab by default.
Input:
101 Ravi
102 Sita
103 Kumar
Output:
(101, Ravi)
(102, Sita)
(103, Kumar)
Both keys and values are represented using the Text data type.
C. SequenceFileInputFormat
Reads Hadoop SequenceFiles containing binary key-value records. It is useful for efficient storage and processing of intermediate datasets.
D. NLineInputFormat
Creates input splits based on a configured number of lines. It is useful when each group of input lines should be processed by a separate Mapper.
E. CombineFileInputFormat
Provides a base class for combining multiple small files into larger logical input splits. It helps reduce the overhead of launching too many Map tasks for small files. A suitable RecordReader implementation is required.
F. DBInputFormat
Allows MapReduce applications to retrieve input records from relational databases using JDBC.
9.3 Comparison of Input Formats
| Input Format | Suitable Data |
|---|---|
| TextInputFormat | Text files and log files |
| KeyValueTextInputFormat | Delimiter-separated key-value records |
| SequenceFileInputFormat | Binary key-value datasets |
| NLineInputFormat | Line-based processing |
| CombineFileInputFormat | Collections of small files |
| DBInputFormat | Relational database records |
9.4 OutputFormat
OutputFormat defines how the final results of a MapReduce application are written.
A. TextOutputFormat
It is the default output format. It writes output key-value pairs as text, typically separated by a tab.
Hadoop 5
Big 3
Data 4
B. SequenceFileOutputFormat
Writes output records in Hadoop’s binary SequenceFile format. It is useful when the output of one MapReduce job becomes the input of another.
C. MapFileOutputFormat
Writes output in Hadoop MapFile format, which contains sorted key-value data and an index for efficient key-based access.
D. NullOutputFormat
Does not write output records to files. It is useful when a job does not require conventional file output.
E. DBOutputFormat
Writes output records into a relational database using JDBC.
9.5 InputFormat vs OutputFormat
| InputFormat | OutputFormat |
|---|---|
| Defines how input data is read. | Defines how output data is written. |
| Creates InputSplits. | Configures output writing. |
| Uses RecordReader. | Uses RecordWriter. |
| Converts input into key-value pairs. | Stores final key-value pairs. |
| Default: TextInputFormat. | Default: TextOutputFormat. |
10. MapReduce Features
Hadoop MapReduce provides several features that make it suitable for large-scale distributed batch processing.
10.1 Parallel Processing
Multiple tasks execute simultaneously on different nodes, reducing processing time for suitable large-scale computational problems.
10.2 Scalability
The processing capacity of Hadoop can be increased by adding more computers to the cluster. This approach is called horizontal scaling or scaling out.
10.3 Fault Tolerance
Hadoop automatically detects task failures and can re-execute failed tasks on available nodes.
10.4 Data Locality
Hadoop attempts to execute Map tasks close to the input data, reducing network communication.
10.5 Distributed Processing
Large computational problems are divided into smaller tasks and distributed across multiple machines.
10.6 Cost Effectiveness
Hadoop can operate on clusters of commodity hardware instead of requiring a single expensive high-performance computer.
10.7 Flexibility
MapReduce supports structured, semi-structured and unstructured data through appropriate input formats and processing logic.
10.8 Automatic Load Distribution
The framework distributes tasks across available cluster resources based on scheduling policies.
10.9 Language Support
Although Hadoop MapReduce is primarily implemented in Java, Hadoop Streaming allows programs written in languages such as Python to be used as Mappers and Reducers.
10.10 Counters
Counters collect statistical information about job execution.
- Number of Map input records.
- Number of Map output records.
- Number of Reduce input records.
- Number of Reduce output records.
- Number of spilled records.
- Number of bytes read and written.
Applications can also define custom counters. For example, a student data processing application may maintain a counter for invalid student records.
10.11 Data Compression
Hadoop supports compression of input data, intermediate Mapper output and final output.
Compression can reduce storage requirements and network communication, although it introduces additional CPU processing.
Common compression formats and codecs include Gzip, Bzip2, Snappy and LZ4.
10.12 Distributed Cache and Resource Localization
Hadoop allows supporting files such as dictionaries, lookup tables and configuration files to be made available to task containers.
For example, a sentiment analysis application can distribute a dictionary containing positive and negative words to all Mapper tasks.
10.13 Job Chaining
Multiple MapReduce jobs can be executed sequentially, where the output of one job becomes the input of another.
↓
↓
↓
↓
Figure 7: MapReduce Job Chaining
10.14 Limitations of MapReduce
| Limitation | Explanation |
|---|---|
| High Latency | Not suitable for immediate response requirements. |
| Disk Overhead | Intermediate processing and job chaining involve disk operations. |
| Iterative Processing | Repeated MapReduce jobs may be inefficient. |
| Programming Complexity | Complex analytical problems may require multiple jobs. |
| Small File Problem | Large numbers of small files increase processing overhead. |
| Real-time Processing | Traditional MapReduce is designed primarily for batch processing. |
| Data Skew | Uneven key distribution may overload particular Reducers. |
Apache Spark is often preferred for iterative and interactive analytics, while Apache Flink supports continuous stream processing.
11. Hadoop Environment
The Hadoop environment refers to the hardware, software, configuration files and distributed services required to execute Hadoop applications.
11.1 Hadoop Environment Architecture
MapReduce Applications, Hive, Pig, Spark
MapReduce and Other Processing Frameworks
YARN
HDFS
Cluster Nodes, CPU, Memory, Storage and Network
Figure 8: Simplified Hadoop Environment Architecture
The major Hadoop modules are Hadoop Common, HDFS, YARN and MapReduce.
11.2 Hadoop Operating Modes
A. Standalone Mode
Standalone mode is also called Local Mode. Hadoop runs as a single Java process using the local file system.
- No distributed Hadoop daemons are required.
- Suitable for development and debugging.
- Easy to configure.
- Does not provide actual distributed processing.
B. Pseudo-Distributed Mode
Hadoop daemons run as separate processes on a single computer.
- Simulates a distributed environment.
- Supports HDFS and, when configured, YARN.
- Suitable for learning and testing.
- Requires limited hardware resources.
C. Fully Distributed Mode
Hadoop runs across multiple interconnected computers.
- Provides actual distributed storage and processing.
- Supports large-scale datasets.
- Offers scalability and fault tolerance.
- Suitable for production environments.
11.3 Comparison of Hadoop Operating Modes
| Feature | Standalone | Pseudo-distributed | Fully Distributed |
|---|---|---|---|
| Computers | One | One | Multiple |
| Daemons | Not required | Separate processes | Distributed |
| File System | Local | HDFS | HDFS |
| Distributed Processing | No | Simulated | Actual |
| Scalability | Limited | Limited | High |
| Usage | Debugging | Learning and testing | Production |
11.4 Hadoop Configuration Files
| Configuration File | Purpose |
|---|---|
| core-site.xml | Core Hadoop settings and default file system. |
| hdfs-site.xml | HDFS replication and storage settings. |
| mapred-site.xml | MapReduce framework and execution settings. |
| yarn-site.xml | YARN resource management settings. |
| hadoop-env.sh | Hadoop environment variables. |
| workers | Worker hosts used by cluster management scripts. |
Example: core-site.xml
<configuration>
<property>
<name>fs.defaultFS</name>
<value>hdfs://localhost:9000</value>
</property>
</configuration>
Example: hdfs-site.xml
<configuration>
<property>
<name>dfs.replication</name>
<value>1</value>
</property>
</configuration>
Example: mapred-site.xml
<configuration>
<property>
<name>mapreduce.framework.name</name>
<value>yarn</value>
</property>
</configuration>
Example: yarn-site.xml
<configuration>
<property>
<name>yarn.nodemanager.aux-services</name>
<value>mapreduce_shuffle</value>
</property>
</configuration>
11.5 Common Hadoop Commands
| Command | Purpose |
|---|---|
| hadoop version | Displays Hadoop version. |
| hdfs dfs -ls / | Lists HDFS files and directories. |
| hdfs dfs -mkdir | Creates a directory. |
| hdfs dfs -put | Uploads a file to HDFS. |
| hdfs dfs -get | Downloads a file from HDFS. |
| hdfs dfs -cat | Displays file contents. |
| hdfs dfs -rm | Removes a file. |
| hadoop jar | Executes a packaged Hadoop application. |
| yarn application -list | Lists YARN applications. |
| yarn node -list | Lists YARN cluster nodes. |
| jps | Displays running local Java processes. |
12. Introduction to YARN
YARN is the resource management and application execution framework introduced in Hadoop 2.x.
YARN separates resource management from application-specific processing, allowing multiple distributed computing frameworks to share the same Hadoop cluster.
12.1 Need for YARN
In Hadoop 1.x, the JobTracker was responsible for both resource management and job execution management.
This centralized architecture resulted in several limitations:
- High workload on the JobTracker.
- Limited scalability.
- Fixed Map and Reduce slots.
- Inefficient resource utilization.
- Limited support for other processing frameworks.
YARN addresses these limitations by separating cluster-wide resource management from application-level coordination.
12.2 YARN Architecture
↓ Application Submission
↓ Container Allocation
Figure 9: YARN Architecture
12.3 Components of YARN
A. ResourceManager (RM)
The ResourceManager is the central authority responsible for managing cluster-wide computing resources.
It performs resource allocation, application acceptance and coordination with NodeManagers.
The ResourceManager contains two major components:
- Scheduler: Allocates resources to applications based on resource requirements, queue capacities and scheduling policies. It does not execute application tasks directly.
- ApplicationsManager: Accepts application submissions and manages the allocation and restarting of ApplicationMaster containers.
B. NodeManager (NM)
The NodeManager is a worker-node service responsible for managing resources and containers on an individual node.
Its responsibilities include launching containers, monitoring resource utilization, reporting node health and communicating with the ResourceManager.
C. ApplicationMaster (AM)
The ApplicationMaster manages the execution of a particular application. Each application has its own ApplicationMaster.
- Negotiates resources with the ResourceManager.
- Requests containers.
- Coordinates application task execution.
- Monitors task progress.
- Handles application-specific failures.
For MapReduce applications, it is called the MRAppMaster.
D. Container
A container represents an allocation of computing resources on a worker node. It may include memory, virtual CPU cores and other supported resource types.
Example: YARN Worker Node
Total Allocatable Resources: 16 GB RAM and 8 vCores
4 GB RAM
2 vCores
4 GB RAM
2 vCores
4 GB RAM
2 vCores
4 GB RAM
2 vCores
Illustrative allocation assuming all 16 GB and 8 vCores are configured as allocatable YARN resources.
Unlike Hadoop 1.x fixed slots, YARN containers allow flexible allocation of resources according to application requirements.
12.4 Working of YARN
- The client submits an application to the ResourceManager.
- The ResourceManager allocates a container for the ApplicationMaster.
- A NodeManager launches the ApplicationMaster.
- The ApplicationMaster registers with the ResourceManager.
- The ApplicationMaster requests additional containers.
- The ResourceManager allocates suitable containers.
- The ApplicationMaster communicates with NodeManagers to launch tasks.
- Tasks execute and report progress.
- The ApplicationMaster completes the application and releases resources.
12.5 Advantages of YARN
- Improved cluster scalability.
- Efficient resource utilization.
- Flexible resource allocation.
- Support for multiple processing frameworks.
- Separation of resource management from application processing.
- Improved multi-user support.
- Support for resource management High Availability.
- Better utilization of distributed computing infrastructure.
12.6 MapReduce vs YARN
| MapReduce | YARN |
|---|---|
| Distributed data processing framework. | Distributed resource management framework. |
| Processes large datasets. | Allocates cluster computing resources. |
| Uses Mapper and Reducer functions. | Uses ResourceManager, NodeManager and ApplicationMaster. |
| Primarily designed for batch processing. | Supports multiple application frameworks. |
| Performs computational operations. | Coordinates resource allocation and execution infrastructure. |
| Can execute on YARN. | Supports MapReduce, Spark and other compatible frameworks. |
13. Real-World Applications of MapReduce
13.1 E-Commerce Sales Analysis
An e-commerce organization generates millions of transaction records every day. MapReduce can be used to calculate product-wise sales, category-wise revenue and region-wise sales performance.
| Product | Sales Amount |
|---|---|
| Laptop | ₹50,000 |
| Mobile | ₹20,000 |
| Laptop | ₹60,000 |
| Mobile | ₹15,000 |
| Tablet | ₹25,000 |
Mapper Output
(Laptop, 50000)
(Mobile, 20000)
(Laptop, 60000)
(Mobile, 15000)
(Tablet, 25000)
Shuffle and Sort Output
(Laptop, [50000, 60000])
(Mobile, [20000, 15000])
(Tablet, [25000])
Reducer Output – Total Sales
Laptop – ₹1,10,000
Mobile – ₹35,000
Tablet – ₹25,000
The organization can use these results to understand product performance and make inventory-related decisions.
13.2 Educational Data Analytics
An educational institution can use MapReduce to process large volumes of student academic records.
Consider the following dataset. The objective is to calculate department-wise average marks.
| Department | Student | Marks |
|---|---|---|
| CSE | Student A | 80 |
| AIML | Student B | 90 |
| CSE | Student C | 70 |
| AIML | Student D | 85 |
| ECE | Student E | 75 |
Mapper Output
(CSE, (80, 1))
(AIML, (90, 1))
(CSE, (70, 1))
(AIML, (85, 1))
(ECE, (75, 1))
Shuffle and Sort Output
(CSE, [(80,1), (70,1)])
(AIML, [(90,1), (85,1)])
(ECE, [(75,1)])
Reducer Output
CSE – 75
AIML – 87.5
ECE – 75
By maintaining both the sum and count, the application can safely perform partial aggregation using a Combiner.
13.3 Other Applications
| Application Area | Use of MapReduce |
|---|---|
| Healthcare | Processing historical patient records and disease statistics. |
| Banking | Analyzing historical transactions and suspicious patterns. |
| Social Media | Hashtag counting, sentiment aggregation and trend analysis. |
| Search Engines | Building indexes from large document collections. |
| Telecommunications | Processing call detail records. |
| Transportation | Analyzing historical traffic and vehicle movements. |
| Cybersecurity | Analyzing large volumes of security logs. |
| Education | Student performance and feedback analysis. |
| Retail | Customer purchasing behavior and sales analysis. |
| Scientific Research | Processing large experimental datasets. |
14. Important Differences for Examinations
14.1 Mapper vs Reducer
| Mapper | Reducer |
|---|---|
| Processes input records. | Processes grouped intermediate records. |
| Generates intermediate key-value pairs. | Generates final key-value pairs. |
| Executes independently for each InputSplit. | Receives partitions from multiple Mappers. |
| Number depends on InputSplits. | Number is configurable. |
| Usually performs filtering and transformation. | Usually performs aggregation and summarization. |
14.2 Combiner vs Reducer
| Combiner | Reducer |
|---|---|
| Performs local aggregation. | Performs final aggregation. |
| Executes on map-side data. | Processes data received from Mappers. |
| Optional optimization. | Required for jobs needing reduce-side processing. |
| Execution is not guaranteed. | Required Reduce tasks must complete successfully. |
| Reduces network traffic. | Produces final analytical results. |
14.3 Shuffle vs Sort
| Shuffle | Sort |
|---|---|
| Transfers intermediate data. | Arranges intermediate data by key. |
| Involves network communication. | Involves comparison, sorting and merging. |
| Delivers partitions to appropriate Reducers. | Enables grouping of identical keys. |
14.4 HDFS Block vs InputSplit
| HDFS Block | InputSplit |
|---|---|
| Physical storage unit. | Logical processing unit. |
| Managed by HDFS. | Created by InputFormat. |
| Used for distributed storage. | Used for distributed processing. |
| Can have multiple replicas. | Contains information about a portion of input data. |
14.5 ResourceManager vs NodeManager
| ResourceManager | NodeManager |
|---|---|
| Manages cluster-wide resources. | Manages resources on an individual node. |
| Allocates containers. | Launches and monitors containers. |
| Receives node status information. | Sends heartbeat and status information. |
| Centralized resource management. | Node-level resource management. |
15. Important Terminology
| Term | Definition |
|---|---|
| Job | Complete MapReduce computational application. |
| Task | Individual unit of work within a job. |
| Task Attempt | Particular execution of a task. |
| InputSplit | Logical portion of input data. |
| Mapper | Function that generates intermediate key-value pairs. |
| Reducer | Function that processes grouped intermediate values. |
| Combiner | Optional local aggregation function. |
| Partitioner | Determines the destination Reducer. |
| Shuffle | Transfer of intermediate data to Reducers. |
| Sort | Arrangement of intermediate records by key. |
| Spill | Writing buffered intermediate data to disk. |
| Serialization | Conversion of objects into bytes. |
| Data Locality | Executing computation close to input data. |
| Heartbeat | Periodic status communication between distributed components. |
| Speculative Execution | Launching duplicate attempts of unusually slow tasks. |
| Container | Allocation of computing resources on a node. |
| Fault Tolerance | Ability to continue or recover from failures. |
| Data Skew | Uneven distribution of data among processing tasks. |
| YARN | Hadoop resource management framework. |
16. Important Examination Questions
Part A – Short Answer Questions (2 Marks)
- Define MapReduce.
- What is an InputSplit?
- What is the purpose of a Combiner?
- Define Partitioner in MapReduce.
- What is Shuffle and Sort?
- What is speculative execution?
- Define data locality.
- What are Writable data types?
- What is the purpose of InputFormat?
- What is OutputFormat?
- Define YARN.
- What is a YARN container?
- Differentiate between a task and a task attempt.
- What is the role of ApplicationMaster?
- List the operating modes of Hadoop.
Part B – Descriptive Questions (5/10 Marks)
- Explain the MapReduce framework with a suitable architecture diagram.
- Develop a MapReduce application for counting the occurrences of words in a document.
- Explain the working of MapReduce with a suitable example.
- Explain the anatomy of a MapReduce job run with a neat diagram.
- Compare FIFO, Capacity and Fair scheduling algorithms.
- Explain map-side and reduce-side Shuffle and Sort operations.
- Explain task execution and speculative execution in MapReduce.
- Discuss different types of failures and their recovery mechanisms in MapReduce.
- Explain different MapReduce data types, input formats and output formats.
- Discuss the important features and limitations of MapReduce.
- Explain different Hadoop operating modes and configuration files.
- Explain YARN architecture and its major components.
- Discuss the working of YARN in executing a MapReduce application.
- Apply the MapReduce framework to calculate department-wise average student marks.
- Compare Hadoop 1.x and YARN-based MapReduce execution architectures.
17. Unit Summary
MapReduce is a distributed batch processing framework that enables large-scale data processing through parallel execution of Map and Reduce tasks.
The complete processing mechanism involves input splitting, mapping, optional combining, partitioning, shuffling, sorting, reducing and output generation.
Hadoop provides scheduling mechanisms, data locality, speculative execution, failure recovery, serialization, compression and different input/output formats to improve distributed processing efficiency.
YARN enhances the Hadoop environment by separating resource management from application execution management. It allows multiple distributed processing frameworks to share the same computing infrastructure.
Hadoop – Three Fundamental Responsibilities
HDFS
Distributed Storage
Stores the data
MapReduce
Distributed Processing
Processes the data
YARN
Resource Management
Manages the resources
Conclusion
Understanding MapReduce is essential for learning distributed computing and Big Data Analytics. Its programming model, distributed execution mechanisms, scheduling techniques and fault-tolerant architecture provide a strong foundation for understanding modern Big Data processing frameworks.
Big Data Frameworks & Analytics | Unit III | IV B.Tech