1. Home
  2. Explore
  3. Computer Science
  4. Hadoop Overview

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Hadoop Overview

Hadoop Study Notes

Big Data Growth Drivers

The exponential growth of data is driven by several key factors:

  • Proliferation of personal devices: In the 1970s and 1980s, few people used computers. Today, everyone owns smartphones, laptops, and tablets, each generating data continuously.

  • Internet of Things (IoT): Smart appliances and interconnected devices form a network of things, communicating and generating data automatically.

  • Social media: Billions of people share thoughts, images, and videos on platforms like Facebook, Twitter, Instagram, and YouTube.

Data generation statistics (per 60 seconds):

  • Facebook: ~4 million likes

  • Twitter: ~300,000 tweets

  • Reddit: ~18,000 user cast votes

  • Instagram: >1 million likes

  • YouTube: ~300 hours of new video uploaded

Cisco’s projections show that global data traffic grew from 3.7 exabytes in 2015 to an estimated 30.6 exabytes by 2020. One exabyte equals 101810^{18}1018 bytes.

Three major reasons for this rise according to Cisco:

  • Adapting to smarter mobile devices: Modern smartphones run apps that generate vast amounts of data.

  • Defining cell network advances: Evolution from 2G to 3G, 4G, and soon 5G enables faster, easier communication, encouraging more data sharing.

  • Reviewing tiered pricing: Affordable unlimited and shared data plans make high data usage feasible for families.

The number of new mobile users is also staggering: 217 new users every 60 seconds.

What is Big Data?

Big data refers to datasets so large or complex that traditional data processing systems cannot store or process them efficiently. It is both a collection of massive data and a problem statement — traditional systems were never designed to handle such volume, variety, and velocity.

Big data is a problem because traditional systems cannot store or process the enormous amount of data generated at high speed.

The 5Vs of Big Data (IBM)

These characteristics help identify whether a dataset qualifies as big data:

  • Volume: The sheer amount of data is so huge that traditional storage systems cannot handle it. When the data size exceeds what legacy systems can manage, a big data solution is needed.

  • Variety: Data comes from diverse sources — text, images, videos, JSON, logs — and in different formats. Approximately 90% of data is unstructured (e.g., social media posts, photos). This unstructured data is valuable for profiling customers and making business decisions, but traditional systems fail to process it.

  • Velocity: The speed at which data is generated and must be processed. For example, a web service might handle thousands of transactions per second, but in the big data world, sensors and GPS devices generate millions of events per second. The inability to keep up with such velocity signals a big data problem.

  • Value: Data must provide useful insights to drive business decisions. If the dataset does not yield valuable information, it is garbage. Identifying which data has value is itself a challenge.

  • Veracity: Data can be incomplete, incorrect, or unreliable. Systems must handle missing values, errors, and inconsistencies — trustworthiness of data cannot be assumed. Application developers must integrate, clean, and extract only meaningful data.

The Solution: Apache Hadoop

Hadoop is an open-source framework that enables distributed storage and parallel processing of large datasets across clusters of commodity hardware. It addresses the two main problems of big data:

  1. Storage — Solved by HDFS (Hadoop Distributed File System), which distributes data across multiple machines.

  2. Processing — Solved by MapReduce, a programming model that processes data in parallel across the cluster.

Story Analogy: Bob’s Restaurant

  • Traditional scenario: A single cook with one food shelf processes 2 orders per hour. Data equivalent: steady, structured data handled easily.

  • Problem: Bob starts taking online orders; orders rise to 10 per hour. The cook cannot keep up. Similarly, traditional systems cannot handle high velocity and variety.

  • Solution: Hire more cooks (multiple processors). But having one food shelf creates a bottleneck (single data warehouse). So Bob gives each cook their own food shelf (data locality) and divides orders into subtasks (meat and sauce prepared in parallel) — this is MapReduce. The head chef combines the results — that’s the Reduce phase.

Key Hadoop concepts from the analogy:

  • Data locality: Processing units have local access to data (like each chef having their own shelf).

  • Map: Parallel execution of subtasks.

  • Reduce: Combining intermediate results into the final output.

Hadoop Architecture (Master/Slave)

Hadoop follows a master/slave architecture:

  • Master node: Manages and monitors slave nodes. Tracks task progress and maintains backup plans.

  • Slave nodes: Perform actual data storage and processing.

Office Analogy

A project manager (master) manages a team (slaves) of four: John, James, Bob, Alice. Each member works on a project (A, B, C, D). When Bob goes on leave, the manager assigns project C to John as a backup — even if one member fails, work continues. Similarly, Hadoop master nodes keep backups for all tasks.

HDFS Core Components

NameNode and DataNode

  • NameNode (Master): Maintains and manages the metadata (information about data). It tracks which data blocks are stored on which DataNodes and receives heartbeats (signals) from DataNodes to confirm they are alive.

  • DataNode (Slave): Stores actual data in data blocks. Multiple DataNodes form the distributed storage.

Secondary NameNode

The Secondary NameNode is not a backup for the NameNode. Its role is checkpointing:

  • FSImage: A file containing the complete state of the file system namespace since the NameNode started. Large, stored on disk.

  • EditLog: Records the most recent changes (e.g., last one hour). Small, stored in RAM.

  • Checkpointing: The Secondary NameNode periodically combines the EditLog with the FSImage to create a new FSImage, updating it with recent changes. This prevents the EditLog from growing too large (which would consume RAM and slow the NameNode) and also helps in failure recovery.

  • Default checkpoint interval: every hour. During checkpoint, new changes are written to a new EditLog until the next checkpoint.

Checkpointing is the process of merging the EditLog with the FSImage to produce an updated FSImage.

HDFS Data Storage (Blocks)

HDFS is a block-structured file system. Files are divided into blocks of fixed size.

  • Default block size: 128 MB (configurable).

  • Example: A 380 MB file splits into three blocks: two of 128 MB, and the last of 124 MB (remaining size).

  • These blocks are distributed across DataNodes. The last block uses only the needed space, saving storage (e.g., 4 MB saved in this small example; huge savings with thousands of files).

Advantages of distributed file system:

  1. Abstraction of large storage: A 3 TB file can be stored across three 1 TB DataNodes, appearing as a single 3 TB system.

  2. Scalability: Adding more DataNodes increases total capacity; HDFS handles the distribution automatically.

  3. Parallel processing: Reading/writing in parallel across nodes reduces time. A job that takes 4 seconds on one node may take 1 second on four nodes.

Fault Tolerance: Replication

HDFS provides fault tolerance through replication. Each data block has multiple copies.

  • Default replication factor: 3 (each block is stored on three different DataNodes).

  • If a DataNode fails, other copies remain available. Even if two copies are lost, one remains.

  • Replication happens automatically when files are written; users do not need to manage it.

"Never put all your eggs in the same basket" — HDFS spreads replicas across nodes to protect against hardware failure.

HDFS Write Mechanism (Step-by-Step)

Writing a file involves three phases:

  1. Pipeline setup:

    • Client requests NameNode to write a block (e.g., Block A).

    • NameNode returns IP addresses of three DataNodes (e.g., DN1, DN4, DN6) where replicas should be stored.

    • Client contacts DN1; DN1 contacts DN4; DN4 contacts DN6. All confirm readiness, establishing a pipeline: DN1 → DN4 → DN6.

  2. Actual writing:

    • Client writes Block A to DN1.

    • DN1 copies the block to DN4, which copies to DN6.

    • Writing happens sequentially along the pipeline for one block, but multiple blocks (e.g., Block A and Block B) are written simultaneously in parallel.

  3. Acknowledgment (reverse order):

    • DN6 acknowledges to DN4, DN4 to DN1, and DN1 to the client.

    • Client notifies NameNode that writing succeeded; NameNode updates metadata.

HDFS Read Mechanism

Reading is simpler:

  • Client requests NameNode for the file's block locations.

  • NameNode returns the DataNode IPs for each block (e.g., Block A on DN1, DN4, DN6; Block B on DN3, DN7, DN9).

  • Client contacts the closest DataNodes and fetches all blocks simultaneously.


MapReduce

MapReduce is the programming model and processing engine for Hadoop. It processes large datasets in parallel across the cluster.

Story Analogy: Counting “Julius” in a Book

  • Traditional approach: One student counts the word across the whole book → takes 4 hours, still gives approximate answer.

  • MapReduce approach: Divide the book into four chapters. Each student counts one chapter in parallel (1 hour each). The professor then sums the results (2 minutes). Final answer: 45 occurrences.

  • Map phase: Each student (mapper) processes a part of the book and outputs (word, count) for that chapter: e.g., (Julius, 12), (Julius, 14), (Julius, 8), (Julius, 11).

  • Reduce phase: The professor (reducer) aggregates all intermediate counts: 12+14+8+11 = 45.

MapReduce Concepts

  • Map task: Reads a chunk of data (input split) and produces key-value pairs as intermediate output.

  • Reduce task: Takes the intermediate key-value pairs from all mappers, groups by key, and aggregates values to produce the final output.

  • The Reduce phase starts only after the Map phase completes because it needs the mapper outputs.

Word Count Example

Input paragraph:

Deer Beer River
Car Car River
Deer Car Beer

Steps:

  1. Input splits: Divide into three splits (one per line).

  2. Map: Each mapper tokenizes its line and outputs (word, 1) for each token.

    • Split1: (Deer,1) (Beer,1) (River,1)

    • Split2: (Car,1) (Car,1) (River,1)

    • Split3: (Deer,1) (Car,1) (Beer,1)

  3. Shuffling and sorting: All identical keys are grouped together and sent to the same reducer.

    • Beer: [1,1] → (Beer,[1,1])

    • Car: [1,1,1] → (Car,[1,1,1])

    • Deer: [1,1] → (Deer,[1,1])

    • River: [1,1] → (River,[1,1])

  4. Reduce: Sum all values for each key.

    • Beer: 1+1 = 2

    • Car: 1+1+1 = 3

    • Deer: 2

    • River: 2

  5. Final output: (Beer,2) (Car,3) (Deer,2) (River,2)

MapReduce Program Structure (Java)

A MapReduce program has three parts:

  1. Mapper class: Extends Mapper class.

    • Input: key (byte offset of line), value (line of text).

    • Output: key (word), value (1).

    • map() method: tokenizes the line and writes (word, 1) using context.write().

  2. Reducer class: Extends Reducer class.

    • Input: key (word), values (Iterable of IntWritable counts).

    • Output: key (word), value (sum of counts).

    • reduce() method: iterates through values, sums them, and writes (word, sum).

  3. Driver class: Contains main() and configures the job:

    • Sets job name, mapper and reducer classes, output key/value types.

    • Specifies input and output paths.

    • Sets input/output format classes (e.g., TextInputFormat, TextOutputFormat).

Example driver code snippet (conceptual):

Configuration conf = new Configuration();
Job job = Job.getInstance(conf, "word count");
job.setJarByClass(WordCount.class);
job.setMapperClass(Map.class);
job.setReducerClass(Reduce.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);

MapReduce Job Workflow (Behind the Scenes)

  • Map tasks write output to a circular memory buffer (default 100 MB).

  • When buffer reaches 80% threshold, a background thread spills the data to disk, partitioning it by reducer and sorting by key.

  • Multiple spill files are merged into a single sorted output file per mapper.

  • Configuration mapreduce.task.io.sort.mb controls buffer size; mapreduce.task.io.sort.factor controls maximum number of streams to merge (default 10).

  • Reducers fetch these partitions from all mappers (shuffle), merge and sort them, then apply the reduce function.


YARN (Yet Another Resource Negotiator)

YARN is the resource management layer of Hadoop (MapReduce v2). It separates resource management from job scheduling/monitoring.

YARN Components

  • ResourceManager (Master): Receives processing requests (e.g., MapReduce jobs), allocates resources, and monitors job progress.

  • NodeManager (Slave): Runs on every DataNode. Manages application containers and monitors resource usage in that node.

  • AppMaster: A per-application daemon (one per job). Negotiates resources with ResourceManager, launches containers, and tracks job execution.

  • Container: A logical bundle of CPU and RAM where the actual processing (map/reduce tasks) executes.

YARN Job Workflow

  1. Client submits a MapReduce job to the ResourceManager.

  2. ResourceManager assigns an Application ID to the client.

  3. ResourceManager contacts a NodeManager to start a container for the AppMaster.

  4. AppMaster negotiates containers (resources) from ResourceManager for map and reduce tasks.

  5. AppMaster launches containers (YARN child processes) on DataNodes to execute tasks.

  6. AppMaster monitors progress and reports to ResourceManager.

  7. After completion, AppMaster terminates.

YARN Architecture Diagram (Conceptual)

  • ResourceManager (master) ↔ NodeManager (slave) on each DataNode.

  • NodeManager hosts AppMaster and containers.

  • AppMaster is launched per job and communicates with ResourceManager for resource allocation.

Combined Hadoop Architecture (HDFS + YARN)

  • Two master nodes: NameNode (HDFS) and ResourceManager (YARN).

  • Two slave daemons per worker machine: DataNode (storage) and NodeManager (processing).

  • Secondary NameNode for checkpointing.


Hadoop Cluster Modes

  1. Standalone/Local mode: All daemons run in a single JVM on one machine. No distributed filesystem. Used for testing.

  2. Pseudo-distributed mode: All Hadoop daemons (NameNode, DataNode, ResourceManager, NodeManager) run on a single machine but with logical separation. Suitable for learning.

  3. Multi-node cluster mode: Multiple machines with separate master and slave nodes. This is the production mode — only this mode provides true distributed storage and parallel processing with fault tolerance.

For production, always use multi-node cluster mode to gain the full benefits of Hadoop (scalability, fault tolerance, parallel processing).


Hadoop Ecosystem

The Hadoop ecosystem is a collection of tools for big data analytics. Not all tools need to be used together; choose based on requirements.

Data Ingestion

  • Flume: Ingests unstructured/semi-structured data (e.g., social media streams) into HDFS.

  • Sqoop: Ingests structured data (e.g., relational databases, Excel files) into HDFS.

Storage

  • HDFS: Distributed file system for storing big data.

Resource Management

  • YARN: Resource negotiation and job scheduling.

Analytics & Processing

  • Hive: Developed by Facebook. Uses HiveQL, a SQL-like language for data analysis. Translates queries into MapReduce jobs.

  • Pig: Uses Pig Latin, a high-level scripting language. One line of Pig can replace ~20 lines of MapReduce code. The Pig compiler converts Pig Latin into MapReduce jobs automatically.

  • Spark: For near real-time processing and machine learning (includes MLlib).

  • Mahout: Machine learning library for scalable algorithms.

Management & Coordination

  • Zookeeper: Coordination service for distributed applications.

  • Ambari: Tool for provisioning, managing, and monitoring Hadoop clusters.

  • Oozie: Workflow scheduler for managing Hadoop jobs (scalable, reliable, extensible).

Real-time & Streaming

  • Storm: Real-time computation engine for processing unbounded data streams.

  • Kafka: Handles real-time data feeds (publish-subscribe messaging).

Search & Indexing

  • Solr / Lucene: Search and indexing tools.

Use Case Example: Analyzing Olympic Data with Pig

Goal: Use Pig to analyze an Olympic dataset (CSV with fields: athlete, age, country, year, closing date, sport, gold, silver, bronze, total medals).

Three analyses:

  1. Top 10 countries with highest total medals.

  2. Top 10 countries with highest gold medals.

  3. Countries with most medals in swimming.

Pig commands (conceptual flow):

Step 1: Load data

olympic = LOAD 'olympics_data.csv' USING PigStorage('\t') AS (athlete:chararray, age:int, country:chararray, year:int, closing:chararray, sport:chararray, gold:int, silver:int, bronze:int, total:int);

Step 2: Select needed fields (country, total medals)

country_totals = FOREACH olympic GENERATE country, total;

Step 3: Group by country and count total medals per country

grouped = GROUP country_totals BY country;
result = FOREACH grouped GENERATE group AS country, COUNT(country_totals) AS total_medals;

Step 4: Sort descending and take top 10

sorted = ORDER result BY total_medals DESC;
top10 = LIMIT sorted 10;

Step 5: Store result

STORE top10 INTO 'output/use_case1';

For gold medals, replace total with gold (index 6). For swimming, filter by sport == 'Swimming' then group by country and count.

Pig’s power: Commands are implicitly converted to MapReduce jobs. A few lines of Pig replace hundreds of lines of Java MapReduce code.


Key Takeaways

  • Big data is characterized by the 5Vs: Volume, Variety, Velocity, Value, Veracity.

  • Hadoop solves big data storage (HDFS) and processing (MapReduce) via distributed, parallel, fault-tolerant architecture.

  • HDFS stores files as blocks (default 128 MB), replicated three times across DataNodes for fault tolerance.

  • NameNode manages metadata; Secondary NameNode performs checkpointing; DataNodes store actual data.

  • MapReduce splits jobs into map tasks (parallel processing of data parts) and reduce tasks (aggregate results).

  • YARN manages cluster resources; ResourceManager (master) and NodeManager (slave) handle job scheduling and execution.

  • Hadoop ecosystem includes many tools (Pig, Hive, Spark, Flume, Sqoop, etc.) for different analytics needs.

  • Pig enables analysts to write concise scripts that compile into MapReduce jobs, making Hadoop accessible without deep Java knowledge.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent