Memory Atlas Β· Data processing

Hadoop

Build a durable mental model of how Spark plans, moves, and optimizes distributed workβ€”then retrieve it under interview pressure.

Chapters
07
Advanced
02
Mode
Recall

Read for structure. Pause at each memory map and answer before revealing the detail.

Foundation

Hadoop Overview and Interview Plan

#

60-second map

Answer First: Hadoop combines HDFS for distributed storage, YARN for resource management, and processing/query engines such as MapReduce, Tez, Spark, and Hive around a shared data platform.

Memory Map: ingest -> HDFS -> YARN -> compute -> Hive/HBase -> secure -> operate -> migrate.

Use the seven modules on this page as one recall atlas. Start with the direct answer, draw the data or control path, name the production trap, and close with the evidence you would inspect.

Version and benchmark guardrails

  • Defaults in this atlas are interview baselines, not universal production values. Confirm them in the deployed distribution's generated configuration; the upstream reference used here is Apache Hadoop 3.4.3.
  • HDFS HA and Federation are independent Hadoop 2-era capabilities. Current HA can run two or more NameNodes; QJM uses a majority of JournalNodes and fencing to prevent split brain.
  • HDFS erasure coding is a directory policy for suitable warm/cold data, not a cluster-wide replacement for replication. RS-6-3-1024k is the upstream system-default EC policy, but new files remain replicated unless an EC policy is set on an ancestor directory.
  • Performance multipliers in the legacy notes are illustrative anecdotes. Treat every β€œfaster” claim as workload-dependent and validate it with representative data, plans, counters, and end-to-end benchmarks.
  • Apache Sqoop was retired to the Apache Attic in 2021. Its commands remain here for legacy-cluster interviews and migrations, not as a recommendation for a new ingestion platform.

Canonical source guide

Merged from HD_00_INTERVIEW_PLAN.md; the legacy source remains unchanged.

Legacy access metadata: free: true.

3-Day Hadoop Interview Prep

πŸ—ΊοΈ Memory Map
Focus: Complete Hadoop ecosystem β€” HDFS, YARN, MapReduce, Hive, HBase, and migration Created: 2026-03-25 Approach: Same as Databricks + Snowflake prep β€” basics inside questions, memory maps, all 3 levels

WHY HADOOP MATTERS FOR YOUR INTERVIEW

  • Many enterprise JDs explicitly mention: Hadoop/Hive as required technology
  • With 10 years experience: interviewers expect deep internals (NameNode HA, YARN schedulers, Hive optimization)
  • Companies still run massive Hadoop clusters β€” knowing it + knowing how to MIGRATE to Spark/cloud is gold
  • Critical bridge question: "How would you migrate this Hadoop pipeline to Databricks/Spark?" β€” shows you know BOTH

3-DAY SCHEDULE

πŸ—ΊοΈMemory Map
DAY 15-6 hoursHDFS + YARN + MAPREDUCE INTERNALS
HDFS Architecture (NameNode, DataNode, blocks, replication)
HDFS NameNode High Availability (Active/Standby, JournalNodes)
HDFS Federation (multiple NameNodes for horizontal scaling)
HDFS Read & Write paths (step-by-step internals)
YARN Architecture (ResourceManager, NodeManager, ApplicationMaster)
YARN Schedulers (FIFO, Capacity, Fair β€” when to use which)
MapReduce Internals (Map β†’ Shuffle β†’ Sort β†’ Reduce)
MapReduce Optimization (combiner, partitioner, compression)
Small Files Problem & Solutions
Hadoop 1 vs Hadoop 2 vs Hadoop 3
DAY 25-6 hoursHIVE + ECOSYSTEM TOOLS
Hive Architecture (Metastore, Driver, Compiler, Execution Engine)
Hive Internal vs External Tables
Hive Partitioning (static, dynamic) β€” design decisions
Hive Bucketing β€” vs partitioning, when to use
Hive File Formats (ORC, Parquet, Avro, Text β€” when to use which)
Hive Query Optimization (vectorization, Tez, LLAP, joins)
HBase Architecture (row key design, regions, compactions)
Sqoop (import/export, incremental loads, split-by)
Flume (sources, channels, sinks β€” for log ingestion)
Oozie (workflow vs coordinator jobs)
ZooKeeper (leader election, distributed coordination)
Scenario: Design a complete Hadoop pipeline for a travel platform
DAY 35-6 hoursPERFORMANCE, SECURITY + CLOUD MIGRATION
Hadoop Security (Kerberos, Apache Ranger, Knox, TLS)
Hadoop Performance Tuning (JVM, GC, memory settings)
Data Skew handling in MapReduce and Hive
HDFS Balancer & Block Management
Hadoop Cluster Sizing & Capacity Planning
Cloudera CDP vs Hortonworks HDP vs Apache Hadoop
Hadoop to Cloud Migration Patterns
Lift-and-Shift (HDFS β†’ ADLS/S3)
Replatform (MapReduce β†’ Spark)
Refactor (Hive β†’ Delta Lake / Snowflake)
Hadoop vs Spark β€” key differences (as a 10-year engineer)
Pig Latin β€” basics + when you'd use it vs Hive vs Spark
Mock Interview β€” 10 most-likely questions for 10-year engineers

PRIORITY MATRIX

MUST KNOW (Will definitely be asked β€” 55%)

  1. HDFS architecture β€” NameNode/DataNode, blocks, replication factor
  2. NameNode HA β€” Active/Standby, JournalNodes, ZooKeeper
  3. YARN β€” ResourceManager, NodeManager, ApplicationMaster
  4. MapReduce flow β€” Map β†’ Shuffle β†’ Sort β†’ Reduce (step by step)
  5. Hive partitioning vs bucketing β€” when to use each
  6. ORC vs Parquet vs Text β€” file formats and tradeoffs
  7. Hive optimization β€” vectorization, Tez, execution engine
  8. Small files problem β€” causes and solutions

SHOULD KNOW (High probability β€” 30%)

  1. Hive internal vs external tables
  2. Sqoop incremental imports
  3. HBase row key design
  4. YARN schedulers (Capacity, Fair)
  5. MapReduce combiner and partitioner
  6. Kerberos authentication in Hadoop
  7. Apache Ranger for authorization
  8. HDFS Federation
  9. Data skew in Hive/MapReduce

NICE TO KNOW β€” Differentiators (15%)

  1. HDFS erasure coding (Hadoop 3 β€” an alternative to replication for suitable data)
  2. Hadoop 3 features (3x→EC, YARN Timeline v2, OpportunisticContainers)
  3. Cloudera CDP vs HDP
  4. Oozie coordinator jobs (time + data triggers)
  5. Flume channel types (memory vs file)
  6. LLAP (Live Long And Process) β€” Hive sub-second queries
  7. Hadoop to Databricks migration strategy (including vendor migration tooling where currently supported)
  8. Apache Pig β€” when still relevant

APPROACH (Same as Databricks + Snowflake Prep)

🧠 INTERVIEW TIP β†’ How to answer confidently with 10-year framing
WHAT IS IT?β†’Simple 2-3 line English explanation
WHY NEED IT?β†’Problem it solves (with travel example)
HOW IT WORKS?β†’Internals + diagrams + commands with comments
WHEN TO USE?β†’Decision guide
INTERVIEW TIPHow to answer confidently with 10-year framing
MEMORY MAPMnemonic to never forget
ALL 3 LEVELS:β†’Direct Q (one-liner) + Mid-level (how/why) + Scenario (design)

Key framing for 10-year experience:

Senior engineers are expected to explain WHY, not just WHAT. Don't just say "NameNode stores metadata" β€” say "Before Hadoop 2, the single NameNode was an availability risk. Hadoop 2 introduced both Active/Standby HA for availability and HDFS Federation for namespace scaling; they solve different problems."

HADOOP ECOSYSTEM OVERVIEW

πŸ“ Architecture Diagram
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                    HADOOP ECOSYSTEM                              β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚                                                                 β”‚
β”‚  INGESTION:                                                     β”‚
β”‚  Sqoop  β†’ Import from RDBMS (Oracle, MySQL) into HDFS/Hive     β”‚
β”‚  Flume  β†’ Stream logs from web servers into HDFS               β”‚
β”‚  Kafka  β†’ Real-time event streaming (feeds into HDFS/HBase)    β”‚
β”‚                                                                 β”‚
β”‚  STORAGE:                                                       β”‚
β”‚  HDFS   β†’ Distributed file system (the core storage)           β”‚
β”‚  HBase  β†’ NoSQL column store on top of HDFS (row-level access) β”‚
β”‚                                                                 β”‚
β”‚  PROCESSING:                                                    β”‚
β”‚  MapReduce β†’ Batch processing (Java, old way)                   β”‚
β”‚  Hive      β†’ SQL on HDFS (translated to MapReduce or Tez)      β”‚
β”‚  Pig       β†’ Scripting language for data flows (Pig Latin)      β”‚
β”‚  Spark     β†’ In-memory fast processing (replaces MapReduce)     β”‚
β”‚  Impala    β†’ Low-latency SQL (Cloudera, no MapReduce)           β”‚
β”‚                                                                 β”‚
β”‚  RESOURCE MANAGEMENT:                                           β”‚
β”‚  YARN      β†’ Cluster resource manager (since Hadoop 2)         β”‚
β”‚                                                                 β”‚
β”‚  COORDINATION:                                                  β”‚
β”‚  ZooKeeper β†’ Distributed coordination (NameNode HA, HBase)     β”‚
β”‚                                                                 β”‚
β”‚  WORKFLOW:                                                      β”‚
β”‚  Oozie     β†’ Job scheduler/workflow (chains MapReduce/Hive/Pig) β”‚
β”‚                                                                 β”‚
β”‚  SECURITY:                                                      β”‚
β”‚  Kerberos  β†’ Authentication (who are you?)                      β”‚
β”‚  Ranger    β†’ Authorization (what can you do?)                   β”‚
β”‚  Knox      β†’ Gateway (API proxy, SSL termination)               β”‚
β”‚                                                                 β”‚
β”‚  METADATA:                                                      β”‚
β”‚  Hive Metastore β†’ Table schema + HDFS location mapping         β”‚
β”‚  Atlas          β†’ Data lineage + governance (Cloudera/HDP)      β”‚
β”‚                                                                 β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

HADOOP vs SPARK vs CLOUD β€” The Big Picture

HADOOP (2006-2018): The original big data platform
βœ“ Batch processing at scale (terabytes to petabytes)
βœ“ Fault-tolerant distributed storage (HDFS)
βœ— Slow (disk-based MapReduce)
βœ— Complex (Java MapReduce code)
βœ— No real-time processing
SPARK (2014-present): The upgrade
βœ“ Can avoid repeated materialization and accelerate iterative workloads; benchmark against MapReduce
βœ“ Python/SQL API (much simpler)
βœ“ Streaming + batch in one framework
βœ“ Still uses HDFS for storage (or cloud storage)
βœ— Still requires cluster management
CLOUD LAKEHOUSE (2020-present): The future
βœ“ No cluster management (fully managed)
βœ“ Infinite scale (pay per use)
βœ“ Delta Lake / Iceberg (ACID on data lake)
βœ“ Unified batch + streaming + ML
Most companies: Hadoop→Spark → Cloud Lakehouse
YOUR POSITION AS 10-YEAR ENGINEER:
"I've worked with Hadoop for years β€” I understand why it was groundbreaking.
I also understand its limitations and have modernized pipelines from
Hive/MapReduce to Spark and now to Databricks/cloud lakehouses."
Intermediate

HDFS, YARN, and MapReduce

#

Answer-first recall layer

Recall: HDFS architecture

Answer First: HDFS separates metadata from block storage: the active NameNode owns the namespace and block map, while DataNodes store and report block replicas; the client carries data directly to or from DataNodes.

Memory Map: client -> NameNode metadata -> DataNode blocks -> heartbeats and block reports.

Recall: HDFS write path

Answer First: The client asks the NameNode for a target pipeline, streams checksummed packets through the DataNodes, and treats the write as durable only after acknowledgements return through the replica pipeline.

Memory Map: create -> choose replicas by rack -> packet pipeline -> reverse acknowledgements -> close.

Recall: HDFS read path and locality

Answer First: The NameNode returns block locations, then the client reads and checksum-verifies the nearest healthy replica directly; failed replicas are skipped and reported.

Memory Map: open -> block locations -> nearest replica -> checksum -> next block.

Recall: NameNode HA and federation

Answer First: HA removes the active NameNode as a service-availability single point through shared edits and failover; federation scales the namespace by running independent nameservices with separate block pools.

Memory Map: HA = one namespace, active/standby; federation = many namespaces, many block pools.

Recall: small files

Answer First: Small files exhaust NameNode heap and create scheduling overhead because each file and block consumes metadata even when it contains little data; compact upstream and use splittable, columnar formats.

Memory Map: file count -> NameNode metadata -> task count -> compaction/container format.

Recall: YARN

Answer First: The ResourceManager arbitrates cluster resources, a per-application ApplicationMaster negotiates containers, and NodeManagers launch and monitor those containers on workers.

Memory Map: client -> ResourceManager -> ApplicationMaster -> NodeManager -> container.

Recall: MapReduce shuffle

Answer First: Mappers emit partitioned, sorted intermediate records; reducers fetch those partitions, merge and group keys, then write final output. The shuffle is the network-and-disk boundary to optimize first.

Memory Map: input split -> map -> partition/sort/spill -> shuffle/merge -> reduce -> HDFS.

Recall: MapReduce tuning

Answer First: Tune from evidence: validate input layout and skew, right-size containers and sort buffers, compress map output, choose reducer parallelism, and verify spill, shuffle, GC, and straggler counters.

Memory Map: layout -> skew -> containers -> spills -> shuffle -> reducers -> counters.

Canonical source guide

Merged from HD_01_HDFS_YARN_MapReduce.md; the legacy source remains unchanged.

Day 1: HDFS + YARN + MapReduce β€” Deep Dive

Time: 5-6 hours | Covers internals + scenario questions at all levels Philosophy: Learn the WHY, not just the WHAT. Every concept taught through the problem it solves. Levels: ⬜ Direct (what/define) | 🟨 Mid-level (how/why) | πŸŸ₯ Scenario (design/debug/fix)

SECTION 1: HDFS β€” HOW HADOOP STORES DATA

🧠 The Core Problem HDFS Solves

Before HDFS: You have 100 TB of booking logs. One server has 4 TB disk. You need 25 servers. But:

  • If one server crashes β†’ that portion of data is LOST
  • To process data β†’ move it all to one machine β†’ network bottleneck
  • No way to scale beyond one machine's processing power

HDFS solution: Split files into blocks, store each block on multiple servers (replication), and run computation where the data lives when scheduling permits. Data locality minimizes network movement; replication, remote reads, and shuffle still use the network. Replicas provide fault tolerance.

Q1: What is HDFS Architecture? Explain every component.

Simple Explanation: HDFS (Hadoop Distributed File System) is a distributed file system that splits large files into fixed-size blocks and stores them across many commodity servers. It has two types of nodes: one master (NameNode) that tracks WHERE everything is, and many workers (DataNodes) that actually store the data blocks.

The NameNode keeps the active namespace and file-to-block map in memory. FsImage and EditLog are persisted on local storage: namespace changes append to EditLog, and checkpoints periodically merge that journal with FsImage.

πŸ“ Architecture Diagram
HDFS CLUSTER ARCHITECTURE:
═══════════════════════════════════════════════════════════════════

Client (your application)
    β”‚
    β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  NAMENODE (Master β€” 1 per cluster, critical!)               β”‚
β”‚                                                             β”‚
β”‚  What it stores IN MEMORY for live namespace operations:     β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”‚
β”‚  β”‚ Namespace = directories, files, permissions, quotas    β”‚  β”‚
β”‚  β”‚ Block Map = file β†’ list of block IDs                  β”‚  β”‚
β”‚  β”‚ Location Map = block ID β†’ DataNode IPs (NOT on disk!) β”‚  β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β”‚
β”‚                                                             β”‚
β”‚  What it PERSISTS on local storage:                         β”‚
β”‚  FsImage = checkpoint of the filesystem namespace           β”‚
β”‚  EditLog = appended namespace changes since the checkpoint  β”‚
β”‚                                                             β”‚
β”‚  What it NEVER stores: actual data bytes                    β”‚
β”‚  The namespace and file-to-block map in memory are rebuilt  β”‚
β”‚  from FsImage + EditLog; block locations come from reports. β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                         β”‚ heartbeat every 3 seconds
                         β”‚ block report every 6 hours
         β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
         β–Ό               β–Ό               β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  DATANODE 1  β”‚  β”‚  DATANODE 2  β”‚  β”‚  DATANODE 3  β”‚
β”‚  (Worker)    β”‚  β”‚  (Worker)    β”‚  β”‚  (Worker)    β”‚
β”‚              β”‚  β”‚              β”‚  β”‚              β”‚
β”‚  Block A     β”‚  β”‚  Block A     β”‚  β”‚  Block B     β”‚
β”‚  Block B     β”‚  β”‚  Block C     β”‚  β”‚  Block C     β”‚
β”‚  ...         β”‚  β”‚  ...         β”‚  β”‚  ...         β”‚
β”‚              β”‚  β”‚              β”‚  β”‚              β”‚
β”‚  Stores:     β”‚  β”‚  Stores:     β”‚  β”‚  Stores:     β”‚
β”‚  actual data β”‚  β”‚  actual data β”‚  β”‚  actual data β”‚
β”‚  block files β”‚  β”‚  block files β”‚  β”‚  block files β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Key: Block A is on DN1 AND DN2 β†’ that's REPLICATION (default 3x)
     If DN1 crashes β†’ data is still safe on DN2 and others

Key numbers to memorize:

Default block size: 128 MB (Hadoop 2+), was 64 MB in Hadoop 1
Default replication: 3 copies per block
Heartbeat interval: 3 seconds (DataNode β†’ NameNode)
Block report interval: 6 hours (full block list from DataNode)
Missing block threshold: 10 minutes without heartbeat→node marked dead
Replication target: Rack-aware (1 copy local rack, 2 copies other rack)

Q2: How does HDFS WRITE work? Step-by-step.

Why this matters: This is the most asked HDFS internals question. If you understand the write path, you understand replication, pipeline writes, fault tolerance, and checksum verification β€” all in one answer.

πŸ“ Architecture Diagram
HDFS WRITE PATH β€” Step by Step:
════════════════════════════════

CLIENT wants to write: booking_logs.csv (400 MB)

STEP 1: Client contacts NameNode
    Client β†’ NameNode: "I want to write booking_logs.csv, 400 MB"
    NameNode checks:
      - Does this file already exist? (no β†’ proceed)
      - Is there enough space across DataNodes?
    NameNode β†’ Client: "Split into 4 blocks of 128 MB. Here are the DataNodes:"
      - Block 1 β†’ store on DN1, DN2, DN3 (replication pipeline)
      - Block 2 β†’ store on DN1, DN4, DN2
      - Block 3 β†’ store on DN2, DN3, DN5
      - Block 4 β†’ store on DN3, DN4, DN1

STEP 2: Client writes Block 1 using PIPELINE
    Client writes to DN1 β†’ DN1 streams to DN2 β†’ DN2 streams to DN3
    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”   128 MB    β”Œβ”€β”€β”€β”€β”€β”€β”   128 MB   β”Œβ”€β”€β”€β”€β”€β”€β”   128 MB   β”Œβ”€β”€β”€β”€β”€β”€β”
    β”‚ Client │──────────► β”‚ DN1  │──────────►│ DN2  │──────────►│ DN3  β”‚
    β””β”€β”€β”€β”€β”€β”€β”€β”€β”˜            β””β”€β”€β”€β”€β”€β”€β”˜           β””β”€β”€β”€β”€β”€β”€β”˜           β””β”€β”€β”€β”€β”€β”€β”˜
                                      β–² pipeline β€” not 3 separate uploads!
                          Each packet ~64 KB, acknowledged back

STEP 3: Acknowledgement chain
    DN3 sends ACK β†’ DN2 β†’ DN1 β†’ Client (block written successfully!)
    If DN2 fails mid-write:
      - Client is notified
      - Block is recovered from DN1 (partial write discarded on DN3)
      - NameNode assigns a new DataNode to complete replication

STEP 4: NameNode updates metadata
    The NameNode updates the namespace and file-to-block map in memory as
    create, block-allocation, and close operations occur.
    For durability, it appends the namespace mutation to the EditLog.
    It does NOT rewrite FsImage for every write; checkpoints periodically merge FsImage and EditLog.
    File is now visible in HDFS namespace

STEP 5: Checksum verification
    Every 512 bytes, HDFS writes a checksum (CRC32)
    On every READ, checksum is verified β†’ detects bit-rot automatically!
    ⚠️ If checksum fails β†’ HDFS uses another replica and flags the bad block

What-if scenarios:

🧠 Memory Map
WHAT IF the writing client crashes or stops renewing its lease?
β†’ The path has already been created and remains listed in the namespace as an under-construction inode
β†’ The NameNode tracks the writer's lease; after lease expiry, or when another client requests it, HDFS starts lease recovery
β†’ Recovery coordinates DataNodes and reconciles the last block to a consistent generation stamp and length
β†’ HDFS then finalizes the inode; complete blocks can remain, while an inconsistent tail may be truncated
β†’ This is not an invisible, all-or-nothing file transaction, and lease recovery does not require a NameNode restart
WHAT IF a DataNode in the pipeline fails?
β†’ Client notified via ACK failure
β†’ Pipeline reformed with remaining DataNodes
β†’ NameNode schedules re-replication to hit the replication factor again
β†’ Write continues (no data loss, just slight delay)
WHAT IF disk is full on a DataNode?
β†’ DataNode reports low disk space in heartbeat
β†’ NameNode stops assigning new blocks to that DataNode
β†’ DataNode continues serving reads for existing blocks

Q3: How does HDFS READ work? (Data Locality)

πŸ“ Architecture Diagram
HDFS READ PATH:
═══════════════

STEP 1: Client asks NameNode for block locations
    Client β†’ NameNode: "Give me locations for all blocks of booking_logs.csv"
    NameNode β†’ Client: block list with DataNode locations (sorted by proximity)
    NameNode does NOT participate in actual data transfer after this!

STEP 2: Client reads blocks directly from DataNodes
    Client reads Block 1 from DN1 (closest/fastest)
    Client reads Block 2 from DN3 (if DN3 is on same rack)
    Client reads Block 3 from DN2

    DATA LOCALITY MAGIC:
    If your MapReduce job runs ON DN1 β†’ reads Block 1 from LOCAL disk
    β†’ No network transfer! This is "data locality" β€” the big Hadoop performance win

STEP 3: If a DataNode fails during read
    Client switches to another replica automatically
    NameNode is notified of the bad DataNode

DATA LOCALITY PRIORITY (YARN allocates tasks in this order):
    1. LOCAL node (same machine as data)     β†’ fastest (local disk)
    2. LOCAL rack (same rack, different node) β†’ fast (intra-rack network)
    3. REMOTE rack (different rack)           β†’ slowest (inter-rack network)

Q4: What is NameNode High Availability (HA)? β€” CRITICAL QUESTION

The Problem with Single NameNode (Hadoop 1.x):

Hadoop 1.x had ONE NameNode. It was the SPOF (Single Point of Failure).
If NameNode server crashes→ENTIRE CLUSTER IS DOWN.
No one can read or write ANY file.
For a 10PB production cluster β€” this is catastrophic.
Also: NameNode maintenance (upgrades, patches) = cluster downtime.

The Solution β€” NameNode HA (Hadoop 2.x):

πŸ“ Architecture Diagram
NAMENODE HIGH AVAILABILITY ARCHITECTURE:
═════════════════════════════════════════

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”              β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  ACTIVE          β”‚              β”‚  STANDBY         β”‚
β”‚  NAMENODE        │◄────────────►│  NAMENODE        β”‚
β”‚                  β”‚   Shared     β”‚                  β”‚
β”‚  Serves clients  β”‚   EditLog    β”‚  In warm standby β”‚
β”‚  Handles all     β”‚              β”‚  Applies edits   β”‚
β”‚  metadata ops    β”‚              β”‚  from JournalNodesβ”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜              β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
         β”‚                                  β”‚
         β”‚ both write/read                  β”‚ reads same
         β–Ό                                  β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚          JOURNAL NODES (3 or 5 β€” odd number!)         β”‚
β”‚                                                      β”‚
β”‚  Journal Node 1   Journal Node 2   Journal Node 3    β”‚
β”‚  [EditLog copy]   [EditLog copy]   [EditLog copy]    β”‚
β”‚                                                      β”‚
β”‚  Active NN writes edits β†’ majority must confirm      β”‚
β”‚  Standby NN reads edits β†’ stays in sync              β”‚
β”‚  Quorum write: 2 of 3 must succeed (majority)        β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
         β”‚                     β”‚
         β–Ό                     β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                    ZOOKEEPER                          β”‚
β”‚          (decides who is ACTIVE NameNode)             β”‚
β”‚                                                      β”‚
β”‚  ZooKeeper watches both NameNodes                    β”‚
β”‚  If Active NN misses heartbeat β†’ ZK starts FAILOVER  β”‚
β”‚  ZKFC (ZooKeeper Failover Controller) on each NN     β”‚
β”‚  ZKFC monitors NN health β†’ tells ZK β†’ ZK triggers   β”‚
β”‚  failover β†’ Standby becomes Active                   β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
         β”‚
         β–Ό  sends heartbeats + block reports to BOTH NNs
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚           ALL DATANODES                               β”‚
β”‚  Report to BOTH Active and Standby NameNodes         β”‚
β”‚  So Standby always has up-to-date block locations    β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

FAILOVER PROCESS (automatic, ~30-60 seconds):
  1. Active NN misses ZooKeeper heartbeat
  2. ZKFC detects health failure
  3. ZooKeeper triggers failover
  4. Standby NN takes ACTIVE lock in ZooKeeper
  5. Standby NN reads remaining edits from JournalNodes
  6. Standby NN is now Active β†’ resumes serving clients
  7. Old Active NN is FENCED (SSH kill, IPMI power off) to prevent split-brain

⚠️ SPLIT-BRAIN PROBLEM β€” critical to mention:

🧠 Memory Map
SPLIT-BRAIN: Both NameNodes think they are Active.
Both accept writes→metadata diverges → DATA CORRUPTION!
SOLUTION: FENCING
Before Standby becomes Active, it MUST kill the old Active.
Methods:
1. SSH fencing: SSH into old Active→kill -9 the NameNode process
2. IPMI/DRAC: Power off the old Active server at hardware level
3. Shared storage fencing: revoke old Active's access to shared disk
⚠️If fencing FAILS β†’ failover is ABORTED (better to be down than corrupted!)

Interview tip (10-year framing):

"In Hadoop 1, I've personally dealt with NameNode failures taking down entire clusters. We implemented NameNode HA in Hadoop 2 with 3 JournalNodes and ZooKeeper for automatic failover. The key lesson: always configure FENCING β€” without it, split-brain can corrupt the entire namespace, which is worse than downtime."

Q5: What is HDFS Federation? When do you need it?

Problem that Federation solves:

πŸ“ Architecture Diagram
Single NameNode (even HA) has limits:
  - The live namespace and block map are in ONE NameNode's RAM
  - NameNode RAM = limiting factor for cluster size
  - 1 billion files Γ— ~150 bytes metadata = ~150 GB RAM just for metadata!
  - Active NameNode serves ALL clients β†’ becomes bottleneck

FEDERATION SOLUTION: Multiple NameNodes, each owning a namespace volume

HDFS FEDERATION ARCHITECTURE:
═══════════════════════════════

  NameNode 1                NameNode 2                NameNode 3
  (namespace: /user)        (namespace: /data)        (namespace: /tmp)
  [metadata for /user]      [metadata for /data]      [metadata for /tmp]
        β”‚                         β”‚                         β”‚
        β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                  β”‚ all NameNodes share the same DataNodes
                      β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                      β–Ό           β–Ό           β–Ό
                    DN 1        DN 2        DN 3
                 (all blocks  (all blocks  (all blocks
                  for all      for all      for all
                  namespaces)  namespaces)  namespaces)

Block Pools: Each NameNode has its own "block pool" on DataNodes
             Block pool = separate namespace on same disk
             DN stores blocks for ALL NameNodes (separated by pool ID)

When to use:

USE FEDERATION when:
βœ“ Cluster > 300 million files (RAM becoming the limit)
βœ“ Multiple teams with different SLAs (isolate namespaces)
βœ“ Want to scale metadata independently
βœ“ Cluster > 10,000 nodes
DO NOT use when:
βœ— Small cluster (< 100M files) β€” complexity not worth it
βœ— Single team/use case β€” HA alone is sufficient

Q6: The Small Files Problem β€” THE most common production issue

What is the small files problem?

🧠 Memory Map
HDFS is designed for LARGE files (GBs, TBs).
Problem: When you have MILLIONS of tiny files (KBs):
Example: 10 million log files, each 1 KB:
Total data: 10 million Γ— 1 KB = ~10 GB (not that much data!)
But: each file = at least 1 metadata entry in NameNode RAM
10 million files Γ— 150 bytes metadata = 1.5 GB RAM just for metadata!
Each file = at least 1 HDFS block (even if file is 1 KB, block is 128 MB)
MapReduce: creates 1 Map task per block β†’ 10 million Map tasks!
Task startup overhead Γ— 10 million = pipeline takes HOURS
THE MATH PROBLEM
1 file of 128 MB→1 block, 1 Map task, 1 metadata entry
128,000 files of 1 KB each→128,000 blocks, 128,000 Map tasks!
Same data volume, 128,000x more overhead!

Solutions β€” know ALL of these:

sql
SOLUTION 1: HAR FILES (Hadoop Archive)
─────────────────────────────────────
  Groups many small files into one HAR archive
  Single metadata entry, but files accessible individually
  hadoop archive -archiveName bookings.har -p /logs/small/ /archives/

  Pros: Reduces NameNode metadata pressure
  Cons: Read-only (can't append), slower random access
  Use when: archiving old data you rarely need to process

SOLUTION 2: SEQUENCE FILES
─────────────────────────────────────
  Binary format: key-value pairs, multiple small files merged into one
  Key = filename, Value = file content
  Used in: MapReduce as input, Kafka β†’ HDFS pipelines

  Pros: Splittable (supports parallel reads), fast
  Cons: Not human-readable, only MapReduce/Spark can read
  Use when: processing pipeline, not for human inspection

SOLUTION 3: COMBINE INPUT FORMAT (MapReduce)
─────────────────────────────────────
  CombineFileInputFormat groups multiple small files into one Map task
  Instead of 10,000 files = 10,000 map tasks:
  CombineFileInputFormat = 100 map tasks (each processes 100 files)

  In Hive: SET hive.input.format=org.apache.hadoop.hive.ql.io.CombineHiveInputFormat;

SOLUTION 4: HIVE MERGE ON INSERT (most practical)
─────────────────────────────────────
  Hive creates small files on every INSERT INTO partition
  Solution: merge small files after write

  SET hive.merge.mapfiles=true;          -- merge after map-only jobs
  SET hive.merge.mapredfiles=true;       -- merge after map-reduce jobs
  SET hive.merge.size.per.task=256000000; -- target 256 MB per merged file
  SET hive.merge.smallfiles.avgsize=16000000; -- trigger if avg < 16 MB

SOLUTION 5: SPARK COALESCE/REPARTITION (modern approach)
─────────────────────────────────────
  After processing, write fewer, larger files:
  df.coalesce(10).write.parquet("/output/bookings/")
  -- Reduces from 10,000 tiny files to 10 files of ~128 MB each

  This is the MODERN solution β€” most interviewers expect this answer!

SOLUTION 6: AVOID CREATING SMALL FILES
─────────────────────────────────────
  Root cause fix: why are small files being created?
  - Streaming writes: use batching (Kafka β†’ buffer 128 MB before writing)
  - Many small partitions: use fewer, coarser partitions
  - Dynamic partitions: too many partition values β†’ too many files
    Solution: partition by month instead of day if data is sparse

Q7: YARN Architecture β€” How Hadoop manages resources

The problem YARN solves:

Hadoop 1.x: MapReduce did BOTH resource management AND job execution.
JobTracker = resource manager + job scheduler (one server does everything)
TaskTracker = executes Map/Reduce tasks on each node
Problems:
Only MapReduce could run (no Spark, no Storm, no other frameworks)
JobTracker was SPOF and bottleneck (managed everything for ALL jobs)
No resource isolation between jobs
YARN"Yet Another Resource Negotiator"
Decouples resource management from job execution
ANY computation framework can now run: Spark, MapReduce, Flink, Tez, Storm
πŸ“ Architecture Diagram
YARN ARCHITECTURE:
══════════════════

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  RESOURCE MANAGER (one per cluster β€” HA supported)            β”‚
β”‚                                                               β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚  β”‚   SCHEDULER         β”‚  β”‚   APPLICATIONS MANAGER          β”‚ β”‚
β”‚  β”‚                     β”‚  β”‚                                 β”‚ β”‚
β”‚  β”‚  Allocates          β”‚  β”‚  Accepts job submissions        β”‚ β”‚
β”‚  β”‚  containers based   β”‚  β”‚  Starts ApplicationMaster       β”‚ β”‚
β”‚  β”‚  on policy          β”‚  β”‚  Monitors AM health             β”‚ β”‚
β”‚  β”‚  (Capacity/Fair)    β”‚  β”‚  Restarts AM on failure         β”‚ β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
              β”‚
              β”‚ manages resources on
              β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  NODE MANAGER       β”‚  β”‚  NODE MANAGER       β”‚  β”‚  NODE MANAGER       β”‚
β”‚  (one per node)     β”‚  β”‚  (one per node)     β”‚  β”‚  (one per node)     β”‚
β”‚                     β”‚  β”‚                     β”‚  β”‚                     β”‚
β”‚  Reports available  β”‚  β”‚  Manages containers β”‚  β”‚  Monitors container β”‚
β”‚  CPU/RAM/disk       β”‚  β”‚  on this node       β”‚  β”‚  health             β”‚
β”‚  to ResourceManager β”‚  β”‚                     β”‚  β”‚                     β”‚
β”‚                     β”‚  β”‚  Container = unit   β”‚  β”‚  Kills containers   β”‚
β”‚  Runs containers    β”‚  β”‚  of resource        β”‚  β”‚  when RM says so    β”‚
β”‚  (actual tasks)     β”‚  β”‚  (CPU + RAM slice)  β”‚  β”‚                     β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
         β”‚
         β–Ό runs inside containers
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  APPLICATION MASTER (one per job β€” runs IN a container!)            β”‚
β”‚                                                                     β”‚
β”‚  For each submitted job:                                            β”‚
β”‚  1. RM starts one AM for this specific job                          β”‚
β”‚  2. AM negotiates containers from RM for its tasks                  β”‚
β”‚  3. AM communicates with NMs to launch tasks in containers          β”‚
β”‚  4. AM monitors task progress, handles failures, re-submits tasks   β”‚
β”‚  5. AM reports job completion to RM, then exits                     β”‚
β”‚                                                                     β”‚
β”‚  Key insight: AM is JOB-SPECIFIC β€” Spark has SparkAM,              β”‚
β”‚  MapReduce has MRAppMaster, Flink has its own AM                    β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

WHAT-IF scenarios for YARN:

🧠 Memory Map
WHAT IF ResourceManager crashes?
β†’ RM HA: Active/Standby RM with ZooKeeper (like NameNode HA)
β†’ Running jobs continue (AM is running independently in containers)
β†’ New RM recovers job state from ZooKeeper (work preservation)
β†’ AM reconnects to new RM
WHAT IF ApplicationMaster crashes?
β†’ RM detects AM failure (missed heartbeat)
β†’ RM restarts AM (up to yarn.am.max-attempts times, default 2)
β†’ Restarted AM can recover task progress from completed tasks
β†’ ⚠️ If AM fails more than max-attemptsβ†’entire job fails
WHAT IF a NodeManager crashes?
β†’ NM stops sending heartbeats to RM
β†’ RM marks NM as dead after timeout
β†’ RM asks other NMs to run the tasks that were on dead NM
β†’ Containers on dead NM = their tasks are rescheduled

Q8: YARN Schedulers β€” Three types, know when to use each

🧠 Memory Map
THREE SCHEDULERS
1. FIFO SCHEDULER (First In, First Out)
───────────────────────────────────
How it works: Jobs run one at a time in submission order.
Job 2 waits until Job 1 is 100% complete before starting.
Queue: [Job1 (ETL, 100 GB)] [Job2 (analyst query)] [Job3 (ML)]
Job 1 uses ALL cluster resources until done.
Job 2 and 3 wait.
βœ“ Simple, maximum resource use for one job
βœ— Interactive queries starve behind long batch jobs
Use when: single-user cluster, dev/test only
NEVER use in production with multiple teams.
2. CAPACITY SCHEDULER (default in Apache Hadoop)
───────────────────────────────────
How it works: Divide cluster into QUEUES with guaranteed capacity.
Each queue gets a % of cluster resources.
Queue can borrow from others if they're idle.
Config: capacity-scheduler.xml
Example at a travel platform:
ETL queue: 40% guaranteed (overnight batch jobs)
Analytics queue: 30% guaranteed (BI queries, 9-6 PM)
ML queue: 20% guaranteed (data science)
Default queue: 10% guaranteed (everything else)
βœ“ Multiple teams share cluster fairly
βœ“ Guaranteed minimum resources per team
βœ“ Elastic: can use idle capacity from other queues
Use when: multi-tenant cluster, multiple teams with SLAs
3. FAIR SCHEDULER (default in Cloudera CDH)
───────────────────────────────────
How it works: ALL jobs get equal share of resources.
Resources rebalanced as jobs arrive/finish.
3 jobs running→each gets 33%
2 jobs done→remaining job gets 100%
New job arrives→each gets 50%
βœ“ No starvation β€” every job makes progress
βœ“ Interactive + batch mix well
βœ“ Preemption: can kill low-priority tasks to give resources to high-priority
Use when: mixed workloads (interactive + batch), fairness is priority
WHICH TO USE
Dev/test only→FIFO
Enterprise production→Capacity (guaranteed SLAs per team)
Mixed interactive+batch→Fair (Cloudera default)

Q9: MapReduce β€” How it REALLY works inside

The mental model: MapReduce is a distributed computing framework. You describe WHAT to compute (not HOW to distribute it). Hadoop handles: data distribution, parallel execution, fault tolerance, and aggregation.

πŸ“ Architecture Diagram
MAPREDUCE COMPLETE EXECUTION FLOW:
════════════════════════════════════

INPUT DATA (in HDFS):
/bookings/2026/march/*.csv (10 GB of booking files)

STEP 1: JOB SUBMISSION
  Client submits job to YARN ResourceManager
  RM starts ApplicationMaster (MRAppMaster) in a container
  AM reads input splits from HDFS (one split per HDFS block = 128 MB)
  AM requests containers from RM for Map tasks

STEP 2: INPUT SPLITS & RECORD READER
  InputFormat splits input into InputSplits (usually = 1 HDFS block each)
  RecordReader reads each split β†’ produces key-value pairs for Mapper
  Default: TextInputFormat β†’ key=line offset (Long), value=line text (Text)

  Split 1 (block 1, 128 MB) β†’ Map Task 1 on Node 1 (DATA LOCALITY!)
  Split 2 (block 2, 128 MB) β†’ Map Task 2 on Node 2
  ...
  Split 80 (block 80) β†’ Map Task 80 on Node 80

STEP 3: MAP PHASE (runs in parallel on all nodes)
  Each Mapper:
    - Reads its InputSplit line by line
    - Applies your map() function to each record
    - Outputs intermediate key-value pairs

  Example: Count bookings per airline
    map("AI,BOM,LHR,500") β†’ emit("AI", 1)
    map("LH,FRA,JFK,800") β†’ emit("LH", 1)
    map("AI,DEL,DXB,300") β†’ emit("AI", 1)

STEP 4: COMBINER (optional, runs on each node BEFORE shuffle)
  "Mini-reducer" that runs locally on each Map task output
  Reduces data volume BEFORE sending to reducers (network optimization!)

  Without combiner: send 1,000,000 ("AI", 1) pairs across network
  With combiner:    combine locally first β†’ send ("AI", 50000) per node

  ⚠️ Combiner function must be same as Reducer function (associative+commutative)
  ⚠️ Combiner is an OPTIMIZATION, not guaranteed to run (Hadoop may skip it)
  Use when: reduce function is associative (sum, count, max/min β€” YES; avg β€” NO!)

STEP 5: PARTITIONER (decides which Reducer gets which keys)
  After Map+Combine: output sorted by key within each Map task
  Partitioner determines: which Reducer handles which keys

  Default: HashPartitioner β†’ (key.hashCode() & Integer.MAX_VALUE) % numReducers
  Result: ALL records with key "AI" β†’ same Reducer (regardless of which Map produced it)

  ⚠️ BAD partitioner β†’ DATA SKEW (one reducer gets 90% of data, others idle)
  Custom partitioner: override to distribute evenly by key range or custom logic

STEP 6: SHUFFLE & SORT (the heart of MapReduce, most expensive phase)
  ────────────────────────────────────────────────────────────────────
  What happens:
  1. Map output written to LOCAL DISK (not HDFS!) in Map task's buffer
  2. Map output sorted by key in buffer (in-memory sort)
  3. When buffer is 80% full β†’ SPILL to local disk (sort + spill file)
  4. Multiple spill files β†’ MERGED and sorted (merge sort)
  5. Each Reducer FETCHES (via HTTP) its assigned partitions from ALL Mappers
     β†’ This is the NETWORK TRANSFER (the expensive part!)
  6. Reducer MERGES all fetched files β†’ one sorted input stream

  The shuffle data flow:
  Mapper 1 output β†’ Sort β†’ [Partition for R0][Partition for R1][Partition for R2]
  Mapper 2 output β†’ Sort β†’ [Partition for R0][Partition for R1][Partition for R2]
  Mapper N output β†’ Sort β†’ [Partition for R0][Partition for R1][Partition for R2]
                             β–Ό                  β–Ό                  β–Ό
                         Reducer 0          Reducer 1          Reducer 2
                         fetches all        fetches all        fetches all
                         R0 partitions      R1 partitions      R2 partitions

STEP 7: REDUCE PHASE
  Each Reducer:
    - Receives sorted input: all ("AI", 1), all ("LH", 1), etc.
    - Calls reduce() once per unique key with all values
    - Outputs final key-value results

  reduce("AI", [1,1,1,...,1]) β†’ emit("AI", 150000) [total AI bookings]
  reduce("LH", [1,1,1,...,1]) β†’ emit("LH", 89000)

STEP 8: OUTPUT
  Reducer output written to HDFS (final output directory)
  Output: _SUCCESS file (job succeeded) + part-r-00000, part-r-00001 (output files)
  Number of output files = number of Reducers

What-if scenarios:

🧠 Memory Map
WHAT IF a Map task fails?
β†’ AM detects failure (task tracker error or timeout)
β†’ AM reschedules the same Map task on a different node
β†’ Default retries: 4 times
→ If all 4 fail→job fails
WHAT IF a Reduce task fails?
β†’ Same: AM reschedules
β†’ But Reduce must re-fetch all shuffle data again (expensive!)
WHAT IF one Reducer is much slower than others (SPECULATIVE EXECUTION)?
β†’ Hadoop launches a DUPLICATE task on another node for slow tasks
→ Whichever finishes first→wins, other is killed
β†’ Controlled by: mapreduce.map.speculative=true (default)
β†’ Helps when: node is degraded (bad disk, CPU issue) but not failed
WHAT IF output directory already exists?
β†’ Job FAILS immediately with FileAlreadyExistsException
β†’ HDFS does NOT overwrite directories (prevents accidental data loss)
β†’ Fix: delete output directory before job: hdfs dfs -rm -r /output/

Q10: HDFS Important Commands β€” Know these cold

bash
# ═══════════════════════════════════
# FILE SYSTEM OPERATIONS
# ═══════════════════════════════════
hdfs dfs -ls /user/data/bookings/          # List directory contents
hdfs dfs -ls -R /user/data/                # List RECURSIVELY (all subdirs)
hdfs dfs -du -s -h /user/data/bookings/   # Disk usage (-h=human readable, -s=summary)
hdfs dfs -mkdir -p /user/data/2026/march/ # Create directory (and parents with -p)
hdfs dfs -put bookings.csv /user/data/    # Upload local file to HDFS
hdfs dfs -get /user/data/bookings.csv .   # Download from HDFS to local
hdfs dfs -cat /user/data/file.csv         # Print file contents to stdout
hdfs dfs -tail /user/data/logs.txt        # Print last 1 KB of file (like Unix tail)
hdfs dfs -cp /src/file.csv /dst/          # Copy within HDFS
hdfs dfs -mv /src/file.csv /dst/          # Move within HDFS
hdfs dfs -rm /user/data/old.csv           # Delete file (goes to Trash by default!)
hdfs dfs -rm -r /user/data/old_dir/      # Delete directory recursively
hdfs dfs -rm -skipTrash /user/data/old.csv  # Delete PERMANENTLY (bypass Trash)
hdfs dfs -expunge                          # Empty Trash (permanently delete)
hdfs dfs -setrep -R 2 /user/data/archive/ # Change replication factor to 2 (save space)
hdfs dfs -checksum /user/data/file.csv    # Get MD5/CRC checksum of file

# ═══════════════════════════════════
# ADMIN OPERATIONS
# ═══════════════════════════════════
hdfs dfsadmin -report                     # Cluster status (live nodes, capacity, used)
hdfs dfsadmin -safemode get               # Check if HDFS is in safe mode
hdfs dfsadmin -safemode leave             # Force exit safe mode (after NameNode restart)
hdfs dfsadmin -refreshNodes               # Re-read includes/excludes (add/remove DNs)
hdfs dfsadmin -setQuota 100 /user/team1/ # Set namespace quota (max 100 files)
hdfs dfsadmin -setSpaceQuota 1t /user/team1/ # Set storage quota (1 TB)

# ═══════════════════════════════════
# FSCK β€” Filesystem health check
# ═══════════════════════════════════
hdfs fsck /user/data/bookings/            # Check health of all files
hdfs fsck / -files -blocks -locations     # Show all files + block locations
hdfs fsck / -list-corruptfileblocks       # List corrupted blocks
# Output to watch for:
# "HEALTHY" = all good
# "Under-replicated blocks" = some blocks don't have 3 replicas (DataNode down?)
# "Missing blocks" = data loss! Block has 0 replicas (need to recover from backup)
# "Corrupt blocks" = checksum mismatch (need to restore from another replica)

# ═══════════════════════════════════
# BALANCER β€” Fix data skew across DataNodes
# ═══════════════════════════════════
hdfs balancer -threshold 10               # Balance cluster (max 10% imbalance)
# Run when: adding new DataNodes (they start empty, all writes go to them)
# Balancer moves blocks from full nodes to empty nodes gradually

# ═══════════════════════════════════
# SAFE MODE β€” Important to understand
# ═══════════════════════════════════
# Safe mode = NameNode startup state
# During safe mode: HDFS is READ-ONLY (no writes allowed)
# NameNode waits for DataNodes to report their blocks
# Safe mode exits when: enough blocks have minimum replication
# ⚠️ If NameNode is stuck in safe mode β†’ cluster appears DOWN
# Fix: hdfs dfsadmin -safemode leave  (only if blocks are actually replicated!)

Q11: Hadoop 1 vs Hadoop 2 vs Hadoop 3 β€” The evolution

🧠 Memory Map
HADOOP 1 (2006-2012)
βœ“ HDFS + MapReduce (one framework)
βœ— Single NameNode (SPOF)
βœ— JobTracker bottleneck (all scheduling in one daemon)
βœ— Only MapReduce (no other frameworks)
βœ— Max cluster: ~4000 nodes
HADOOP 2 (2012-2017): Major redesign
+ YARN: decoupled resource management→any framework runs
+ NameNode HA: Active/Standby + JournalNodes
+ HDFS Federation: multiple NameNodes
+ Snapshot support (create point-in-time HDFS snapshots)
+ NFS gateway (mount HDFS as NFS drive)
Max cluster: 10,000+ nodes
HADOOP 3 (2017-present): Key improvements
+ HDFS ERASURE CODING (directory-level alternative to replication for suitable data)
Old: store 128 MB block β†’ 384 MB used (3 copies)
New: store 128 MB block β†’ ~192 MB used (EC-encoded)
50% storage savings! But: higher CPU cost for reconstruction
Use for: cold/archive data (rarely read, storage matters)
Keep replication for hot data (often read, fast recovery needed)
+ YARN Timeline Server v2 (better job history + metrics)
+ Opportunistic Containers (run low-priority tasks in spare capacity)
+ Multiple Standby NameNodes (more than 1 standby for HA)
+ Minimum Java 8 (drops Java 7 support)
+ Intra-DataNode balancer (balance disks within one DataNode)

⚑ SECTION 8: OPTIMIZATIONS β€” THE MOST IMPORTANT SECTION

Senior engineers are judged on this. Knowing "what is MapReduce" is basic. Knowing "which config knob to turn and WHY" is what gets you hired at 10 years.

🧠 OPTIMIZATION MASTER MEMORY MAP

HADOOP OPTIMIZATION"MY BLOCK COMPRESS FLY"
MMemory sizing (mapper/reducer heap, YARN container sizes)
YYARN container settings (vcores, memory ratio)
BBlock size tuning (bigger blocks for large files)
LLocality maximized (rack-aware placement)
OOutput compression (reduce network + disk IO)
CCombiner (mini-reducer, cut network traffic 80%)
Kpartitioning (uniform Reduce load distribution)
CCompression codecs (Snappy=fast, GZIP=small, LZO=splittable)
OORC/Parquet for Hive (columnar pruning/compression; benchmark the workload)
MMap join (small tables broadcast, avoid shuffle)
PParallel copy during shuffle (mapreduce.reduce.shuffle.parallelcopies)
RReplication factor for cold data (drop to 2 or 1)
EErasure coding (Hadoop 3, 50% storage savings for cold data)
SSpeculative execution (re-run slow tasks automatically)
SSort buffer tuning (mapreduce.task.io.sort.mb)

Q12: MapReduce Optimization β€” All Settings Explained

πŸ’‘ Interview Tip
🎀Interviewer will ask:
: "You have a MapReduce job that runs for 6 hours. How do you optimize it?"

STEP 1: Optimize Memory (Most Common Problem)

xml
<!-- mapred-site.xml β€” MapReduce memory config -->

<!-- Container memory for Map tasks -->
<property>
  <name>mapreduce.map.memory.mb</name>
  <value>2048</value>
  <!-- Default is 1024 MB. Increase if mappers are getting killed (OOM) -->
  <!-- Rule: set to 1.5x - 2x your data per mapper -->
</property>

<!-- Container memory for Reduce tasks -->
<property>
  <name>mapreduce.reduce.memory.mb</name>
  <value>4096</value>
  <!-- Reducers need more memory than Mappers (they hold sorted data) -->
  <!-- Rule: 2x mapper memory is a safe starting point -->
</property>

<!-- JVM heap for Map tasks (must be LESS than container memory) -->
<property>
  <name>mapreduce.map.java.opts</name>
  <value>-Xmx1638m</value>
  <!-- Rule: 80% of mapreduce.map.memory.mb -->
  <!-- 2048 * 0.8 = 1638 MB β€” remaining 20% is for JVM overhead -->
</property>

<!-- JVM heap for Reduce tasks -->
<property>
  <name>mapreduce.reduce.java.opts</name>
  <value>-Xmx3276m</value>
  <!-- Rule: 80% of mapreduce.reduce.memory.mb = 4096 * 0.8 = 3276 MB -->
</property>

STEP 2: Sort Buffer (Shuffle Performance)

xml
<!-- The sort buffer is IN-MEMORY β€” bigger = fewer disk spills = FASTER shuffle -->

<property>
  <name>mapreduce.task.io.sort.mb</name>
  <value>512</value>
  <!-- Default: 100 MB β€” way too small for large jobs -->
  <!-- Increase to 512 MB or more to reduce disk spills during shuffle -->
  <!-- Must fit within map container memory (mapreduce.map.memory.mb) -->
  <!-- Tuning: If you see "Spilling to disk" logs β†’ increase this first! -->
</property>

<!-- When buffer is X% full, start spilling to disk (while still mapping) -->
<property>
  <name>mapreduce.map.sort.spill.percent</name>
  <value>0.80</value>
  <!-- Default: 0.80 (80%) β€” spill when 80% of sort buffer is used -->
  <!-- Increasing to 0.90 keeps more in memory but risks OOM -->
</property>

<!-- Number of parallel sort/merge threads for spill files -->
<property>
  <name>mapreduce.task.io.sort.factor</name>
  <value>100</value>
  <!-- Default: 10 β€” how many spill files merged at once -->
  <!-- Increase to reduce the number of merge passes β†’ fewer I/O operations -->
</property>

STEP 3: Compression (Biggest Network Win)

xml
<!-- Compress map output (the shuffle data β€” this crosses network!) -->
<property>
  <name>mapreduce.map.output.compress</name>
  <value>true</value>
  <!-- TRUE = compress data during shuffle β†’ HUGE network bandwidth savings -->
  <!-- Cost: CPU for compress/decompress (usually worth it on network-bound jobs) -->
</property>

<property>
  <name>mapreduce.map.output.compress.codec</name>
  <value>org.apache.hadoop.io.compress.SnappyCodec</value>
  <!-- Snappy: FAST compress/decompress, moderate compression ratio -->
  <!-- Best choice for intermediate shuffle data (speed matters here) -->
  <!-- Alternatives: LZ4 (even faster), Zlib (smaller but slower) -->
</property>

<!-- Compress final job output -->
<property>
  <name>mapreduce.output.fileoutputformat.compress</name>
  <value>true</value>
</property>

<property>
  <name>mapreduce.output.fileoutputformat.compress.codec</name>
  <value>org.apache.hadoop.io.compress.GzipCodec</value>
  <!-- GZIP for final output: better compression ratio (smaller files stored long-term) -->
  <!-- ⚠️ GZIP is NOT splittable! Use LZO or Snappy if next job needs to read this -->
  <!-- LZO: splittable + fast β€” best for output that will be input to another MR job -->
  <!-- Bzip2: most compressed, splittable, but VERY slow compression -->
</property>

COMPRESSION CODEC COMPARISON TABLE

CODECSpeedRatioSplittableBest For
SnappyFASTMediumNOShuffle intermediate data, hot data
LZ4FASTERMediumNOReal-time, fastest option
LZOFastMediumYES*Pipeline data (input to next job)
GZIP/ZlibMediumHighNOFinal archive output (read rarely)
Bzip2SLOWHighestYESCold archive (max compression)
ORC/ParquetN/AHighestYESHive tables (columnar, built-in compress)

* LZO needs an index file created (lzop --index) to be splittable

STEP 4: Number of Reducers

xml
<!-- Number of reduce tasks (parallel reducers) -->
<property>
  <name>mapreduce.job.reduces</name>
  <value>10</value>
  <!-- Default: 1 (terrible for large jobs!) -->
  <!-- Rule of thumb: 0.95 Γ— (nodes Γ— max_containers_per_node) -->
  <!-- Example: 10 nodes Γ— 4 containers = 40 β†’ set reducers = 38 -->
  <!-- Too many reducers: overhead of managing many tasks + small output files -->
  <!-- Too few reducers: bottleneck, data skew impact is worse -->
  <!-- 0 reducers: no shuffle phase (map-only job) β€” for filter/transform jobs! -->
</property>

STEP 5: JVM Reuse (Huge Win for Many Small Tasks)

xml
<!-- Reuse JVM containers across multiple mapper tasks -->
<property>
  <name>mapreduce.job.jvm.numtasks</name>
  <value>10</value>
  <!-- Default: 1 (new JVM per task = slow startup for each task!) -->
  <!-- Setting to 10: same JVM handles 10 tasks before restarting -->
  <!-- Setting to -1: unlimited reuse (one JVM per slot for entire job) -->
  <!-- HUGE gain when you have MANY small mapper tasks (small files problem!) -->
  <!-- ⚠️ Can cause memory leaks if tasks have bugs β†’ use with stable code only -->
</property>

STEP 6: Speculative Execution

xml
<!-- Automatically re-run slow (straggler) tasks on another node -->
<property>
  <name>mapreduce.map.speculative</name>
  <value>true</value>
  <!-- Default: true β€” Hadoop automatically detects slow mappers and duplicates them -->
</property>

<property>
  <name>mapreduce.reduce.speculative</name>
  <value>true</value>
  <!-- Default: true -->
  <!-- ⚠️ Disable if your tasks have side effects (writing to DB, calling API) -->
  <!-- Otherwise same row could be written TWICE to the external system! -->
</property>

Q12 INTERVIEW ANSWER β€” "How to optimize a 6-hour MapReduce job?"

🧠 Memory Map
"I would approach this systematically β€” 5 steps:
1. DIAGNOSE FIRST: Look at the job logs β€” is it slow in map phase or reduce phase?
Is there 'Spilling to disk' in logs? Are reducers getting skewed data?
2. MEMORY + SORT BUFFER:
Increase mapreduce.task.io.sort.mb from 100 MB β†’ 512 MB (reduce disk spills)
Set map memory to 2 GB, Java opts to 80% = 1.6 GB
Result: fewer shuffle spills β†’ faster map phase
3. COMPRESSION:
Enable mapreduce.map.output.compress with Snappy codec
This cuts shuffle network traffic by 50-70%
Result: HUGE win on network-bound jobs
4. COMBINERS:
Add a Combiner class = same logic as Reducer
Runs on mapper's local output BEFORE shuffle
Cuts data volume going over network by 60-80% for aggregation jobs
5. REDUCERS + PARTITIONING:
If job has only 1 reducer β†’ parallelism is the bottleneck
Increase mapreduce.job.reduces to nodes Γ— containers Γ— 0.95
Use custom Partitioner to ensure even data distribution
6. JVM REUSE:
If job has thousands of small tasks, set mapreduce.job.jvm.numtasks=10
Saves JVM startup overhead for every task"

Q13: HDFS Block Size Optimization

🧠 Memory Map
BLOCK SIZE TUNING
Default: 128 MB (Hadoop 2/3), was 64 MB in Hadoop 1
WHEN TO INCREASE BLOCK SIZE (256 MB, 512 MB, 1 GB)
βœ“ Very large files (terabytes of log data, genomics data)
βœ“ Sequential scan workloads (full table scans in Hive/MapReduce)
βœ“ Want fewer blocksβ†’less NameNode memory pressure
βœ“ Fewer mapper tasksβ†’less task overhead
WHEN TO KEEP SMALL BLOCK SIZE (64 MB, 128 MB)
βœ“ Lots of small-to-medium files
βœ“ Random read patterns (HBase uses 64 MB HDFS blocks!)
βœ“ When parallelism matters more than overhead
FORMULA FOR OPTIMAL BLOCK SIZE
Goal: each mapper processes 1-2 blocks in 1-2 minutes
If mappers finish in 2 seconds→blocks too small → increase
If mappers run for 30 minutes→blocks too large → decrease
PRACTICAL EXAMPLE
Daily log file: 10 GB→at 128 MB = 80 blocks = 80 mappers (good!)
Daily log file: 10 GB→at 64 MB = 160 blocks = 160 mappers (more parallelism, more overhead)
Yearly archive: 10 TB→at 128 MB = 80,000 blocks (high NameNode memory)
at 512 MB = 20,000 blocks (4x less NameNode memory!)
CHANGE BLOCK SIZE PER FILE
bash
# Set block size when writing a specific file (512 MB blocks)
hdfs dfs -D dfs.blocksize=536870912 -put large_file.dat /data/archive/

# Or set in your application
# In MapReduce job config:
job.getConfiguration().set("dfs.blocksize", "536870912");

Q14: YARN Resource Optimization

xml
<!-- yarn-site.xml β€” resource manager settings -->

<!-- Total memory available for YARN on each NodeManager -->
<property>
  <name>yarn.nodemanager.resource.memory-mb</name>
  <value>49152</value>
  <!-- On a 64 GB node: reserve 8 GB for OS + other services = 56 GB, then YARN gets 48 GB -->
  <!-- Rule: YARN memory = total RAM - OS overhead (8-16 GB) - HBase/etc memory -->
</property>

<!-- Total CPU vcores available for YARN on each NodeManager -->
<property>
  <name>yarn.nodemanager.resource.cpu-vcores</name>
  <value>16</value>
  <!-- On a 16-core node: give all 16 to YARN (OS uses very little normally) -->
</property>

<!-- Minimum container size (floor) -->
<property>
  <name>yarn.scheduler.minimum-allocation-mb</name>
  <value>512</value>
  <!-- No container gets less than 512 MB β€” prevents tiny useless containers -->
</property>

<!-- Maximum container size (ceiling) -->
<property>
  <name>yarn.scheduler.maximum-allocation-mb</name>
  <value>16384</value>
  <!-- No single container gets more than 16 GB (prevents one job hogging all RAM) -->
</property>

<!-- Minimum vcores per container -->
<property>
  <name>yarn.scheduler.minimum-allocation-vcores</name>
  <value>1</value>
</property>

<!-- Maximum vcores per container -->
<property>
  <name>yarn.scheduler.maximum-allocation-vcores</name>
  <value>4</value>
</property>

YARN Capacity Scheduler Optimization

xml
<!-- capacity-scheduler.xml -->

<!-- Define queue capacities (must add up to 100%) -->
<property>
  <name>yarn.scheduler.capacity.root.production.capacity</name>
  <value>70</value>
  <!-- Production queue gets 70% of cluster resources guaranteed -->
</property>

<property>
  <name>yarn.scheduler.capacity.root.development.capacity</name>
  <value>20</value>
</property>

<property>
  <name>yarn.scheduler.capacity.root.adhoc.capacity</name>
  <value>10</value>
</property>

<!-- Maximum capacity (can use idle resources from other queues) -->
<property>
  <name>yarn.scheduler.capacity.root.production.maximum-capacity</name>
  <value>90</value>
  <!-- Production can burst to 90% if other queues are idle -->
</property>

<!-- User limit: how much one user can use within a queue -->
<property>
  <name>yarn.scheduler.capacity.root.production.user-limit-factor</name>
  <value>2</value>
  <!-- One user can use up to 2x their fair share within the queue -->
</property>

Q15: Data Skew in MapReduce β€” Problem + Solutions

⚠️ Common Trap
THIS IS A MUST-KNOW SCENARIO QUESTION FOR 10-YEAR ENGINEERS
PROBLEM: Data Skew
Your MapReduce job has 100 reducers, 99 finish in 5 minutes
But 1 reducer takes 3 HOURS β€” the whole job waits for it!
Reason: one key has 10 million values, others have 100 values each
EXAMPLE
Booking data grouped by country_code
US: 10 million bookings→one reducer handles ALL US data
Fiji: 200 bookings
SOLUTIONS
1. SALTING (most common technique):
Add random suffix to hot key: "US_0", "US_1", "US_2" ... "US_99"
Now US data splits across 100 reducers
Downside: need a second step to re-aggregate the salted results
2. CUSTOM PARTITIONER:
Write custom Partitioner that knows "US" is hot
Sends US data to multiple reducers intentionally
More maintenance but precise control
3. SAMPLING:
Sample data first, find hot keys
Use TotalOrderPartitioner for sorted output without skew
4. COMBINERS:
Reduce data at mapper output BEFORE shuffle
Cuts how much data hot-key reducer receives from each mapper
5. FOR HIVE (Day 2 β€” but mention here):
SET hive.groupby.skewindata=true β†’ Hive automatically handles skew
Uses two-phase aggregation for skewed GROUP BY

Q16: HDFS Replication Optimization

bash
# Change replication factor for cold/archive data (save storage)
hdfs dfs -setrep -w 1 /data/archive/2020/     # Old archive β†’ 1 copy (risk: data loss!)
hdfs dfs -setrep -w 2 /data/historical/2023/  # Historical β†’ 2 copies (balanced)
hdfs dfs -setrep -w 3 /data/production/       # Hot production data β†’ 3 copies (default)

# Check current replication factor of a file
hdfs fsck /data/archive/2020/ -files | grep "replication"

# HDFS Balancer β€” rebalance blocks across DataNodes (run after adding new nodes)
hdfs balancer -threshold 10
# threshold: consider node "balanced" if within 10% of average utilization
# Run this AFTER adding new DataNodes β€” new nodes start empty, data doesn't auto-move!

# Or run balancer as background process
hdfs balancer -threshold 5 &
🧠 Memory Map
REPLICATION TUNING STRATEGY
HOT DATA (accessed daily)
β†’ replication = 3 (default, fast recovery, data locality for jobs)
WARM DATA (accessed weekly/monthly)
β†’ replication = 2 (saves 33% storage)
COLD DATA (accessed rarely, archive)
β†’ replication = 1 (saves 67% storage vs default)
β†’ OR: Hadoop 3 ERASURE CODING (saves ~50% vs default 3x replication)
β†’ EC-6-3-1024k: store 6 data blocks + 3 parity blocks
β†’ can lose any 3 of 9 blocks and still recover
β†’ storage overhead: 1.5x vs 3x replication = 50% savings
⚠️Erasure coding has higher CPU cost for recovery β€” use only for cold/archive data!

Q17: MapReduce Performance Summary β€” Interview Answer Framework

"When I get a slow MapReduce job, I follow this checklist (mnemonic: MCJ-COMP):
MMemory: increase sort buffer (task.io.sort.mb), container memory, Java heap
CCombiners: add combiner to cut shuffle data 60-80% for aggregation jobs
JJVM Reuse: set jvm.numtasks=10 for jobs with many small tasks
CCompression: enable map output compress with Snappy (cuts network 50-70%)
OOutput: compress final output with GZIP (smaller files on disk)
MMore Reducers: increase from 1 to nodes Γ— containers Γ— 0.95
PPartitioner: ensure even key distribution (custom partitioner for skewed data)
MOST COMMON FIX: 90% of slow jobs = sort buffer too small OR map output not compressed
SECOND MOST COMMON: Only 1 reducer when there should be 20+
For Hive jobs (same cluster): ORC format + vectorization + Tez engine β€” Day 2 topic."

Integrated quick recall

Merged from HD_01_Quick_Recall.md; the legacy source remains unchanged.

Day 1: HDFS + YARN + MapReduce β€” Quick Recall Guide

⚑Must rememberπŸ”‘Key concept⚠️Common trap🧠Memory MapπŸ“One-liner

🧠 MASTER MEMORY MAP β€” Day 1

🧠 HDFS KEY NUMBERS = "1-3-128-3-64"
HDFS KEY NUMBERS"1-3-128-3-64"
1 β€” NameNode (one namespace; keeps the live namespace/block map in RAM)
3 β€” Default replication factor (3 copies of every block)
128 β€” Default block size (128 MB per block)
3 β€” Heartbeat timeout before DataNode marked dead (3 seconds interval)
64 β€” Old Hadoop 1 block size (64 MB, now 128 MB)
NAMENODE HA"JZ-FENCE"
JJournalNodes (quorum log β€” both Active+Standby read edit log here)
ZZooKeeper (elects Active, runs ZKFC on each NameNode)
FENCE β€” Fencing (kill the old Active before new one takes over β€” prevents split-brain!)
MAPREDUCE PHASES"I-Map-CBS-Reduce-O" (8 steps)
IInput Splits (decide how many mappers)
Map β€” Map phase (your map() function runs)
CCombiner (optional mini-reducer, runs locally on mapper node)
BBuffer (sort buffer in RAM β€” mapreduce.task.io.sort.mb)
SShuffle + Sort (data crosses network sorted by key)
Reduce β€” Reduce phase (your reduce() function runs)
OOutput (written to HDFS)
YARN"RM-NM-AM"
RM β€” ResourceManager (cluster boss: Scheduler + ApplicationsManager)
NM β€” NodeManager (per-node worker, runs containers, monitors health)
AM β€” ApplicationMaster (per-JOB manager, negotiates resources from RM)
OPTIMIZATION CHECKLIST"MCJ-COMP"
MMemory: increase sort buffer + container memory
CCombiner: cut shuffle data by 60-80%
JJVM Reuse: reuse JVM across tasks (jvm.numtasks=10)
CCompression: Snappy for shuffle, GZIP for output
OOutput: compress final output to save disk
MMore reducers: increase from 1 to NΓ—containersΓ—0.95
PPartitioner: even distribution (custom for skewed data)

SECTION 1: HDFS β€” DIRECT QUESTIONS

⚑ MUST KNOW DIRECT QUESTIONS

Q1What is HDFS?

Hadoop Distributed File System β€” splits large files into 128 MB blocks and distributes them across DataNodes. NameNode stores metadata (which blocks are where), DataNodes store actual data.

Q2What does NameNode store?

The live namespace, file-to-block map, and reported block locations are held in RAM. FsImage and EditLog are persistent local files: mutations append to EditLog, and periodic checkpoints merge EditLog into a new FsImage.

Q3What does DataNode store?

Actual data blocks (128 MB each). It sends heartbeats every 3 seconds + block reports every 6 hours to NameNode. If no heartbeat for 10 minutes β†’ DataNode marked dead.

⚑ Q4What is replication factor?

Number of copies of each block. Default = 3. First replica on writer's node, second on a different rack, third on same rack as second (rack-aware). If a DataNode dies, NameNode triggers re-replication.

Q5What is the default HDFS block size?

128 MB (Hadoop 2+). Was 64 MB in Hadoop 1. Larger blocks = fewer blocks = less NameNode memory. Each block = one mapper input (usually).

⚠️ Q6What is the small files problem?

Millions of tiny files (1 KB, 10 KB) each create a separate block entry in NameNode. 1 million files Γ— 150 bytes = 150 MB of NameNode RAM just for metadata! NameNode runs OOM. Also: one mapper per file = overhead with no actual work.

Q7Solutions to the small files problem?
    1. HAR files (archive, read-only)
    2. 2SequenceFile (bundle many β†’ one file)
    3. 3CombineInputFormat (one mapper for many small files)
    4. 4Hive: hive.merge.smallfiles.avgsize
    5. 5Spark: coalesce() before writing
    6. 6Fix upstream pipeline to write fewer large files.

SECTION 1: HDFS

Q8Explain the HDFS Write Path step by step.
    1. Client β†’ NameNode: "I want to create /data/file.txt"
    2. 2NN checks permissions, creates metadata, returns list of 3 DataNodes
    3. 3Client opens pipeline to DN1 β†’ DN1 connects to DN2 β†’ DN2 connects to DN3
    4. 4Client sends blocks (64 KB packets) down the pipeline
    5. 5DN3 sends ACK β†’ DN2 β†’ DN1 β†’ Client (ACK chain confirms receipt)
    6. 6After all blocks written, client closes stream, notifies NameNode
    7. 7NameNode marks file as complete.
Q9Explain the HDFS Read Path.
    1. Client β†’ NameNode: "I want to read /data/file.txt"
    2. 2NN returns list of block locations (DataNodes, ordered by proximity)
    3. 3Client reads DIRECTLY from DataNodes (bypasses NameNode)
    4. 4Priority: local node > same rack > different rack (data locality!)
    5. 5If DataNode fails mid-read, client tries next DataNode for that block.
⚠️ Q10What happens when a DataNode dies?

NameNode stops receiving heartbeats. After timeout (~10 min) marks DataNode dead. Identifies all blocks that were on that node with replication < target. Queues re-replication from other nodes. HDFS automatically recovers without manual intervention.

SECTION 1: HDFS β€” SCENARIO QUESTIONS

⚑ Q11 SCENARIO: A DataNode is dead and your replication factor is 3. What happens?

NameNode detects missing heartbeat β†’ marks DataNode dead β†’ checks all blocks that were on it β†’ finds blocks now have replication factor 2 β†’ schedules re-replication from surviving DataNodes β†’ target replication (3) is restored. Process is automatic. Time depends on block size and network.

Q12 SCENARIO: Someone accidentally deleted a critical file from HDFS. How do you recover?

    1. Check HDFS Trash: hdfs dfs -ls /user//.Trash/Current/
    2. 2If in trash: hdfs dfs -mv /user/.Trash/Current/data/file.txt /data/file.txt
    3. 3If trash emptied: restore from Snapshot (if snapshots were enabled): hdfs dfs -cp /data/.snapshot/s1/file.txt /data/file.txt
    4. 4If no snapshot: restore from backup (HDFS to S3/Azure, Hive metastore backup). Lesson: always enable snapshots on critical directories!

Q13 SCENARIO: NameNode is in safe mode and cluster is not accepting writes. Fix it?

NameNode enters safe mode on startup or when blocks fall below minimum replication. Check with hdfs dfsadmin -safemode get. Wait for DataNodes to report blocks β€” safe mode usually exits automatically. If stuck: hdfs dfsadmin -safemode leave (only after verifying blocks are actually replicated, not just because you're impatient!).

SECTION 2: NameNode HA β€” QUESTIONS

⚑ Q14What is NameNode Single Point of Failure (SPOF)?

Hadoop 1 had ONE NameNode β€” if it crashed, entire HDFS went down. No writes, no reads. Hadoop 2 introduced Active/Standby HA to eliminate this.

Q15How does NameNode HA work?

Active NameNode writes edit log to JournalNodes (quorum = must write to N/2+1 JNs). Standby NameNode reads same JournalNode logs, stays in sync. ZooKeeper detects Active failure (via ZKFC - ZooKeeper Failover Controller). ZKFC triggers fencing β†’ kills old Active β†’ promotes Standby to Active.

⚠️ Q16What is split-brain in NameNode HA? How does fencing prevent it?

Split-brain: both Active and Standby think they are Active β†’ two NameNodes write metadata simultaneously β†’ data corruption. Fencing: before promoting Standby, ZKFC sends SSH command to old Active to kill itself (or calls a fencing script). New Active only starts AFTER old Active is confirmed dead.

Q17What are JournalNodes?

Separate lightweight daemons (typically 3 or 5, odd number for quorum). Active NameNode writes every edit log entry to a MAJORITY (quorum) of JournalNodes. Standby reads from JournalNodes to stay in sync. If a JournalNode is down, writes still proceed (quorum, not all-or-nothing). Typical setup: 3 JournalNodes β†’ can tolerate 1 failure.

SECTION 3: YARN β€” QUESTIONS

⚑ Q18What is YARN?

Yet Another Resource Negotiator β€” Hadoop's cluster resource manager. Decouples resource management from processing framework. Before YARN (Hadoop 1): only MapReduce ran on the cluster. With YARN: Spark, Flink, MapReduce, Tez all share same cluster resources.

Q19YARN components β€” explain each.

ResourceManager (RM): Cluster boss. Scheduler allocates containers, ApplicationsManager tracks running apps. NodeManager (NM): Per-node daemon. Launches containers, monitors CPU/memory per container, kills containers that exceed limits. ApplicationMaster (AM): Per-JOB daemon. Requests containers from RM, coordinates job execution, handles task failures within a job.

Q20What is a Container in YARN?

A unit of resource allocation (CPU vcores + memory) on a specific NodeManager. A MapReduce mapper = one container. A Spark executor = one container. RM assigns containers, NM enforces resource limits.

⚑ Q21YARN Scheduler types β€” when to use each?
βœ… Pro Tip
FIFO: First in first out. Never use in multi-user production. Capacity Scheduler: Multiple queues, guaranteed % capacity per team. Use for enterprise multi-tenant. Fair Scheduler: All jobs get equal resources over time. Use when running many small-medium jobs from multiple users.
⚠️ Q22What happens when a NodeManager dies?

RM detects missing heartbeat β†’ marks NM dead β†’ all containers on that NM are lost β†’ ApplicationMaster is notified β†’ AM re-requests containers from RM for failed tasks β†’ job continues but with delay. YARN handles NM failures transparently.

SECTION 4: MAPREDUCE β€” QUESTIONS

⚑ Q23Explain MapReduce phases in order.
    1. Input Splits (decide mapper count) β†’
    2. 2Map (process each split) β†’
    3. 3Combiner (optional local aggregation) β†’
    4. 4Partitioner (decides which reducer gets which key) β†’
    5. 5Shuffle+Sort (move + sort data across network) β†’
    6. 6Reduce (aggregate, output) β†’
    7. 7Output (write to HDFS).
Q24What is the Shuffle phase? Why is it the most expensive?
βœ… Pro Tip
Shuffle = moving map outputs to the correct reducer across the network. Sorted by key. Data goes: mapper β†’ local disk β†’ network β†’ reducer's disk β†’ reducer. It's expensive because: hits local disk twice + crosses network + sorts data. Performance tip: minimize shuffle data with combiners and compression.
Q25What is a Combiner? Rules for using it?
  1. Mini-reducer that runs on the mapper's local node BEFORE shuffle. Reduces network traffic by pre-aggregating locally. RULES:
  2. 1Must be commutative AND associative (order doesn't matter, grouping doesn't matter).
  3. 2Works for: SUM, COUNT, MAX, MIN.
  4. 3DOES NOT work for: AVERAGE (average of averages β‰  total average).
⚠️ Q26Why can't you use a Combiner for calculating Average?

Average is NOT associative. avg(avg(1,2), avg(3,4)) = avg(1.5, 3.5) = 2.5, but correct avg(1,2,3,4) = 2.5... wait β€” this particular example works but with unequal group sizes it fails: avg(avg(1), avg(2,3,4)) = avg(1, 3) = 2, but correct avg = 2.5. Solution: emit (sum, count) as value β†’ reduce calculates sum/count.

Q27What is a Partitioner?

Decides which reducer receives which key. Default: HashPartitioner (key.hashCode() % numReducers). Custom partitioner used when you want: specific keys to go to specific reducers, or when default causes data skew.

⚑ Q28What is Speculative Execution?

When a task runs much slower than peers (straggler), Hadoop launches a DUPLICATE of that task on another node. Whichever finishes first wins, the other is killed. Enabled by default. ⚠️ DISABLE if tasks have side effects (writing to external DB, calling APIs) β€” otherwise same operation runs TWICE!

SECTION 5: OPTIMIZATIONS β€” QUESTIONS

⚑ Q29What is mapreduce.task.io.sort.mb and why does it matter?

The in-memory sort buffer for map output. Default: 100 MB (too small!). When 80% full, Hadoop spills to disk. Many spills = many small disk files + merge overhead = slow shuffle. Increase to 512 MB to reduce spills. Rule: fits within mapper container memory (usually 80% of container).

Q30How do you compress map output and why?

Set mapreduce.map.output.compress=true and mapreduce.map.output.compress.codec=SnappyCodec. Snappy is fast compress/decompress β€” compresses shuffle data 50-70% β†’ massive network bandwidth savings. Cost: small CPU overhead (almost always worth it).

⚠️ Q31GZIP vs Snappy vs LZO β€” when to use each?

Snappy: Fast, medium compression, NOT splittable β†’ use for shuffle intermediate data. GZIP: Medium speed, high compression, NOT splittable β†’ use for final archive output. LZO: Fast, medium compression, SPLITTABLE (with index) β†’ use for output that will be INPUT to another MapReduce job. ⚠️ Non-splittable codec on large output file = ONE mapper handles entire file!

Q32What is JVM Reuse and when should you use it?

mapreduce.job.jvm.numtasks=10 β€” same JVM handles 10 tasks before restart. Saves JVM startup time (100-500 ms per task). Use when: thousands of small tasks (small files). ⚠️ Can cause memory leaks if tasks have bugs β†’ only use with stable code.

⚑ Q33How to fix a slow MapReduce job that has 99 reducers done but 1 still running for hours?
  1. Classic DATA SKEW. One key has disproportionate data. Solutions:
  2. 1Salting (add random suffix to hot key to spread across reducers)
  3. 2Custom partitioner
  4. 3Add Combiner to pre-reduce hot key data
  5. 4Increase reducer count so hot key impact is diluted. Root cause: HashPartitioner sent all "US" records to one reducer.
Q34What is the optimal number of reducers formula?

0.95 Γ— (num_nodes Γ— containers_per_node). The 0.95 factor ensures slightly fewer reducers than total capacity β†’ room for ApplicationMaster and other overhead. ⚠️ Default is 1 reducer β€” terrible for large jobs!

SECTION 6: HDFS COMMANDS β€” QUICK FIRE

Q35How to check HDFS file system health?

hdfs fsck / -files -blocks -locations β€” shows corrupt blocks, missing blocks, under-replicated blocks. -files: list each file. -blocks: show block details. -locations: show which DataNodes have each block.

Q36How to check cluster usage?

hdfs dfsadmin -report β€” shows each DataNode: capacity, used, remaining. Shows total cluster storage.

Q37How to check safe mode status?

hdfs dfsadmin -safemode get β†’ outputs Safe mode is OFF or Safe mode is ON.

Q38How to run the HDFS balancer?

hdfs balancer -threshold 10 β€” rebalances blocks so no DataNode is more than 10% above/below average utilization. Run after adding new DataNodes!

🧠 FINAL REVISION β€” Day 1 Summary Card

πŸ“ Architecture Diagram
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚               DAY 1: HDFS + YARN + MAPREDUCE                      β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚                                                                  β”‚
β”‚  HDFS KEY FACTS:                                                 β”‚
β”‚  NameNode: live namespace/block maps in RAM; FsImage+edits on diskβ”‚
β”‚  DataNode: actual 128 MB blocks, heartbeat every 3 seconds        β”‚
β”‚  Replication: 3 copies, rack-aware (cross-rack for 2nd copy)     β”‚
│  Write path: client→NN→pipeline(DN1→DN2→DN3)→ACK chain          │
β”‚  Read path: NN gives locations β†’ client reads directly from DNs  β”‚
β”‚                                                                  β”‚
β”‚  NAMENODE HA:                                                    β”‚
β”‚  Active + Standby (both read JournalNodes)                       β”‚
β”‚  ZooKeeper + ZKFC = automatic failover                           β”‚
β”‚  FENCING = kill old Active before promoting Standby (split-brain!)β”‚
β”‚  3 JournalNodes (quorum) β†’ can tolerate 1 JN failure            β”‚
β”‚                                                                  β”‚
β”‚  YARN:                                                           β”‚
β”‚  RM (cluster boss) + NM (per-node) + AM (per-job)               β”‚
β”‚  Schedulers: FIFO (dev) / Capacity (multi-tenant) / Fair (mixed) β”‚
β”‚  Container = CPU + Memory allocation on a NodeManager            β”‚
β”‚                                                                  β”‚
β”‚  MAPREDUCE FLOW = "I-Map-CBS-Reduce-O":                         β”‚
β”‚  Input Splits β†’ Map β†’ Combiner β†’ Buffer+Sort β†’ Shuffle β†’ Reduce  β”‚
β”‚  Shuffle: most expensive (disk + network)                        β”‚
β”‚  Combiner: cut network 60-80% (only for commutative+associative) β”‚
β”‚  Speculative: duplicate slow tasks (disable if side effects!)    β”‚
β”‚                                                                  β”‚
β”‚  OPTIMIZATIONS = "MCJ-COMP":                                     β”‚
│  M-Memory: sort buffer 100 MB→512 MB (biggest win!)               │
β”‚  C-Combiner: pre-aggregate locally (SUM/COUNT/MAX/MIN)           β”‚
β”‚  J-JVM Reuse: numtasks=10 for small file jobs                    β”‚
β”‚  C-Compress shuffle: Snappy codec β†’ 50-70% network reduction     β”‚
β”‚  O-Output compress: GZIP for archives, LZO for pipeline output   β”‚
β”‚  M-More reducers: 1β†’N (formula: nodesΓ—containersΓ—0.95)          β”‚
β”‚  P-Partitioner: custom for skewed data (salting)                 β”‚
β”‚                                                                  β”‚
β”‚  SMALL FILES PROBLEM:                                            β”‚
β”‚  Each file = 1 metadata entry in NameNode RAM                    β”‚
β”‚  Fix: HAR / SequenceFile / CombineInputFormat / Hive merge       β”‚
β”‚                                                                  β”‚
β”‚  HADOOP VERSIONS:                                                β”‚
β”‚  v1: Single NameNode (SPOF), only MapReduce                      β”‚
β”‚  v2: YARN, NameNode HA, HDFS Federation                          β”‚
β”‚  v3: Erasure Coding (50% storage savings for cold data)          β”‚
β”‚                                                                  β”‚
β”‚  TOP 5 THINGS TO SAY IN INTERVIEW:                               β”‚
β”‚  1. "NameNode HA uses JournalNodes + ZooKeeper + FENCING"        β”‚
β”‚  2. "Shuffle is the bottleneck β€” minimize with combiner+compress" β”‚
β”‚  3. "Sort buffer default 100 MB is too small β€” increase to 512 MB" β”‚
β”‚  4. "Speculative execution: disable if tasks have side effects"  β”‚
β”‚  5. "Erasure coding in Hadoop 3: 50% storage savings for cold"   β”‚
β”‚                                                                  β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
Intermediate

Hive and the Hadoop Ecosystem

#

Answer-first recall layer

Recall: Hive architecture

Answer First: Hive compiles SQL through parsing, semantic analysis, optimization, and physical planning, then executes the plan through an engine such as Tez while the Metastore supplies table and partition metadata.

Memory Map: client -> HiveServer2 -> compiler/optimizer -> Metastore -> execution engine -> storage.

Recall: managed and external tables

Answer First: Table type primarily governs lifecycle: dropping a managed table removes its managed data, while dropping an external table normally removes metadata but leaves data at its external location.

Memory Map: schema and location -> ownership -> DROP behavior.

Recall: partitioning

Answer First: Partitioning maps selected column values to directory-level metadata so predicates can prune whole paths; static inserts name values explicitly, while dynamic inserts derive them from rows.

Memory Map: predicate -> partition metadata -> directory pruning -> fewer files scanned.

Recall: bucketing

Answer First: Bucketing hashes a key into a fixed number of files and can support sampling and compatible bucket-aware joins, but it does not replace partition pruning and only helps when writers enforce the layout.

Memory Map: hash key -> bucket number -> stable files -> sampling/join opportunity.

Recall: Hive file formats

Answer First: Use ORC or Parquet for analytic scans and pruning, Avro for row-oriented interchange and schema evolution, and TextFile/CSV mainly for landing, interchange, and debugging. Text can be compressed, but its row-oriented layout and the codec's splittability still govern scan cost and parallelism.

Memory Map: workload -> row/column layout -> statistics -> compression -> interoperability.

Recall: Hive query optimization

Answer First: Start with partition pruning and file layout, refresh statistics for CBO, use vectorized execution and an appropriate engine, and inspect joins, skew, reducer counts, and spills in the physical plan.

Memory Map: EXPLAIN -> scan/prune -> join -> skew -> vectorize -> engine counters.

Recall: HBase

Answer First: HBase is a distributed, sparse, sorted key-value store on HDFS for low-latency random access; row-key design determines locality, hotspot risk, and scan efficiency.

Memory Map: row key -> region -> RegionServer -> HFile/WAL -> compaction.

Recall: ecosystem ingestion and coordination

Answer First: Sqoop parallelizes bulk RDBMS transfer, Flume streams event data, Oozie coordinates Hadoop workflows, and ZooKeeper provides coordination primitives; each solves a different control or data-plane problem.

Memory Map: sources -> Sqoop/Flume -> HDFS/Hive -> Oozie workflow; ZooKeeper coordinates.

Canonical source guide

Merged from HD_02_Hive_Ecosystem.md; the legacy source remains unchanged.

Day 2: Hive + Hadoop Ecosystem β€” Deep Interview Guide

All 3 levels per topic β€” from fundamentals to advanced scenarios Key for today: Hive is your SQL layer on top of HDFS. Understand it deeply. Focus: Hive internals, optimizations (CRITICAL!), HBase, Sqoop, Oozie, ZooKeeper

🧠 MASTER MEMORY MAP β€” Day 2

sql
HIVE ARCHITECTURE = "DMCTE"
    D β€” Driver (receives SQL queries, manages lifecycle)
    M β€” Metastore (schema + HDFS location mapping β€” the catalog)
    C β€” Compiler (parses SQL β†’ query plan)
    T β€” Tez/MR Engine (executes the plan)
    E β€” Execution (launches tasks on YARN)

HIVE OPTIMIZATION = "VECTOR-TOP":
    V β€” Vectorization (process 1024 rows at once, not 1)
    E β€” Engine: evaluate Tez instead of MapReduce for multi-stage DAG execution
    C β€” Column pruning (SELECT only needed columns)
    T β€” Table stats: ANALYZE TABLE for CBO
    O β€” ORC format (columnar + predicate pushdown)
    R β€” REPARTITION/REDISTRIBUTE (avoid data skew)

    T β€” Tez DAG (avoid MapReduce chains)
    O β€” Order of joins (small table FIRST for map join)
    P β€” Partition pruning (WHERE on partition columns only)

HIVE FILE FORMATS = "OPTA"
    O β€” ORC    (best for Hive: columnar, ACID, compression)
    P β€” Parquet (best for cross-tool: Spark, Impala, Hive)
    T β€” Text   (default, row-oriented; compressed input supported; useful for landing/interchange)
    A β€” Avro   (row-based, best for Kafka/Sqoop schema evolution)

PARTITIONING RULES = "QDLF"
    Q β€” Query filter columns β†’ partition by those columns
    D β€” Date/region usually best partition keys
    L β€” Low cardinality (10s to 100s of values, not millions!)
    F β€” Few files per partition (avoid small files inside partitions)

SECTION 1: HIVE ARCHITECTURE

What is Hive?

Hive is SQL-on-Hadoop. You write HiveQL (SQL dialect), Hive translates it to MapReduce or Tez jobs that run on YARN. Data lives in HDFS, schema lives in Metastore. Analogy: Hive is the "database frontend" for HDFS. HDFS stores the data like a file system, but you want to query it like a database. Hive bridges that gap.

sql
HOW HIVE WORKS (end-to-end):

You type:  SELECT country, COUNT(*) FROM bookings GROUP BY country;
           ↓
Driver:    Receives your query, manages session
           ↓
Compiler:  Parses SQL β†’ AST (Abstract Syntax Tree)
           ↓
Metastore: Compiler asks Metastore: "where is 'bookings' table in HDFS?"
           β†’ Returns: /user/hive/warehouse/bookings, format=ORC, partitions=[2023,2024]
           ↓
Optimizer: Rewrite query to most efficient plan (Cost-Based Optimizer if stats exist)
           β†’ Decides: map join or shuffle join? apply partition pruning?
           ↓
Execution: Submit MapReduce/Tez job to YARN
           ↓
Output:    Results written to HDFS or returned to client

Hive Metastore β€” The Most Important Component

🧠 METASTORE = "The Schema Registry for Hive"
METASTORE"The Schema Registry for Hive"
What it stores:
Table name β†’ HDFS path mapping (/user/hive/warehouse/bookings)
Table schema (columns, data types)
Partition information (which partition directories exist)
File format (ORC, Parquet, Text)
Statistics (number of rows, column stats β€” used by Cost-Based Optimizer)
Where it lives:
Backend: MySQL/PostgreSQL database (NOT HDFS!)
The MySQL DB stores all the schema metadata as rows
Metastore modes:
1. Embedded: Metastore + Hive in same JVM (dev/testing only)
2. Local: Separate Metastore process, same machine (not used much)
3. Remote: Metastore runs as separate service (PRODUCTION standard)
Multiple HiveServer2 instances connect to ONE Metastore
β†’ Allows BI tools (Tableau, PowerBI) to connect simultaneously
⚠️CRITICAL: If Metastore MySQL goes down β†’ ALL Hive queries fail!
Because Hive cannot find WHERE tables are in HDFS without Metastore.
Solution: Metastore HA with MySQL replication or AWS RDS Multi-AZ

SECTION 2: HIVE INTERNAL vs EXTERNAL TABLES

The Most Commonly Asked Hive Question

sql
INTERNAL TABLE (Managed Table):
    CREATE TABLE bookings (
        booking_id STRING,
        passenger STRING,
        flight STRING,
        amount DOUBLE
    )
    STORED AS ORC;
    -- Data goes to: /user/hive/warehouse/bookings/
    -- Hive OWNS this data

    WHAT HAPPENS ON DROP TABLE:
    β†’ DROP TABLE bookings;
    β†’ Hive deletes BOTH metadata (from Metastore) AND data (from HDFS)!
    ⚠️ Data is GONE. Cannot recover unless Trash is enabled.

EXTERNAL TABLE:
    CREATE EXTERNAL TABLE bookings_external (
        booking_id STRING,
        passenger STRING
    )
    LOCATION '/data/raw/bookings/'   -- You specify HDFS path
    STORED AS ORC;
    -- Hive points TO this data but does NOT own it

    WHAT HAPPENS ON DROP TABLE:
    β†’ DROP TABLE bookings_external;
    β†’ Hive deletes ONLY metadata from Metastore
    β†’ Data in /data/raw/bookings/ is UNTOUCHED ← this is the key difference!

Decision Guide β€” Internal vs External

sql
USE INTERNAL WHEN:
  βœ“ Hive is the only tool accessing this data
  βœ“ You want Hive to manage lifecycle (cleanup = just DROP TABLE)
  βœ“ Gold/final tables that won't be shared

USE EXTERNAL WHEN:
  βœ“ Data is shared with Spark, Presto, Pig, other tools
  βœ“ Data is ingested by another process (Sqoop, Flume, Kafka)
  βœ“ You CANNOT afford accidental data deletion on DROP TABLE
  βœ“ Data lives outside /user/hive/warehouse/
  βœ“ Production Bronze/Silver tables (raw landing, shared data)

EXAMPLE:
  Raw flight data ingested by Sqoop every hour β†’ EXTERNAL TABLE
  (Sqoop writes to HDFS path, Hive just reads it, never owns it)
  Aggregated booking report table β†’ INTERNAL TABLE
  (Hive fully manages this output)

SECTION 3: HIVE PARTITIONING

Static vs Dynamic Partitioning

WHAT IS A HIVE PARTITION?
A partition = a subdirectory in HDFS under the table's location
Example: /user/hive/warehouse/bookings/booking_date=2024-01-15/
Hive reads ONLY the subdirectory for the date you filter on
Result: instead of scanning 365 daily partitions→scan 1; elapsed speedup still depends on files, metadata, and the rest of the plan.
TABLE DEFINITION WITH PARTITION
sql
-- Partitioned table: booking_date is the partition column
-- booking_date does NOT appear in the regular column list!
CREATE TABLE bookings (
    booking_id  STRING,
    passenger   STRING,
    flight_code STRING,
    amount      DOUBLE
)
PARTITIONED BY (booking_date STRING)  -- partition key goes here
STORED AS ORC;

-- This creates directory structure:
-- /user/hive/warehouse/bookings/booking_date=2024-01-15/part-00000.orc
-- /user/hive/warehouse/bookings/booking_date=2024-01-16/part-00000.orc
-- ...
sql
-- STATIC PARTITIONING: you manually specify the partition value
INSERT INTO bookings PARTITION (booking_date='2024-01-15')
SELECT booking_id, passenger, flight_code, amount
FROM bookings_raw
WHERE booking_date = '2024-01-15';
-- Loads ONLY one partition at a time
-- SAFE: you control exactly which partition is written
-- Use for: loading historical data one date at a time
sql
-- DYNAMIC PARTITIONING: Hive reads the partition value from the data itself
SET hive.exec.dynamic.partition=true;
SET hive.exec.dynamic.partition.mode=nonstrict;
-- nonstrict = allow ALL partitions to be dynamic (at least 1 static needed for strict mode)

INSERT INTO bookings PARTITION (booking_date)
SELECT booking_id, passenger, flight_code, amount, booking_date  -- booking_date last!
FROM bookings_raw;
-- Hive reads booking_date column from each row, creates partition automatically
-- ⚠️ Can create HUNDREDS of partitions in one query β†’ many small files problem!
-- ⚠️ If booking_date has 1000 unique dates β†’ 1000 partitions Γ— reducers = MANY files

Partition Optimization Settings

sql
-- Limit max dynamic partitions (safety net)
SET hive.exec.max.dynamic.partitions=1000;
SET hive.exec.max.dynamic.partitions.pernode=256;
-- If query would create more than 1000 partitions β†’ FAIL (prevents cluster overload)

-- Merge small output files after insert
SET hive.merge.mapredfiles=true;
SET hive.merge.mapfiles=true;
SET hive.merge.smallfiles.avgsize=128000000;  -- 128 MB target
SET hive.merge.size.per.task=256000000;       -- 256 MB max
-- After INSERT, Hive runs a merge job to combine small output files into larger ones
-- This prevents small files inside partitions!

CRITICAL: MSCK REPAIR TABLE

sql
-- THE SCENARIO: Files added directly to HDFS (bypassing Hive)
-- Example: Sqoop wrote data to /user/hive/warehouse/bookings/booking_date=2024-02-01/
-- But Hive Metastore doesn't know this partition exists!

-- SYMPTOM:
SELECT * FROM bookings WHERE booking_date = '2024-02-01';
-- Returns: 0 rows (Metastore says this partition doesn't exist!)

-- FIX:
MSCK REPAIR TABLE bookings;
-- "MSCK" = MetaStore Check
-- What it does: scans HDFS for partition directories, adds missing partitions to Metastore
-- After this: Hive knows about the new partition β†’ query works!

-- FASTER ALTERNATIVE (add one specific partition):
ALTER TABLE bookings ADD PARTITION (booking_date='2024-02-01')
LOCATION '/user/hive/warehouse/bookings/booking_date=2024-02-01/';

-- ⚠️ MSCK REPAIR can be SLOW on tables with THOUSANDS of partitions
-- (scans all of HDFS under the table path)
-- For large tables: use ALTER TABLE ADD PARTITION instead!

SECTION 4: HIVE BUCKETING

WHAT IS BUCKETING?
Divide table data into N fixed buckets (fixed number of files)
based on HASH of a column's value
Each bucket = one file in the partition directory
BUCKETING vs PARTITIONING:
PARTITIONING: BUCKETING:
Subdirectory per value Fixed N files per table/partition
Good for: date/region Good for: user_id, booking_id (high cardinality)
Cardinality: LOW Cardinality: HIGH
Pruning: YES Pruning: NO (reads all buckets usually)
Benefit: skip partitions Benefit: efficient sampling + JOIN optimization
sql
-- Create bucketed table: divide by booking_id into 32 buckets
CREATE TABLE bookings_bucketed (
    booking_id  STRING,
    passenger   STRING,
    amount      DOUBLE
)
CLUSTERED BY (booking_id) INTO 32 BUCKETS
STORED AS ORC;

-- Insert data β€” Hive automatically routes rows to correct bucket via hash(booking_id) % 32
INSERT INTO bookings_bucketed SELECT * FROM bookings_raw;

-- Bucket JOIN optimization (two tables bucketed by SAME column in SAME number of buckets)
-- Bucket 1 from table A joins with Bucket 1 from table B β†’ NO SHUFFLE!
SET hive.optimize.bucketmapjoin=true;
SET hive.optimize.bucketmapjoin.sortedmerge=true;

-- Hash sampling into 10 logical sample buckets:
SELECT * FROM bookings_bucketed TABLESAMPLE(BUCKET 1 OUT OF 10 ON booking_id);
-- This deterministically selects one hash bucket, but does not guarantee exactly 10% of rows.
-- Physical input pruning aligns best when y divides or is a multiple of the table's bucket count.
-- Here 10 is neither a divisor nor a multiple of 32, so Hive cannot map the sample cleanly
-- to whole physical bucket files and may need to scan broader input.

-- Alignment example for a 32-bucket table: y=16 selects two physical buckets.
SELECT * FROM bookings_bucketed TABLESAMPLE(BUCKET 1 OUT OF 16 ON booking_id);

SECTION 5: HIVE FILE FORMATS β€” DEEP COMPARISON

🧠 Memory Map
ORC (Optimized Row Columnar) β€” Best for HIVE:
Structure: Stripe→Row group → Column data
Each stripe = 250 MB (configurable)
Each stripe has: min/max stats for every column
β†’ Predicate pushdown: "WHERE amount > 1000"β†’skip stripes where max < 1000!
Features:
βœ“ Built-in compression (ZLIB, Snappy)
βœ“ ACID support (INSERT/UPDATE/DELETE in Hive)
βœ“ Column-level min/max for predicate pushdown
βœ“ Native to Hive β€” best optimization
βœ“ Bloom filters per column (point lookup optimization)
βœ— Less inter-operable with non-Hive tools
PARQUET β€” Best for CROSS-TOOL use (Hive + Spark + Impala):
Structure: Row group→Column chunk → Data pages
Default row group: 128 MB
Column encoding: dictionary, RLE, delta
Features:
βœ“ Supported by Hive, Spark, Impala, Presto, Drill, Pandas
βœ“ Nested schemas (arrays, maps inside columns) β€” great for JSON-like data
βœ“ Good compression (Snappy or GZIP)
βœ— ACID support in Hive is weaker than ORC
βœ— Slightly less optimized in pure Hive workloads vs ORC
TEXT/CSV β€” Useful for landing and interchange, usually not ideal for analytical serving:
βœ“ TextFile is Hive's default storage format and can store compressed text/CSV
βœ“ Hive automatically detects Gzip and Bzip2 when they are loaded into a TextFile table
βœ“ Human-readable and broadly interoperable for exchange, inspection, and recovery workflows
βœ— The format is row-oriented and lacks column statistics and column pruning
βœ— It offers no format-level predicate pushdown, so filters must parse records unless partitions prune files
βœ— Parallelism depends on codec splittability: a large Gzip file is not splittable;
Bzip2 is splittable but CPU-heavy, so validate file sizes and codec costs
AVRO β€” Best for SCHEMA EVOLUTION + KAFKA/SQOOP:
Row-based (not columnar) β†’ not great for analytics
βœ“ Schema evolution: add/remove fields without breaking downstream
βœ“ Works perfectly with Kafka (Confluent Schema Registry uses Avro)
βœ“ Sqoop imports delimited text by default; request Avro explicitly with `--as-avrodatafile`
βœ— Not columnarβ†’full row scan
Use for: staging/landing tables, Kafka consumers, Sqoop imports

File Format Decision Guide

sql
-- Create ORC table with compression:
CREATE TABLE bookings_orc (
    booking_id STRING, passenger STRING, amount DOUBLE
)
STORED AS ORC
TBLPROPERTIES ("orc.compress"="SNAPPY");
-- SNAPPY = fast (good for hot frequently-read data)
-- ZLIB = more compressed (good for cold archive data)

-- Create Parquet table:
CREATE TABLE bookings_parquet (
    booking_id STRING, passenger STRING, amount DOUBLE
)
STORED AS PARQUET;

-- Convert existing Text table to ORC (HUGE performance win):
CREATE TABLE bookings_orc STORED AS ORC AS
SELECT * FROM bookings_text;
-- This can materially reduce scanned bytes; measure the full query rather than assuming a multiplier.

SECTION 6: HIVE QUERY OPTIMIZATION β€” ALL SETTINGS

⚑ THIS IS WHAT A SENIOR ENGINEER MUST KNOW DEEPLY

Optimization 1: Execution Engine β€” Use Tez, NOT MapReduce

sql
-- DEFAULT in older clusters: MapReduce (slow)
-- SET this at the START of every Hive session:
SET hive.execution.engine=tez;  -- Or 'mr' for MapReduce (don't use)

-- WHY TEZ IS FASTER:
-- MapReduce: Chain of MR jobs β†’ each writes to HDFS between stages
-- SELECT country, COUNT(*), SUM(amount) GROUP BY country ORDER BY country
-- MapReduce: Job1 (GROUP BY) β†’ write HDFS β†’ Job2 (ORDER BY) β†’ write HDFS
-- Tez:       One DAG: GROUP BY β†’ ORDER BY; it avoids materializing every MR stage as HDFS output, but can still spill.
-- Result: often less startup and intermediate-I/O overhead; benchmark the actual plan.

Optimization 2: Vectorization (Process Rows in Batches)

sql
-- Enable vectorized query execution
SET hive.vectorized.execution.enabled=true;
SET hive.vectorized.execution.reduce.enabled=true;

-- WHAT IT DOES:
-- Default: process 1 row at a time (row-by-row)
-- Vectorized: process 1024 rows at once (batch)
-- Uses CPU SIMD instructions (process multiple values in parallel on the CPU)
-- Result: batch execution can improve CPU efficiency for supported types and formats; measure it.
-- Works BEST with ORC format (which stores data column-by-column)
-- ⚠️ Only works with ORC (not Text or CSV tables)

Optimization 3: Cost-Based Optimizer (CBO)

sql
-- Enable Cost-Based Optimizer
SET hive.cbo.enable=true;
SET hive.compute.query.using.stats=true;
SET hive.stats.fetch.column.stats=true;

-- CBO needs TABLE STATISTICS to work:
ANALYZE TABLE bookings COMPUTE STATISTICS;           -- row count, file sizes
ANALYZE TABLE bookings COMPUTE STATISTICS FOR COLUMNS booking_id, country, amount;
-- Column stats: min, max, distinct count, nulls
-- CBO uses these stats to choose optimal join order and join type

-- WITHOUT stats: Hive guesses β†’ wrong join order β†’ shuffle join for a small table
-- WITH stats:    CBO says "passengers table has 10k rows β†’ use MAP JOIN, no shuffle"

Optimization 4: Map Join (Small Table Broadcast)

sql
-- MAP JOIN = load small table into EVERY mapper's RAM, join locally (NO SHUFFLE!)
-- Auto map join (CBO decides based on table size):
SET hive.auto.convert.join=true;
SET hive.mapjoin.smalltable.filesize=25000000;  -- 25 MB threshold
-- If the smaller table < 25 MB β†’ Hive automatically uses map join
-- ⚠️ Increase this if you have slightly larger but still "small" dimension tables

-- FORCE map join for a specific query with hint:
SELECT /*+ MAPJOIN(airports) */
    b.booking_id,
    a.airport_name
FROM bookings b
JOIN airports a ON b.departure_airport = a.code;
-- airports table is small (100 airports) β†’ broadcast to all mappers β†’ NO shuffle!

-- BUCKET MAP JOIN (both tables bucketed by join key):
SET hive.optimize.bucketmapjoin=true;
-- Even faster: only load matching bucket from small table into mapper

Optimization 5: Partition Pruning

sql
-- PARTITION PRUNING: Hive SKIPS partitions not matching WHERE clause
-- ⚠️ ONLY WORKS if you filter on the PARTITION COLUMN!

-- βœ“ GOOD β€” partition pruning works (only scans booking_date=2024-01-15):
SELECT COUNT(*) FROM bookings WHERE booking_date = '2024-01-15';

-- βœ— BAD β€” NO partition pruning (scans ALL partitions!):
SELECT COUNT(*) FROM bookings WHERE YEAR(booking_date) = 2024;
-- Hive applies function YEAR() to each row β†’ can't prune without scanning all!
-- FIX: WHERE booking_date BETWEEN '2024-01-01' AND '2024-12-31'

-- βœ— ANOTHER TRAP β€” dynamic partition filter from subquery:
-- This may or may not prune depending on Hive version and optimizer
SELECT * FROM bookings b
JOIN date_dim d ON b.booking_date = d.date
WHERE d.year = 2024;
-- May not prune! Use: WHERE b.booking_date >= '2024-01-01'

Optimization 6: GROUP BY Skew Handling

sql
-- Data skew in GROUP BY (one key dominates):
-- Example: 50% of bookings are from 'US' β†’ one reducer handles all US data!

SET hive.groupby.skewindata=true;
-- What Hive does: 2-phase aggregation:
-- Phase 1: randomly distribute keys β†’ partial aggregation in parallel
-- Phase 2: final aggregation by real key
-- Result: no single reducer bottleneck for skewed keys

-- Also for skewed JOIN:
SET hive.optimize.skewjoin=true;
SET hive.skewjoin.key=100000;  -- Keys with > 100k rows are treated as "skew keys"

Optimization 7: LLAP (Live Long And Process) β€” Hive Sub-Second Queries

LLAPLive Long And Process
Problem: Every Hive query spins up new containers→JVM startup = 5-30 seconds overhead
LLAP Solution:
Persistent JVM daemons on each node (always running, no startup!)
In-memory columnar cache (keep hot data in RAM across queries)
Sub-second queries for dashboard/BI workloads (like Impala but inside Hive)
SET hive.llap.execution.mode=auto; -- Use LLAP when available, fallback to Tez
⚑ INTERVIEW TIP:
"LLAP is Hive's answer to Impala. It adds persistent daemons with in-memory cache.
Without LLAP, every query has cold-start overhead. With LLAP, same data stays warm
in memory β€” especially valuable for BI dashboards hitting the same tables repeatedly."

Optimization 8: Sorting and Ordering

sql
-- ORDER BY vs SORT BY vs DISTRIBUTE BY vs CLUSTER BY:

ORDER BY column     -- Global sort (all data goes to ONE reducer) β†’ SLOW for large data
SORT BY column      -- Local sort (each reducer sorts its own output) β†’ FAST but not globally sorted
DISTRIBUTE BY col   -- Control which rows go to which reducer (like partitioner)
CLUSTER BY col      -- = DISTRIBUTE BY col SORT BY col (same column for both)

-- ⚑ INTERVIEW TRAP: "What's the difference between ORDER BY and SORT BY?"
-- ORDER BY: guaranteed global order, uses 1 reducer (slow for billions of rows!)
-- SORT BY: each reducer output is sorted, but globally NOT sorted (multiple reducers)
-- Use SORT BY when you just need local sorted chunks (e.g., before writing partitioned output)
-- Use ORDER BY only for final result sets that need to be globally ordered

SECTION 7: WHAT-IF SCENARIOS β€” HIVE

SCENARIO 1: Data deleted manually from HDFS (most common interview question!)

sql
-- WHAT HAPPENED:
-- Someone ran: hdfs dfs -rm -r /user/hive/warehouse/bookings/booking_date=2024-01-15/
-- Now this query returns 0 rows:
SELECT COUNT(*) FROM bookings WHERE booking_date = '2024-01-15';
-- Even though Metastore thinks the partition exists!

-- DIAGNOSIS:
-- 1. Check if partition exists in Metastore:
SHOW PARTITIONS bookings;
-- Shows: booking_date=2024-01-15 (it's there in Metastore!)
-- 2. Check if files exist in HDFS:
-- hdfs dfs -ls /user/hive/warehouse/bookings/booking_date=2024-01-15/
-- Output: No such file or directory ← CONFIRMED β€” data deleted!

-- FIX OPTIONS:
-- Option 1: Restore data from backup and MSCK REPAIR TABLE bookings
-- Option 2: If no backup β€” DROP the stale partition from Metastore:
ALTER TABLE bookings DROP PARTITION (booking_date='2024-01-15');
-- Now Hive is consistent again (it won't show non-existent partition)
-- Then: reload data into that partition from source

-- PREVENTION:
-- 1. NEVER run hdfs dfs -rm directly on Hive-managed table locations
-- 2. Use HDFS Trash (hdfs dfs -rm moves to .Trash, not permanent delete)
-- 3. Enable HDFS Snapshots for the warehouse directory

SCENARIO 2: New data added to HDFS but Hive doesn't see it

sql
-- WHAT HAPPENED: Sqoop/Spark wrote new partition directory to HDFS
-- but forgot to register it in Hive Metastore

-- DIAGNOSIS:
SELECT * FROM bookings WHERE booking_date = '2024-03-01';
-- Returns 0 rows... but file exists in HDFS!

-- FIX β€” Option 1: MSCK REPAIR (for EXTERNAL tables, scans all partitions):
MSCK REPAIR TABLE bookings;

-- FIX β€” Option 2: ADD PARTITION (fast, for specific known partition):
ALTER TABLE bookings ADD IF NOT EXISTS PARTITION (booking_date='2024-03-01')
LOCATION '/user/hive/warehouse/bookings/booking_date=2024-03-01/';

-- ⚠️ MSCK REPAIR on a table with 10,000 partitions β†’ scans 10,000 HDFS paths!
-- Use ALTER TABLE ADD PARTITION when you know exactly which partition to add

SCENARIO 3: Hive query is very slow β€” debug and fix

sql
-- STEP 1: Enable EXPLAIN to see query plan:
EXPLAIN SELECT country, COUNT(*) FROM bookings GROUP BY country;
-- Look for: Map Join vs Shuffle Join, partition pruning status, # of Map/Reduce stages

-- STEP 2: Check query stats after run:
SET hive.stats.autogather=true;
-- After INSERT: Hive auto-collects stats (rows, bytes)

-- STEP 3: Check if vectorization is working:
EXPLAIN VECTORIZATION SELECT country, COUNT(*) FROM bookings_orc GROUP BY country;
-- Should show "Vectorized execution: true" for ORC tables

-- STEP 4: Check for data skew:
-- If one reducer takes much longer than others β†’ skew problem
SET hive.groupby.skewindata=true;

-- STEP 5: Confirm Tez engine:
SET hive.execution.engine;
-- Should show: tez (if mr β†’ change to tez immediately!)

SECTION 8: HBASE

What is HBase?

sql
HBASE = NoSQL column-family database on top of HDFS

WHY HBASE? HDFS is write-once (append-only). HBase gives you random read/write!
Use when:
  βœ“ Need random row lookups by key (e.g., GET booking_id = 'B12345')
  βœ“ Need sub-10 ms response time for individual record access
  βœ“ Millions of concurrent point queries
  βœ“ Wide-column schema (each row can have different columns)

HBASE vs HIVE:
  HBase: real-time point lookups (GET/PUT/DELETE by row key)
  Hive:  batch analytics (SELECT COUNT(*) GROUP BY)
  HBase: low-latency random access when row keys and regions are designed well; Hive: analytic scans
  HBase: NoSQL, Hive: SQL
  Both: run on top of HDFS

HBase Architecture

🧠 Memory Map
HBASE ARCHITECTURE
HMaster (like NameNode):
Manages region assignment (which RegionServer handles which range of rows)
Handles RegionServer failures, load balancing
ZooKeeper: elects HMaster (Active/Standby HA)
RegionServer (like DataNode):
Each RegionServer handles multiple Regions
Each Region = a range of row keys (e.g., rows A000-A999)
Contains MemStore (RAM) + HFiles (HDFS)
WRITE PATH (HBase)
1. Client writes to WAL (Write-Ahead Log = HLog on HDFS) β†’ durability
2. Data written to MemStore (in RAM) β†’ fast
3. When MemStore full (128 MB default) β†’ flush to HFile on HDFS
4. Background: compact small HFiles into larger ones (compaction)
READ PATH
1. Client→ZooKeeper: "Where is the META table?" (META = region location index)
2. ZooKeeper→"META is on RegionServer 3"
3. Client→META: "Where is row key BK12345?"
4. META→"BK12345 is in Region on RegionServer 7"
5. Client→RegionServer 7: GET row BK12345
6. RegionServer: check MemStore (RAM first) β†’ if not found β†’ BlockCache β†’ HFile
7. Return row to client

HBase Row Key Design β€” CRITICAL INTERVIEW TOPIC

🧠 ROW KEY = Primary key + sorting key + access key in HBase
ROW KEYPrimary key + sorting key + access key in HBase
All HBase reads are by row key (or row key range scan)
❌ BAD ROW KEY: timestamp prefix
Row key: "2024-01-15_BK12345"
Problem: ALL writes go to ONE region (latest timestamp β†’ same RegionServer = HOTSPOT!)
All 1000 writes/second→Region Server 7 handles everything → overload!
βœ“ GOOD ROW KEY: reversed timestamp or salted key
Reversed timestamp: Long.MAX_VALUE - timestamp = rows stored newest-first
Salted: hash(booking_id) % 10 as prefix β†’ distribute writes across 10 regions
ROW KEY DESIGN RULES
1. AVOID monotonically increasing keys (timestamps, auto-increment IDs)
β†’ Creates write hotspot on last region
2. DISTRIBUTE writes across regions (salt prefix, hash prefix, reverse timestamp)
3. Row key = most frequent access pattern (you can only get rows by key!)
4. Keep row keys SHORT (they're stored with every row, saved bytes matter)
5. Row key is LEXICOGRAPHICALLY sorted (alphabetical, not numeric!)
β†’ "9" > "10" in HBase (string sort, not number sort!)
β†’ Store numbers with zero-padding: "0009", "0010"
EXAMPLE
Booking lookup service:
βœ“ Row key: booking_id (used for direct lookups)
βœ— NOT: booking_date + booking_id (hotspot on recent dates)
Use: salt_prefix(booking_id) + booking_id β†’ distribute across regions

SECTION 9: SQOOP β€” RDBMS to Hadoop

SQOOPSQL-to-Hadoop
Purpose: Import data FROM relational databases (Oracle, MySQL, PostgreSQL) INTO HDFS/Hive
Export data FROM HDFS TO relational databases
Use case: Import flight inventory from Oracle→HDFS for Hive analysis
bash
# BASIC IMPORT: Oracle table β†’ HDFS
sqoop import \
  --connect jdbc:oracle:thin:@//db-host:1521/ENTERPRISE \
  --username etl_user \
  --password 'secret' \
  --table FLIGHT_INVENTORY \
  --target-dir /data/raw/flight_inventory/ \
  --num-mappers 4             # 4 parallel import tasks

# IMPORT WITH HIVE INTEGRATION: directly to Hive table
sqoop import \
  --connect jdbc:mysql://db-host/bookings \
  --username user --password pass \
  --table bookings \
  --hive-import \             # create Hive table automatically
  --hive-table booking_db.bookings_raw \
  --create-hive-table \
  --num-mappers 8

# INCREMENTAL IMPORT (most important for production!):
# Only import NEW rows since last run (much faster than full import daily)

# Mode 1: append β€” for insert-only tables (new rows have higher IDs)
sqoop import \
  --connect jdbc:oracle:thin:@//db-host:1521/ENTERPRISE \
  --table BOOKINGS \
  --incremental append \
  --check-column booking_id \     # column to check for new rows
  --last-value 1000000 \          # only import booking_id > 1000000
  --target-dir /data/raw/bookings_incremental/

# Mode 2: lastmodified β€” for tables with an update timestamp
sqoop import \
  --connect jdbc:oracle:thin:@//db-host:1521/ENTERPRISE \
  --table BOOKINGS \
  --incremental lastmodified \
  --check-column updated_at \     # timestamp column
  --last-value "2024-01-15 00:00:00" \
  --target-dir /data/raw/bookings_incremental/

# --split-by: control how data is split across mappers (affects parallelism)
sqoop import \
  --table BOOKINGS \
  --split-by booking_date \       # each mapper handles a date range
  --num-mappers 8
# ⚠️ Default: split by primary key (must be numeric!)
# ⚠️ If no primary key and no --split-by β†’ must use --num-mappers 1 (slow!)

Sqoop Interview Key Points

🧠 Memory Map
1. Sqoop uses MapReduce underneath (each mapper connects to DB, reads a range)
2. --num-mappers = number of DB connections simultaneously!
⚠️Too many mappers β†’ DB connection pool exhausted β†’ DB overload
Production recommendation: 4-8 mappers max (check with DBA)
3. Incremental import saves Sqoop job config in "metastore":
sqoop job --create daily_booking_import -- import ...
sqoop job --exec daily_booking_import
β†’ Saves last-value, auto-updates each run
4. Sqoop EXPORT (HDFS β†’ Oracle):
sqoop export --connect ... --table TARGET_TABLE --export-dir /data/output/
⚠️EXPORT is NOT atomic β€” if it fails halfway, partial data is in DB!
Solution: use staging table + DB transaction to swap atomically

SECTION 10: OOZIE β€” WORKFLOW SCHEDULER

🧠 OOZIE = Hadoop workflow scheduler
OOZIEHadoop workflow scheduler
Think: Apache Oozie is like Apache Airflow for Hadoop
Schedule chains of: MapReduce→Hive → Sqoop → Pig jobs
TWO JOB TYPES
1. WORKFLOW JOB:
A DAG of actions (nodes)
Actions: MapReduce, Hive, Sqoop, Pig, Shell, Java, Spark
Runs once (you submit it)
Has: start node β†’ action nodes β†’ decision nodes β†’ fork/join β†’ end node
2. COORDINATOR JOB:
Schedules Workflow jobs on:
a) TIME trigger: run every day at 8am
b) DATA trigger: run when this HDFS path has new data
"Coordinator" = orchestrator of workflows
More powerful than cron: waits for both time AND data availability
BUNDLE JOB
A collection of Coordinator jobs managed together
Like a "project" that contains multiple pipelines
xml
<!-- workflow.xml β€” simple Hive workflow -->
<workflow-app name="daily-booking-report" xmlns="uri:oozie:workflow:0.5">

    <start to="hive-action"/>

    <!-- Action 1: Run Hive query -->
    <action name="hive-action">
        <hive xmlns="uri:oozie:hive-action:0.5">
            <job-tracker>${jobTracker}</job-tracker>
            <name-node>${nameNode}</name-node>
            <script>/user/oozie/scripts/aggregate_bookings.hql</script>
            <param>booking_date=${booking_date}</param>
        </hive>
        <ok to="sqoop-export"/>
        <error to="fail"/>
    </action>

    <!-- Action 2: Export result to Oracle -->
    <action name="sqoop-export">
        <sqoop xmlns="uri:oozie:sqoop-action:0.4">
            <command>export --connect jdbc:oracle:... --table REPORT_TABLE ...</command>
        </sqoop>
        <ok to="end"/>
        <error to="fail"/>
    </action>

    <kill name="fail">
        <message>Workflow failed: ${wf:errorMessage(wf:lastErrorNode())}</message>
    </kill>

    <end name="end"/>
</workflow-app>

SECTION 11: ZOOKEEPER β€” DISTRIBUTED COORDINATION

🧠 ZOOKEEPER = Distributed coordination service
ZOOKEEPERDistributed coordination service
Think: ZooKeeper is like a "trusted referee" for distributed systems.
When nodes disagree (who is the master? is this node alive?),
ZooKeeper is the single source of truth.
WHAT ZOOKEEPER DOES IN HADOOP
1. NameNode HA:
Keeps track of which NameNode is Active
ZKFC (ZooKeeper Failover Controller) on each NameNode
If Active NN dies β†’ ZKFC detects β†’ ZK elects new Active
2. HBase:
HMaster election (Active/Standby)
Stores META table location (where is the region directory?)
RegionServer health monitoring
3. YARN ResourceManager HA:
Active/Standby RM election
Stores AM state for recovery after RM restart
ZooKeeper DATA MODEL:
Tree of "znodes" (like directories/files)
Ephemeral znodes: auto-deleted when creator disconnects
β†’ Used for leader election (NN creates /namenode/active as ephemeral znode)
→ If NN dies→ephemeral znode deleted → Standby sees znode gone → takes over!
Persistent znodes: stay until explicitly deleted
β†’ Used for configuration storage
ZooKeeper ENSEMBLE:
Always odd number of ZooKeeper servers (3, 5, 7)
Quorum needed: majority must be up (3-node β†’ need 2; 5-node β†’ need 3)
3-node ZK: can handle 1 failure
5-node ZK: can handle 2 failures
⚠️NEVER run 2 ZooKeeper nodes! (1 failure = no quorum = total outage)

SECTION 12: FLUME β€” LOG INGESTION

🧠 FLUME = Distributed, reliable log collection service
FLUMEDistributed, reliable log collection service
Use case: Stream web server access logs from hundreds of servers INTO HDFS in real-time
FLUME ARCHITECTURE
Source→Channel → Sink
↑ ↑ ↓
Events Buffer Output
SOURCE: Where data comes from
Exec source: tail -F /var/log/apache/access.log
Spooling directory: watches a folder for new files
Avro source: receives Avro-encoded events from other Flume agents
Kafka source: reads from Kafka topic
CHANNEL: Buffer between source and sink
Memory channel: events in RAM β†’ FAST but data loss on crash!
File channel: events on local disk β†’ DURABLE, survives restart
Kafka channel: uses Kafka as the buffer (most durable, 2023+)
⚑ INTERVIEW: "Memory channel = fast but not durable, File channel = durable"
SINK: Where data goes
HDFS sink: writes to HDFS (most common)
Kafka sink: forward to Kafka topic
Avro sink: forward to another Flume agent (fan-out)
Logger sink: just logs events (debugging)
HDFS SINK SETTINGS
hdfs.rollInterval = 3600 # create new HDFS file every 1 hour
hdfs.rollSize = 134217728 # roll file when it reaches 128 MB
hdfs.rollCount = 0 # don't roll by event count (0 = disabled)
hdfs.path = /user/logs/%Y/%m/%d/%H # time-based partitioning!

SECTION 13: DESIGN SCENARIO β€” End-to-End Travel Pipeline

"Design a Hadoop pipeline to process 100 million daily flight bookings"

🧠 Memory Map
INTERVIEWER: "Walk me through how you'd design the data pipeline."
YOUR ANSWER
INGESTION LAYER
Option A: Batch (daily) β€” Sqoop incremental import from Oracle booking DB
β†’ Run at 2am, import new bookings since last run
β†’ Write to HDFS: /data/raw/bookings/booking_date=YYYY-MM-DD/ (ORC format)
Option B: Real-time — Flume agents on web servers→Kafka → Spark Streaming
β†’ Near-real-time (minutes), for fraud detection use case
STORAGE
Raw (Bronze): HDFS, External Hive table, Avro or ORC format, partitioned by date
Processed (Silver): HDFS, ORC + Snappy, partitioned by booking_date + region
Aggregated (Gold): HDFS, ORC + ZLIB (more compressed for smaller aggregations)
PROCESSING
Hive + Tez for batch transformations
SET hive.execution.engine=tez;
SET hive.vectorized.execution.enabled=true;
Partition pruning for date-range queries
Map join for dimension tables (airports 10k rows, aircraft_types 500 rows)
SERVING
HBase: booking lookup service (real-time GET by booking_id)
Hive: ad-hoc analytics queries by data scientists
LLAP: BI dashboards (Tableau/PowerBI connecting via HiveServer2)
ORCHESTRATION
Oozie Coordinator: time trigger at 3am + data availability check
Workflow: Sqoop→Hive transformations → Hive aggregations → Sqoop export to Oracle
OPTIMIZATION APPLIED
βœ“ ORC format throughout Silver/Gold layers
βœ“ Partition by booking_date (pruning for date-range queries)
βœ“ Tez execution engine (not MapReduce)
βœ“ Vectorization enabled
βœ“ CBO with ANALYZE TABLE for optimal join plans
βœ“ Map join for small dimension tables (airports, aircraft)
βœ“ Sort buffer 512 MB (not default 100 MB)
βœ“ Compression: Snappy for hot data, ZLIB for cold archive

Integrated quick recall

Merged from HD_02_Quick_Recall.md; the legacy source remains unchanged.

Day 2: Hive + Ecosystem β€” Quick Recall Guide

⚑Must rememberπŸ”‘Key concept⚠️Common trap🧠Memory MapπŸ“One-liner

🧠 MASTER MEMORY MAP β€” Day 2

sql
HIVE ARCHITECTURE = "DMCTE"
    D β€” Driver (receives SQL, manages lifecycle)
    M β€” Metastore (schema + HDFS location β†’ MySQL backend!)
    C β€” Compiler (SQL β†’ query plan)
    T β€” Tez/MR engine (executes plan on YARN)
    E β€” Execution (submits to YARN, reads from HDFS)

HIVE OPTIMIZATION = "VECTOR-TOP":
    V β€” Vectorization (1024 rows at once: hive.vectorized.execution.enabled=true)
    E β€” Engine=Tez (hive.execution.engine=tez, not mr)
    C β€” CBO stats (ANALYZE TABLE + hive.cbo.enable=true)
    T β€” Tez DAG (can pipeline stages and avoid mandatory HDFS materialization between every stage)
    O β€” ORC format (columnar + predicate pushdown + ACID)
    R β€” REPARTITION/skew fix (hive.groupby.skewindata=true)

    T β€” Table map join (hive.auto.convert.join=true, small table β†’ broadcast)
    O β€” ORDER BY β†’ SORT BY (local sort, use instead of global sort)
    P β€” Partition pruning (filter on partition column, not derived expressions)

HIVE FILE FORMATS = "OPTA":
    O β€” ORC    (Hive-native, ACID, predicate pushdown β€” BEST FOR HIVE)
    P β€” Parquet (cross-tool: Spark+Impala+Hive β€” BEST FOR MULTI-TOOL)
    T β€” Text   (default row format; compressed input supported; best for landing/interchange)
    A β€” Avro   (schema evolution, Kafka/Sqoop landing β€” ROW-based)

INTERNAL vs EXTERNAL:
    Internal = Hive OWNS data β†’ DROP TABLE = data DELETED from HDFS
    External = Hive POINTS to data β†’ DROP TABLE = only metadata deleted, data SAFE
    ⚑ Rule: External for shared/raw data, Internal for Hive-only output

ECOSYSTEM = "SQOF-ZK":
    S β€” Sqoop (RDBMS ↔ HDFS transfer)
    Q β€” (Hive = SQL on HDFS)
    O β€” Oozie (workflow + coordinator jobs)
    F β€” Flume (log streaming β†’ HDFS)
    ZK β€” ZooKeeper (distributed coordination, leader election)

SECTION 1: HIVE β€” DIRECT QUESTIONS

⚑ Q1What is the Hive Metastore?

MySQL/PostgreSQL database that stores schema metadata: table names, column types, HDFS paths, partition information, file formats. Hive queries it to know WHERE data lives in HDFS. If Metastore goes down β†’ ALL Hive queries fail.

Q2Internal vs External table β€” key difference?

Internal: Hive owns data. DROP TABLE = delete metadata + delete HDFS data. External: Hive points to data. DROP TABLE = delete metadata only, HDFS data untouched.

⚑ Q3When to use External table?

Always for: raw/Bronze landing tables, shared data (Spark also reads it), Sqoop-ingested data, data you can't afford to accidentally delete.

Q4What is a Hive partition?

A subdirectory in HDFS organized by a column value. booking_date=2024-01-15/ is one partition. Partition pruning skips unrelated directories β†’ reads only what's needed.

⚠️ Q5Common partition column trap?

WHERE YEAR(booking_date) = 2024 β†’ NO partition pruning (function applied to column). Fix: WHERE booking_date BETWEEN '2024-01-01' AND '2024-12-31' β€” Hive can prune date range.

Q6Static vs Dynamic partitioning?

Static: you specify partition value in INSERT (PARTITION (date='2024-01-15')). Dynamic: Hive reads partition value from the data itself (PARTITION (date), last column in SELECT). Dynamic can create many files β†’ enable merge settings.

SECTION 2: HIVE SCENARIOS

⚑ Q7 SCENARIO: Sqoop wrote new data to HDFS but Hive shows 0 rows. Fix?

Metastore doesn't know about the new partition. Fix: MSCK REPAIR TABLE bookings; β€” scans HDFS, adds missing partitions to Metastore. Or faster: ALTER TABLE bookings ADD PARTITION (booking_date='2024-03-01') LOCATION '...'

⚠️ Q8 SCENARIO: Someone ran hdfs dfs -rm -r on a Hive partition. Now what?

Check Trash first: hdfs dfs -ls /user/username/.Trash/Current/ β†’ restore if found. If no trash: restore from backup. If no backup: ALTER TABLE bookings DROP PARTITION (booking_date='...') to remove stale metadata. Prevent with snapshots.

Q9 SCENARIO: Hive query runs for hours. Top 5 things to check?

    1. SET hive.execution.engine β†’ should be tez, not mr
    2. 2SET hive.vectorized.execution.enabled=true (ORC only)
    3. 3Check if partition pruning works (WHERE on partition column directly)
    4. 4Any shuffle joins that could be map joins? (small tables < 25 MB)
    5. 5Data skew? SET hive.groupby.skewindata=true

SECTION 3: HIVE OPTIMIZATIONS β€” FLASH CARDS

⚑ Q10What does hive.execution.engine=tez do?
βœ… Pro Tip
Uses Apache Tez instead of MapReduce. Tez represents work as a DAG and can avoid mandatory HDFS materialization between every stage, though it may still spill. Benchmark the resulting plan rather than promising a fixed multiplier.
⚑ Q11What does vectorization do?

SET hive.vectorized.execution.enabled=true enables batch-oriented operators for supported plans and formats. Batch size, format support, and gains are version- and workload-dependent; inspect the plan and benchmark.

Q12What is a Map Join and when does Hive use it?

Load small table into every mapper's RAM β†’ join locally without shuffle. Hive auto-decides: hive.auto.convert.join=true with threshold hive.mapjoin.smalltable.filesize=25 MB. Force with /*+ MAPJOIN(table) */ hint.

⚠️ Q13ORDER BY vs SORT BY β€” when to use each?
βœ… Pro Tip
ORDER BY: global sort β†’ all data β†’ ONE reducer (slow for billions!). SORT BY: each reducer sorts its own output (local sort, faster). Use SORT BY + multiple reducers when global order not required.
Q14What is MSCK REPAIR TABLE?

MetaStore Check β€” scans HDFS for new partition directories and adds them to the Hive Metastore. Needed when files are added directly to HDFS without going through Hive INSERT. ⚠️ Slow on tables with 10,000+ partitions.

⚑ Q15What is ORC predicate pushdown?

ORC stores min/max statistics per column per stripe. When you do WHERE amount > 1000, Hive reads only stripes where max(amount) > 1000. Skip stripes without touching them β†’ can skip 90%+ of data!

Q16What is hive.groupby.skewindata=true?

Two-phase aggregation for skewed GROUP BY. Phase 1: randomly distribute keys β†’ partial aggregation in parallel. Phase 2: final aggregation by real key. Prevents one reducer getting all "US" country records.

SECTION 4: HBASE β€” FLASH CARDS

⚑ Q17What is HBase and when do you use it?

NoSQL column-family database on top of HDFS. Use for low-latency random row reads/writes when row keys, regions, caching, and capacity are engineered for the workload. Use an analytic engine rather than HBase for broad batch scans.

Q18What is a Row Key in HBase?

Primary sort key for all HBase data. All access is BY row key. Lexicographically sorted. Design it based on your access pattern (how will you look up rows?).

⚠️ Q19Why is timestamp as row key bad?

Monotonically increasing timestamps β†’ all new writes go to the LAST region (last RegionServer) β†’ write hotspot! All 1000 writes/second hit one machine. Fix: salt prefix (hash(id) % 10) or reverse timestamp (Long.MAX_VALUE - timestamp).

Q20HBase write path?
    1. WAL (Write-Ahead Log on HDFS) for durability
    2. 2MemStore (RAM) for fast writes
    3. 3When MemStore full (128 MB) β†’ flush to HFile on HDFS
    4. 4Background: compact HFiles to reduce read overhead.

SECTION 5: SQOOP β€” FLASH CARDS

⚑ Q21What is Sqoop incremental import?

Import only NEW rows since last run. Mode append: only rows where check-column > last-value. Mode lastmodified: rows updated after last-value timestamp. Much faster than full daily import!

Q22What does --num-mappers do in Sqoop?

Number of parallel DB connections to use. Each mapper reads a range of rows. ⚠️ Too high β†’ DB connection pool exhausted. Typical production: 4-8 mappers.

⚠️ Q23Sqoop export data safety issue?

Sqoop EXPORT (HDFS β†’ DB) is NOT atomic. If it fails halfway β†’ partial data in DB. Solution: export to staging table β†’ run DB transaction to swap (DELETE + INSERT in one transaction).

SECTION 6: OOZIE β€” FLASH CARDS

Q24Oozie Workflow vs Coordinator job?

Workflow: a DAG of actions (Hive→Sqoop→MapReduce), runs once when submitted. Coordinator: schedules Workflows based on TIME trigger (every 8am) or DATA trigger (when HDFS path has new data). Use Coordinator for production pipelines.

Q25What's the advantage of Oozie Coordinator data trigger?

Job starts only when upstream data arrives in HDFS β€” not just at a scheduled time. So if upstream job is delayed 2 hours, Coordinator waits β†’ no failed run due to missing data. Airflow equivalent: ExternalTaskSensor.

SECTION 7: ZOOKEEPER + FLUME β€” FLASH CARDS

⚑ Q26What does ZooKeeper do in Hadoop?

Distributed coordination: NameNode HA leader election, HMaster election for HBase, RegionServer health monitoring, YARN ResourceManager HA. Uses ephemeral znodes (auto-deleted on disconnect) for leader tracking.

Q27Why must ZooKeeper have an odd number of nodes?

Quorum = majority needed for decisions (3 β†’ need 2, 5 β†’ need 3). Even number: possible tie β†’ no majority β†’ ZK stuck. Minimum 3 nodes. ⚠️ Never run 2-node ZK!

Q28Flume Memory Channel vs File Channel?

Memory channel is fast but can lose buffered events if the agent crashes. File channel survives restart at higher I/O cost. For production, choose a durable channel or broker when the delivery requirement demands it, and test recovery/back-pressure behavior.

🧠 FINAL REVISION β€” Day 2 Summary Card

sql
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                  DAY 2: HIVE + ECOSYSTEM                          β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚                                                                  β”‚
β”‚  HIVE ARCHITECTURE = "DMCTE":                                    β”‚
β”‚  Driver β†’ Metastore β†’ Compiler β†’ Tez Engine β†’ Execution          β”‚
β”‚  Metastore backend = MySQL (NOT HDFS) β€” it goes down β†’ all fail  β”‚
β”‚                                                                  β”‚
β”‚  INTERNAL vs EXTERNAL:                                           β”‚
β”‚  Internal: DROP TABLE = metadata + HDFS data deleted!            β”‚
β”‚  External: DROP TABLE = only metadata, HDFS data SAFE            β”‚
β”‚  Use External for: raw data, shared data, Sqoop imports          β”‚
β”‚                                                                  β”‚
β”‚  PARTITIONING:                                                   β”‚
β”‚  Static: PARTITION (date='2024-01-15') β€” manual                  β”‚
β”‚  Dynamic: SET hive.exec.dynamic.partition.mode=nonstrict         β”‚
β”‚  MSCK REPAIR TABLE = add missing partitions to Metastore         β”‚
β”‚  Partition pruning: filter DIRECTLY on partition column!         β”‚
β”‚                                                                  β”‚
β”‚  HIVE OPTIMIZATION = "VECTOR-TOP":                               β”‚
β”‚  1. Engine=Tez (5-10x vs MapReduce)                              β”‚
β”‚  2. Vectorization (1024 rows batch, ORC only)                    β”‚
β”‚  3. CBO + ANALYZE TABLE (stats for optimal join plan)            β”‚
β”‚  4. Map Join (small table < 25 MB β†’ broadcast, no shuffle)        β”‚
β”‚  5. ORC + predicate pushdown (skip stripes by min/max)           β”‚
β”‚  6. skewindata=true (2-phase GROUP BY for hot keys)              β”‚
β”‚  7. SORT BY not ORDER BY (unless global sort needed)             β”‚
β”‚                                                                  β”‚
β”‚  FILE FORMATS = "OPTA":                                          β”‚
β”‚  ORC: Hive-native, ACID, predicate pushdown                      β”‚
β”‚  Parquet: cross-tool (Spark+Impala+Hive)                         β”‚
β”‚  Text: landing/interchange; compressed input supported           β”‚
β”‚  Avro: schema evolution, Kafka/Sqoop landing                     β”‚
β”‚                                                                  β”‚
β”‚  HBASE:                                                          β”‚
β”‚  Random read/write on HDFS (what Hive can't do!)                 β”‚
β”‚  Row key: NEVER monotonic (hotspot!), use salt/reverse timestamp β”‚
β”‚  Write path: WAL β†’ MemStore β†’ HFile (flush on 128 MB)            β”‚
β”‚                                                                  β”‚
β”‚  SQOOP:                                                          β”‚
β”‚  Incremental import: --incremental append/lastmodified           β”‚
β”‚  --split-by: parallelize by column (default: primary key)        β”‚
β”‚  Export: NOT atomic β†’ use staging table!                         β”‚
β”‚                                                                  β”‚
β”‚  OOZIE:                                                          β”‚
β”‚  Workflow: DAG of actions (run once)                             β”‚
β”‚  Coordinator: time + data trigger (production pipelines)         β”‚
β”‚                                                                  β”‚
β”‚  ZOOKEEPER:                                                      β”‚
β”‚  Leader election for NameNode/HMaster/YARN RM                    β”‚
β”‚  Always odd nodes (3/5/7) for quorum                             β”‚
β”‚  Ephemeral znodes = auto-deleted on crash = leader detection     β”‚
β”‚                                                                  β”‚
β”‚  TOP 5 THINGS TO SAY IN INTERVIEW:                               β”‚
β”‚  1. "External tables for all raw data β€” DROP TABLE is safe"      β”‚
β”‚  2. "MSCK REPAIR TABLE when Sqoop adds files outside Hive"       β”‚
β”‚  3. "Tez + vectorization + ORC can cut I/O and CPU; benchmark"  β”‚
β”‚  4. "HBase row key must not be monotonic β€” causes hotspot!"      β”‚
β”‚  5. "Oozie Coordinator = time + data trigger (smart scheduling)" β”‚
β”‚                                                                  β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
Advanced

Performance, Security, and Migration

#

Answer-first recall layer

Recall: Kerberos, Ranger, and Knox

Answer First: Kerberos proves identity, Ranger evaluates authorization policies and audits access, and Knox fronts cluster services at the perimeter; production security needs all three layers plus encryption and key management.

Memory Map: authenticate -> authorize/audit -> gateway -> encrypt.

Recall: keytabs and ticket renewal

Answer First: A keytab stores long-lived principal keys for non-interactive login; protect it like a password and renew or reacquire tickets before expiry for long-running services.

Memory Map: keytab -> kinit -> ticket cache -> renewal -> service request.

Recall: YARN and JVM tuning

Answer First: Size containers from measured live heap, native/off-heap overhead, GC, and concurrency; align map/reduce memory with Java opts and avoid both wasteful oversized containers and kill-prone undersizing.

Memory Map: node capacity -> container memory/vcores -> JVM heap -> overhead -> concurrency.

Recall: data skew

Answer First: Prove skew from partition and task distributions, then choose a key-aware remedy such as salting, pre-aggregation, a map-side join, custom partitioning, or splitting hot keys.

Memory Map: metrics -> hot key -> partition imbalance -> targeted redistribution -> validate tails.

Recall: Hadoop distributions

Answer First: Apache Hadoop supplies upstream components, while historical HDP and CDH distributions packaged management, security, and support; CDP is Cloudera's later hybrid platform, so compare exact deployed versions and services.

Memory Map: upstream components -> distribution packaging -> management/security -> support lifecycle.

Recall: cloud migration

Answer First: Choose lift-and-shift, replatform, or refactor per workload; inventory data and dependencies, validate semantics and performance in parallel, reconcile outputs, then cut over with rollback.

Memory Map: discover -> classify -> transfer/convert -> dual run -> reconcile -> cut over.

Recall: erasure coding

Answer First: HDFS erasure coding lowers cold-data storage overhead by storing data and parity cells instead of three full replicas, trading additional CPU/network work and weaker small-file economics for capacity savings.

Memory Map: policy -> data cells + parity cells -> reconstruct on failure -> storage/compute trade-off.

Recall: capacity planning

Answer First: Plan usable capacity from ingest, retention, replication or EC overhead, temporary/shuffle headroom, growth, and failure reserve; separately model NameNode heap from file and block counts.

Memory Map: daily ingest x retention x protection + workspace + growth + failure reserve.

Canonical source guide

Merged from HD_03_Performance_Security_Migration.md; the legacy source remains unchanged.

Day 3: Performance, Security + Cloud Migration β€” Deep Interview Guide

🧠 MASTER MEMORY MAP β€” Day 3

🧠 HADOOP SECURITY = "KRK" (Kerberos β†’ Ranger β†’ Knox):
HADOOP SECURITY"KRK" (Kerberos β†’ Ranger β†’ Knox):
KKerberos: AUTHENTICATION (who are you?)
RRanger: AUTHORIZATION (what can you do?)
KKnox: GATEWAY (how do you get in? SSL + API proxy)
PERFORMANCE TUNING LAYERS"JYH" (JVM β†’ YARN β†’ Hadoop):
JJVM tuning (heap sizes, GC, JVM reuse)
YYARN tuning (container sizes, scheduler config)
HHadoop-level (block size, replication, compression)
CLOUD MIGRATION PATTERNS"LRR" (Lift β†’ Replatform β†’ Refactor):
LLift-and-Shift: HDFS β†’ S3/ADLS (same MapReduce/Hive, just different storage)
RReplatform: MapReduce β†’ Spark (same data in cloud, better processing)
RRefactor: Hive β†’ Delta Lake / Snowflake (rebuild for cloud-native)
HADOOP vs SPARK = "DISK vs RAM":
Hadoop MapReduce: disk-based, fault-tolerant, Java-only
Spark: can retain reused data in memory; Python/SQL/Scala, streaming + batch
When to still use Hadoop: legacy code, can't migrate budget, HBase is on-prem

SECTION 1: HADOOP SECURITY

Layer 1: Kerberos β€” Authentication

KERBEROSMIT protocol for distributed authentication
WITHOUT KERBEROS (plain Hadoop)
User: "I am root"
Hadoop: "OK, here's all the data" ← takes your word for it!
Security: ZERO
WITH KERBEROS
User: must have valid Kerberos ticket (cryptographically signed by KDC)
Hadoop: verifies ticket with KDC before granting access
Can't fake identity→proper enterprise security
πŸ“‹ Overview
HOW KERBEROS WORKS (simplified)
KDCKey Distribution Center (the central auth server)
Authentication Service (AS): verifies your password
Ticket Granting Service (TGS): gives service-specific tickets
STEP 1: User kinit (login):
$ kinit krishna@ENTERPRISE.COM
Enter password→KDC verifies → gives Ticket-Granting Ticket (TGT)
TGT stored locally (~8 hour validity)
STEP 2: Access Hadoop service:
User app: "I want to access HDFS, here's my TGT"
KDC/TGS: verifies TGT→issues Service Ticket for HDFS (specific to HDFS daemon)
User app presents Service Ticket to HDFS NameNode
NameNode: "This ticket is valid"β†’access granted
STEP 3: Each service has its own Kerberos principal:
hdfs/namenode-host@ENTERPRISE.COM (HDFS NameNode)
yarn/rm-host@ENTERPRISE.COM (YARN ResourceManager)
hive/hiveserver2-host@ENTERPRISE.COM (HiveServer2)
KEY TERMS
Principal: identity in Kerberos realm (user or service)
keytab: file with pre-stored credentials (for automated services like Oozie)
β†’ No password prompt, used in cron jobs and service accounts
realm: Kerberos domain (e.g., ENTERPRISE.COM)
kinit: manual login to get TGT (for humans)
klist: show current Kerberos tickets
kdestroy: destroy tickets (logout)
bash
# Production Hadoop with Kerberos:
kinit -kt /etc/security/keytabs/hive.service.keytab hive/hiveserver2@ENTERPRISE.COM
# Login using keytab file (automated, no password prompt)
# Used in Oozie jobs, cron jobs, service accounts

klist
# Credentials cache: FILE:/tmp/krb5cc_1000
# Default principal: hive/hiveserver2@ENTERPRISE.COM
# Expires: Thu Jan 16 08:00:00 2025

# Renew ticket before it expires (important for long-running jobs!):
kinit -R
# ⚠️ If ticket expires mid-job β†’ job fails with "Authentication failure"
# Solution: use long-lived keytabs + auto-renewal in production

Layer 2: Apache Ranger β€” Authorization

🧠 RANGER = Role-Based Access Control for ALL Hadoop services
RANGERRole-Based Access Control for ALL Hadoop services
Without Ranger: access control via HDFS POSIX permissions only
β†’ hdfs dfs -chmod 750 /data/pii/ (coarse-grained, file-level)
β†’ Can't say "marketing can read column1 but not SSN column"
With Ranger: fine-grained policies for EVERY service:
β†’ Hive: table-level, column-level, row-level masking
β†’ HDFS: path-level access
β†’ HBase: table + column family level
β†’ Kafka: topic-level
β†’ YARN: queue-level
All in ONE central UI!
sql
RANGER POLICY EXAMPLES:

Policy 1: Hive table access
  Name: "Marketing team can read bookings"
  Resource: database=bookings_db, table=bookings, columns=*
  Permissions: user=marketing_role β†’ SELECT
  Exclude: columns=credit_card_number (masked!)

Policy 2: Column masking (PII protection)
  Name: "Mask SSN for non-PII team"
  Resource: database=bookings_db, table=customers, column=ssn
  Masking: MASK (show only last 4 digits: ***-**-1234)
  Applied to: all users EXCEPT pii_approved_role

Policy 3: Row-level filter
  Name: "Regional teams see only their region"
  Resource: database=bookings_db, table=bookings
  Row filter: region = current_user_region()
  Applied to: regional_analyst role

RANGER AUDIT:
  Every access (success AND failure) is logged
  "Who accessed what, when, from where"
  Critical for compliance (GDPR, PCI-DSS, SOX)
  Stored in Solr or HDFS for long-term retention

Layer 3: Apache Knox β€” Gateway

🧠 KNOX = API Gateway for Hadoop cluster
KNOXAPI Gateway for Hadoop cluster
Problems Knox solves:
1. Users need to access multiple services (HiveServer2, HDFS, YARN UI, Oozie)
Each service has its own host:port→complex firewall rules
2. No SSL on internal Hadoop services (encrypted in transit needed for compliance)
3. Direct service access exposes internal cluster topology
Knox solution:
Single entry point: https://knox-gateway:8443/gateway/
β†’ Users never connect directly to internal services
β†’ Knox proxies requests to appropriate backend service
β†’ SSL termination at Knox (external traffic encrypted)
β†’ Authentication at Knox (SSO with LDAP/Kerberos)
External: User→HTTPS → Knox:8443
Internal: Knox→HTTP → HiveServer2, HDFS, YARN UI, Oozie
KNOX PATHS
/gateway/default/webhdfs/β†’HDFS WebHDFS API
/gateway/default/hive/β†’HiveServer2
/gateway/default/yarn/β†’YARN ResourceManager UI
/gateway/default/oozie/β†’Oozie API

SECTION 2: PERFORMANCE TUNING

Level 1: JVM Tuning

xml
<!-- Tune NameNode JVM heap for the live namespace and block maps held in RAM. -->
export HADOOP_NAMENODE_OPTS="-Xmx16g -Xms16g -XX:+UseG1GC"
<!-- -Xmx16g: max heap 16 GB -->
<!-- -Xms16g: initial heap = max heap (prevents resize pauses) -->
<!-- -XX:+UseG1GC: G1 garbage collector (low-pause, good for large heaps) -->
<!-- Default: only 1 GB β†’ too small for clusters with >10 million files! -->

<!-- Rule for NameNode heap sizing: -->
<!-- 1 GB per 1 million files/blocks (rough estimate) -->
<!-- 10M files β†’ 10 GB NameNode heap minimum -->
<!-- 100M files β†’ 100 GB NameNode heap (need large server!) -->

<!-- DataNode JVM: less critical (doesn't keep metadata) -->
export HADOOP_DATANODE_OPTS="-Xmx4g -XX:+UseG1GC"

<!-- YARN NodeManager JVM: -->
export YARN_NODEMANAGER_OPTS="-Xmx4g -XX:+UseG1GC"
GC PAUSES β€” THE SILENT KILLER:
JVM Garbage Collection = JVM pauses ALL threads to reclaim memory
On NameNode: GC pause = HDFS appears DOWN during pause (RPCs timeout!)
On DataNode: GC pause = heartbeats delayed→NN marks DN as dead!
Fix:
1. Use G1GC (XX:+UseG1GC) β€” concurrent collector, shorter pauses
2. Set -Xms = -Xmx (avoid heap resizing GC)
3. Don't make heap too large β€” longer full GC if it happens
NameNode: max ~32 GB is practical; larger = painful GC pauses
Signs of GC problems: "Long GC pause" in logs, DataNodes showing as dead
Check: hdfs dfsadmin -report | grep "Dead datanodes"

Level 2: YARN Memory Tuning (Full Reference)

xml
<!-- yarn-site.xml β€” Complete memory configuration -->

<!-- Node-level memory available to YARN: -->
<property>
  <name>yarn.nodemanager.resource.memory-mb</name>
  <value>49152</value>   <!-- 48 GB on a 64 GB server -->
  <!-- Reserve: 8 GB for OS + 8 GB for other services (HBase, DN, NM JVMs) -->
</property>

<!-- Node-level CPU vcores for YARN: -->
<property>
  <name>yarn.nodemanager.resource.cpu-vcores</name>
  <value>16</value>   <!-- All cores on a 16-core server -->
</property>

<!-- Scheduler min/max container sizes: -->
<property>
  <name>yarn.scheduler.minimum-allocation-mb</name>
  <value>1024</value>   <!-- No container gets < 1 GB -->
</property>
<property>
  <name>yarn.scheduler.maximum-allocation-mb</name>
  <value>16384</value>   <!-- No container gets > 16 GB -->
</property>

<!-- Memory increment: allocations happen in multiples of this: -->
<property>
  <name>yarn.scheduler.increment-allocation-mb</name>
  <value>512</value>
</property>
🧠 Memory Map
MEMORY CALCULATION EXAMPLE β€” 10 node cluster, 64 GB each:
PER NODE
Total RAM: 64 GB
OS overhead: -4 GB
HDFS DataNode: -2 GB (hdfs heap)
YARN NodeManager: -2 GB (nm heap)
Available for YARN containers: 56 GB→set to 49152 MB (leave buffer)
CONTAINER SIZING
Mapper: 2048 MB (map container) β†’ Java heap: 1638 MB (80%)
Reducer: 4096 MB→Java heap: 3276 MB
Containers per node: 49152 / 2048 = 24 mappers OR 12 reducers
TOTAL CLUSTER
10 nodes Γ— 24 containers = 240 concurrent mapper slots
10 nodes Γ— 12 containers = 120 concurrent reducer slots

Level 3: Hadoop Configuration Performance Settings

xml
<!-- hdfs-site.xml performance settings -->

<!-- Block size: increase for large sequential files -->
<property>
  <name>dfs.blocksize</name>
  <value>268435456</value>   <!-- 256 MB for large files (default: 128 MB) -->
</property>

<!-- DataNode transfer thread pool (how many concurrent block transfers): -->
<property>
  <name>dfs.datanode.max.transfer.threads</name>
  <value>4096</value>   <!-- Default: 4096, can increase for high-throughput nodes -->
</property>

<!-- NameNode handler count (parallel RPC threads for client requests): -->
<property>
  <name>dfs.namenode.handler.count</name>
  <value>100</value>
  <!-- Default: 10 β†’ way too small for large clusters! -->
  <!-- Rule: 20 * log2(cluster_size) -->
  <!-- 100 nodes β†’ 20 * log2(100) = 20 * 6.6 = 132 β†’ set to 100-150 -->
</property>

<!-- Short-circuit reads: client reads directly from local DataNode (no network!) -->
<property>
  <name>dfs.client.read.shortcircuit</name>
  <value>true</value>   <!-- If client is on same node as DataNode β†’ read locally -->
</property>
xml
<!-- mapred-site.xml performance settings β€” FULL REFERENCE -->

<!-- MAP task memory -->
<property>
  <name>mapreduce.map.memory.mb</name>
  <value>2048</value>
</property>
<property>
  <name>mapreduce.map.java.opts</name>
  <value>-Xmx1638m -XX:+UseG1GC</value>   <!-- 80% of container + G1GC -->
</property>

<!-- REDUCE task memory -->
<property>
  <name>mapreduce.reduce.memory.mb</name>
  <value>4096</value>
</property>
<property>
  <name>mapreduce.reduce.java.opts</name>
  <value>-Xmx3276m -XX:+UseG1GC</value>

<!-- Sort buffer: MOST IMPORTANT for shuffle performance -->
</property>
<property>
  <name>mapreduce.task.io.sort.mb</name>
  <value>512</value>   <!-- Default: 100 MB β†’ increase to 512 MB! -->
</property>

<!-- Sort spill threshold: spill to disk when X% of sort buffer used -->
<property>
  <name>mapreduce.map.sort.spill.percent</name>
  <value>0.80</value>
</property>

<!-- Parallel copies during shuffle (how many parallel transfers from mappers): -->
<property>
  <name>mapreduce.reduce.shuffle.parallelcopies</name>
  <value>50</value>   <!-- Default: 5 β†’ very low! Increase for faster shuffle -->
</property>

<!-- In-memory merge threshold (before writing merged spills to disk): -->
<property>
  <name>mapreduce.reduce.shuffle.input.buffer.percent</name>
  <value>0.70</value>   <!-- 70% of reducer heap used for in-memory shuffled data -->
</property>

<!-- Output compression -->
<property>
  <name>mapreduce.map.output.compress</name>
  <value>true</value>
</property>
<property>
  <name>mapreduce.map.output.compress.codec</name>
  <value>org.apache.hadoop.io.compress.SnappyCodec</value>
</property>

<!-- JVM reuse for jobs with many small tasks: -->
<property>
  <name>mapreduce.job.jvm.numtasks</name>
  <value>10</value>   <!-- Reuse same JVM for 10 tasks before restart -->
</property>

<!-- Number of parallel reducers: -->
<property>
  <name>mapreduce.job.reduces</name>
  <value>10</value>   <!-- Default: 1 β€” always set this based on data volume! -->
</property>

Level 4: Hive Performance Settings (Full Reference)

sql
-- HIVE PERFORMANCE SETTINGS β€” run at start of session or in hive-site.xml

-- MUST-SET EVERY TIME:
SET hive.execution.engine=tez;                        -- NOT mr!
SET hive.vectorized.execution.enabled=true;           -- batch row processing
SET hive.vectorized.execution.reduce.enabled=true;
SET hive.cbo.enable=true;                             -- Cost-Based Optimizer
SET hive.compute.query.using.stats=true;
SET hive.stats.fetch.column.stats=true;

-- JOIN OPTIMIZATION:
SET hive.auto.convert.join=true;                      -- auto map join for small tables
SET hive.mapjoin.smalltable.filesize=25000000;        -- 25 MB threshold
SET hive.auto.convert.join.noconditionaltask=true;
SET hive.auto.convert.join.noconditionaltask.size=20971520;  -- 20 MB

-- SKEW HANDLING:
SET hive.groupby.skewindata=true;                     -- 2-phase GROUP BY
SET hive.optimize.skewjoin=true;
SET hive.skewjoin.key=100000;

-- DYNAMIC PARTITIONING:
SET hive.exec.dynamic.partition=true;
SET hive.exec.dynamic.partition.mode=nonstrict;
SET hive.exec.max.dynamic.partitions=2000;
SET hive.exec.max.dynamic.partitions.pernode=500;

-- SMALL FILE MERGING (prevents small files after INSERT):
SET hive.merge.mapfiles=true;
SET hive.merge.mapredfiles=true;
SET hive.merge.smallfiles.avgsize=134217728;          -- target 128 MB
SET hive.merge.size.per.task=268435456;               -- max 256 MB per output file

-- PARALLELISM:
SET hive.exec.parallel=true;                          -- run independent stages in parallel
SET hive.exec.parallel.thread.number=8;               -- max parallel threads

-- LLAP (if available):
SET hive.llap.execution.mode=auto;

Level 5: HDFS Balancer Tuning

bash
# HDFS Balancer: rebalance blocks across DataNodes
# When to run:
#   1. After adding new DataNodes (new nodes start empty!)
#   2. After replacing failed DataNodes
#   3. When some DataNodes are much more full than others

# Run balancer with specific bandwidth limit (don't saturate network):
hdfs balancer -threshold 10 -bandwidth 100m
# -threshold 10: a node is "balanced" if within 10% of average utilization
# -bandwidth 100m: use max 100 MB/s for rebalancing (don't flood production network)
# Without bandwidth limit: balancer uses ALL available bandwidth β†’ impacts jobs!

# Check balance:
hdfs dfsadmin -report
# Look for: "DFS Used%" column across DataNodes
# If one node is at 90% and another at 20% β†’ run balancer

# Intra-DataNode balancer (Hadoop 3 β€” balance disks within one DataNode):
hdfs diskbalancer -plan datanode-hostname
hdfs diskbalancer -execute plan.json
# Useful when one disk on a DataNode is much fuller than others

SECTION 3: DATA SKEW IN HADOOP β€” COMPLETE GUIDE

sql
DATA SKEW = uneven data distribution across nodes/reducers

SYMPTOMS:
  - MapReduce: 99 reducers done, 1 reducer running for hours
  - Hive: GROUP BY query takes much longer than expected
  - YARN: one container using 10x memory of others

ROOT CAUSES:
  - Hot keys: "US" has 10M rows, "Fiji" has 100 rows β†’ one reducer handles all US
  - Non-uniform partitioning: HashPartitioner with non-uniform key distribution
  - NULL values: all NULL keys go to same reducer by default

SOLUTIONS BY TYPE:

1. MAPREDUCE SKEW β†’ Custom Partitioner + Salting
   Hot key "US" β†’ spread as "US_0", "US_1", ..., "US_99" across 100 reducers
   Then second step: combine partial aggregations back

2. HIVE GROUP BY SKEW β†’ skewindata
   SET hive.groupby.skewindata=true;
   Hive automatically uses 2-phase aggregation

3. HIVE JOIN SKEW β†’ skewjoin
   SET hive.optimize.skewjoin=true;
   SET hive.skewjoin.key=100000;
   Hive splits join: hot keys via separate broadcast, rest via shuffle join

4. NULL KEY SKEW β†’ handle NULLs explicitly
   -- Instead of: SELECT a.*, b.* FROM a JOIN b ON a.key = b.key
   -- (all NULLs in a.key go to one reducer!)
   -- Use:
   SELECT a.*, b.*
   FROM a JOIN b ON COALESCE(a.key, CONCAT('null_', RAND())) = b.key;
   -- Random null values β†’ distributed across reducers

5. SPARK (if migrated): repartition(), broadcast(), salting still apply

SECTION 4: CLOUDERA CDP vs HDP vs APACHE HADOOP

APACHE HADOOP (bare): Open source, no support, you manage everything
Use for: learning, custom builds, research
HORTONWORKS HDP (Hadoop Data Platform)
Was THE enterprise Hadoop distribution (2011-2019)
Merged with Cloudera in 2019
Legacy: many enterprises still run HDP 2.x or 3.x
Tools included: Ambari (management UI), Tez, ORC, Ranger, Atlas, Knox
EOL: HDP 2.x is end-of-life β†’ companies migrating to CDP
CLOUDERA CDP (Cloudera Data Platform)
Combined Cloudera + Hortonworks (2019 merger)
On-premises: CDP Private Cloud
Cloud: CDP Public Cloud (AWS, Azure, GCP)
Management: Cloudera Manager (better than Ambari for large clusters)
Includes: CDW (Cloudera Data Warehouse), CML (ML), CDE (Data Engineering)
Key differentiator: SDX (Shared Data Experience) β€” unified security across all services
Atlas (data lineage + governance) is deeply integrated
INTERVIEW POSITIONING
"I've worked with HDP in production β€” Ambari for management, Ranger for security,
Atlas for lineage. With the Cloudera-Hortonworks merger, companies moving to CDP.
I understand the migration path: HDP Ambari→Cloudera Manager, same security model."

SECTION 5: CLOUD MIGRATION PATTERNS

Pattern 1: Lift-and-Shift (HDFS β†’ Cloud Storage)

bash
WHAT: Move data from HDFS to cloud object storage (ADLS Gen2, S3, GCS)
      Keep same processing (Hive/MapReduce) but on cloud compute

HOW:
  Tool: DistCp (Distributed Copy β€” uses MapReduce to copy files in parallel)

hdfs distcp \
  hdfs://namenode:8020/user/hive/warehouse/ \
  wasbs://container@storageaccount.blob.core.windows.net/hive/warehouse/
  # wasbs = Windows Azure Storage Blob Secure

  Or to S3:
  hdfs distcp hdfs://namenode:8020/data/ s3a://my-bucket/data/

  For large datasets β€” incremental copy:
  hdfs distcp -update -skipcrccheck \
    hdfs://namenode/data/ \
    s3a://bucket/data/
  # -update: skip files already copied (incremental)
  # -skipcrccheck: S3 CRC differs from HDFS CRC (avoid false mismatches)

PROS:
  βœ“ Minimal code changes (Hive still works with ADLS/S3 as backend)
  βœ“ Low risk, fast migration
  βœ“ Can keep Hive metastore pointing to new paths

CONS:
  βœ— Still paying for compute clusters (no serverless)
  βœ— MapReduce still disk-based and slow
  βœ— Misses opportunity to modernize processing

WHEN TO CHOOSE:
  β†’ Budget limited, need quick win
  β†’ Large Hadoop investment, can't rewrite apps
  β†’ As Phase 1 of a larger migration

Pattern 2: Replatform (MapReduce β†’ Spark)

sql
WHAT: Keep data in cloud storage, replace MapReduce processing with Spark
      Data: HDFS β†’ S3/ADLS
      Processing: MapReduce Java β†’ Spark (Python/Scala)

CHANGES:
  Old: MapReduce Job β†’ YARN β†’ HDFS
  New: Spark Job β†’ Databricks/EMR/HDInsight β†’ S3/ADLS

MIGRATION STEPS:
  1. Copy HDFS data to S3/ADLS (DistCp)
  2. Rewrite MapReduce jobs as Spark jobs (logic same, API different)
  3. Migrate Hive tables: update LOCATION to cloud paths
  4. Migrate Oozie workflows to Airflow/Databricks Workflows
  5. Migrate Sqoop imports to ADF/Glue/Spark JDBC

HIVE β†’ SPARK SQL MIGRATION:
  Most Hive SQL is compatible with Spark SQL!
  -- Old Hive:
  SET hive.execution.engine=tez;
  INSERT INTO bookings_silver PARTITION (booking_date)
  SELECT ... FROM bookings_bronze WHERE booking_date >= '2024-01-01';

  -- New Spark SQL (almost identical!):
  spark.sql("""
    INSERT INTO bookings_silver PARTITION (booking_date)
    SELECT ... FROM bookings_bronze WHERE booking_date >= '2024-01-01'
  """)

PROS:
  βœ“ Often faster for iterative or multi-stage work; validate Spark vs MapReduce on representative workloads
  βœ“ Python/SQL (no more Java)
  βœ“ Unified streaming + batch
  βœ“ Lower compute costs (Spark finishes faster = fewer cluster-hours)

CONS:
  βœ— Rewriting all jobs takes time
  βœ— Spark expertise needed
  βœ— Still no ACID transactions without Delta Lake

Pattern 3: Refactor (Hive β†’ Delta Lake / Databricks)

sql
WHAT: Full modernization to cloud-native lakehouse
  Storage: HDFS β†’ ADLS Gen2 or S3
  Format:  ORC/Parquet β†’ Delta Lake (ACID transactions!)
  Processing: Hive+Tez β†’ Spark+Databricks
  Orchestration: Oozie β†’ Databricks Workflows / ADF / Airflow
  Security: Ranger β†’ Unity Catalog (Databricks)

HIVE TABLE β†’ DELTA LAKE TABLE:
  Old Hive (ORC):
  CREATE EXTERNAL TABLE bookings (...)
  STORED AS ORC
  LOCATION 'hdfs://namenode/user/hive/warehouse/bookings/';

  New Delta Lake:
  CREATE TABLE bookings (...)
  USING DELTA
  LOCATION 'abfss://container@storage.dfs.core.windows.net/bookings/'

  Convert existing ORC to Delta (in Databricks):
  CONVERT TO DELTA parquet.`/mnt/data/bookings/`   -- if Parquet
  -- Or write new Delta table from Hive:
  spark.table("hive_db.bookings").write.format("delta").save("/mnt/delta/bookings")

MIGRATION TOOLING EXAMPLE: Databricks Lakebridge (verify current support and scope):
  - Official Databricks tool for Hive β†’ Delta Lake migration
  - Auto-converts Hive DDL to Delta Lake CREATE TABLE statements
  - Migrates Hive Metastore β†’ Unity Catalog
  - Translates HiveQL β†’ Databricks SQL
  - Handles data copy from HDFS to cloud storage
  - Can assess compatibility: show what will break vs work automatically

PROS:
  βœ“ Full ACID (what Hive ACID never quite delivered)
  βœ“ Time travel / data versioning
  βœ“ Schema enforcement + evolution
  βœ“ Unified batch + streaming on same tables
  βœ“ Unity Catalog = better governance than Ranger + Atlas
  βœ“ Serverless (no cluster management)

CONS:
  βœ— Largest investment (rewrite + retrain team)
  βœ— Vendor lock-in (Databricks)
  βœ— Cost of migration project

WHEN TO CHOOSE:
  β†’ Greenfield or major modernization initiative
  β†’ Current Hadoop cost is very high (license + hardware)
  β†’ Team is growing and needs SQL-first tooling
  β†’ Need ACID and time travel on large tables

Hadoop vs Spark β€” Complete Comparison

FEATURE HADOOP MAPREDUCE APACHE SPARK
─────────────────────────────────────────────────────────────────────
Storage HDFS HDFS, S3, ADLS, local
Processing model Materializes stages Can retain/reuse data in memory
API Java only Python, Scala, Java, R, SQL
Fault tolerance Re-run from HDFS Re-compute from DAG lineage
Streaming Kafka→HDFS → MR Spark Streaming (micro-batch)
(latency: minutes) (latency: seconds)
Machine Learning Mahout (weak) MLlib, TensorFlow (strong)
Interactive SQL Hive via MR (slow) Spark SQL (fast)
ACID Hive ACID (complex) Delta Lake (native)
Latency Minutes to hours Seconds to minutes
Code complexity High (Java verbose) Low (Python/SQL)
When still used Legacy code, New development,
HBase on-prem, cloud-native
budget constraints lakehouse workloads
10-YEAR ENGINEER'S ANSWER:
"I've built production MapReduce pipelines and I understand the disk-based model.
In practice, I moved our critical pipelines to Spark years ago β€” the speed difference
is real. MapReduce still runs in companies because of existing code investment.
But for new development, there's no reason to use MapReduce over Spark today."

SECTION 6: HADOOP 3 FEATURES β€” DEEP DIVE

Erasure Coding

🧠 ERASURE CODING = alternative to 3x replication for cold/archive data
ERASURE CODINGalternative to 3x replication for cold/archive data
OLD WAY (Replication)
Store 1 GB file→3 copies → 3 GB used on HDFS
Storage overhead: 200% (3x replication = 200% overhead)
ERASURE CODING
Default EC policy: RS-6-3-1024k (Reed-Solomon, 6 data + 3 parity, 1 MB cells)
Store 1 GB file→6 data blocks + 3 parity blocks = 9 blocks
9 blocks total, each 1/6 size→total = 9/6 = 1.5x storage
Storage overhead: 50% (vs 200% for 3x replication)
SAVINGS: 50% storage reduction!
MATH EXAMPLE
Without EC: 128 MB block Γ— 3 copies = 384 MB used
With EC RS(6,3): 128 MB data β†’ 6 Γ— (21 MB data blocks) + 3 Γ— (21 MB parity blocks)
= 9 Γ— 21 MB = 189 MB used (β‰ˆ1.5x overhead vs 3x overhead)
TRADEOFFS
βœ“ 50% storage savings (saves money!)
βœ— Higher CPU overhead for reconstruction (when a node fails)
βœ— Cannot reconstruct if more than 3 nodes fail (lose 4+ β†’ data loss)
βœ— Not good for hot data (reconstruction is slow on read)
USE ERASURE CODING FOR
βœ“ Cold/archive data (accessed rarely)
βœ“ Large files in archive directories
βœ“ /archive, /backup, /historical paths
KEEP 3x REPLICATION FOR:
βœ“ Hot production data (fast recovery needed)
βœ“ Small files (EC overhead not worth it for small files)
βœ“ Data accessed frequently by MapReduce (data locality doesn't work well with EC)
bash
# Set EC policy on a directory:
hdfs ec -setPolicy -policy RS-6-3-1024k -path /data/archive/2020/
# All new files in /data/archive/2020/ will use EC instead of 3x replication

# Check current EC policy:
hdfs ec -getPolicy -path /data/archive/2020/

# List available EC policies:
hdfs ec -listPolicies

# Disable EC (back to replication) on a path:
hdfs ec -unsetPolicy -path /data/archive/2020/

SECTION 7: MOCK INTERVIEW β€” Top 10 Questions for 10-Year Engineers

Q1: "Walk me through the complete lifecycle of a Hive query"

sql
"When I run SELECT country, COUNT(*) FROM bookings GROUP BY country in Hive:

1. Driver receives query, initiates session
2. Compiler sends query to Metastore: 'where is bookings table?'
   Metastore returns: HDFS path, ORC format, partition scheme
3. Parser builds AST (Abstract Syntax Tree)
4. Semantic analyzer validates: table exists? columns exist? permissions OK?
5. Optimizer (CBO if stats exist): decides join type, partition pruning, predicate pushdown
6. Physical plan: break into stages (Stage 1: MAP + partial agg, Stage 2: reduce+sort)
7. With Tez: translate plan to Tez DAG (not MapReduce chain)
8. Submit to YARN: YARN allocates containers for Tez workers
9. Each Tez task reads ORC file from HDFS, uses vectorization (1024 rows at a time)
10. Results aggregated, written to temp HDFS path
11. Driver returns results to client

Key optimizations I'd verify: execution.engine=tez, vectorization=true,
ORC format, partition pruning active, CBO stats current."

Q2: "How did you handle data skew in a production pipeline?"

"I had a job grouping e-commerce transactions by country β€” US had 70% of all data.
One reducer was running for 6 hours while others finished in 20 minutes.
My fix: two-step approach.
Step 1: I set hive.groupby.skewindata=true in Hive β€” that fixed the Hive queries.
For MapReduce jobs: I implemented salting. I appended a random suffix to US keys:
'US_0', 'US_1' ... 'US_19' to distribute US data across 20 reducers.
Then a second MapReduce job merged the partial aggregations.
I also ran ANALYZE TABLE to let CBO make better decisions.
The job went from 6 hours to 45 minutes."

Q3: "HDFS NameNode HA failed. Active NameNode is dead, Standby is not taking over. Debug?"

"I'd debug in layers:
1. Check ZooKeeper: is ZK quorum healthy?
echo 'ruok' | nc zk-host 2181β†’expects 'imok'
If ZK is down→ZKFC can't elect new Active → failover stuck!
2. Check ZKFC on both NameNode hosts:
systemctl status hadoop-hdfs-zkfc
Look for: 'ZKFC is connected to ZooKeeper' vs 'Connection timeout'
3. Check FENCING: Did fencing script work on old Active?
Check logs: /var/log/hadoop-hdfs/hadoop-hdfs-namenode.log on standby
Look for: 'Fencing successful' or 'Fencing FAILED'
If fencing failed: Standby refuses to promote (correctly! prevents split-brain)
4. Force failover manually (with caution):
hdfs haadmin -failover --forceactive nn2
Only after confirming old Active is truly dead!
5. If Standby is way behind on edit logs:
hdfs namenode -bootstrapStandby
Re-sync Standby from JournalNodes"

Q4: "How would you migrate our 500 TB Hadoop cluster to Databricks on Azure?"

🧠 Memory Map
"I'd phase it over 6 months:
Phase 1 (Month 1-2): Assessment
Inventory all tables, jobs, data volumes, SLAs
Identify: HiveQL compatibility with Spark SQL (most is compatible!)
Find blockers: Hive UDFs in Java β†’ need to rewrite in Python
Use Databricks Lakebridge for automated assessment
Phase 2 (Month 2-3): Infrastructure + Data Migration
Set up ADLS Gen2 as new storage layer
Use DistCp to copy HDFS β†’ ADLS (start with cold/historical data first)
Convert ORC tables to Delta Lake format
Set up Databricks workspace + Unity Catalog for governance
Phase 3 (Month 3-5): Job Migration (start with easy wins)
Migrate Hive SQL jobs first (SQL is most compatible)
Migrate Oozie β†’ Databricks Workflows
Migrate Sqoop β†’ Azure Data Factory + Databricks autoloader
Keep old Hadoop running for validation (dual-run)
Phase 4 (Month 5-6): Cutover + Decommission
Run old and new in parallel for 2-4 weeks, compare results
Cut over teams one by one (analytics first, ETL pipeline last)
Decommission Hadoop cluster after validation period
RISK MITIGATION
Never do big-bang migration (always parallel run)
Start with read workloads, then write workloads
Hive ACID tables β†’ need careful migration to Delta Lake (preserve row-level changes)
Test SLAs: some Hive batch jobs may need Spark optimization to meet same SLAs"

Q5: "What are the biggest performance problems you've seen in Hadoop at scale?"

"Three big ones from production experience:
1. NameNode memory pressure:
50 million small files→NameNode OOM crash
Fix: HAR files for archive, Hive merge settings for new writes,
NameNode heap increased to 32 GB with G1GC
2. Shuffle bottleneck in MapReduce:
Sort buffer at default 100 MB→constant disk spill
Fix: increased mapreduce.task.io.sort.mb to 512 MB + enabled Snappy compression
Result: 60% job time reduction
3. Hive queries on Text format tables:
DBA created tables as TEXT (CSV). Text/CSV can be compressed, but compression does not
add column statistics or column pruning; these row-oriented scans and limited pruning
made analytical queries parse billions of complete records
Fix: converted all production tables to ORC + enabled vectorization
Result: 15x query speed improvement for analytical queries
The Hadoop small files problem is the most insidious β€” it degrades NameNode
stability gradually and only becomes critical when it's already a crisis."

SECTION 8: CAPACITY PLANNING

🧠 Memory Map
HADOOP CLUSTER SIZING GUIDELINES (10-year engineer reference)
STORAGE SIZING
Raw data size Γ— replication factor Γ— 1.25 (growth headroom)
Example: 100 TB raw data Γ— 3 replication Γ— 1.25 = 375 TB raw disk needed
With Erasure Coding (for cold data): 100 TB Γ— 1.5 Γ— 1.25 = 187.5 TB
COMPUTE SIZING
Determine: daily data processed + concurrent user queries
Rule of thumb: 1 compute node per 5 TB of hot data
For Hive/YARN: plan for peak concurrency (how many jobs run simultaneously)
DataNode spec: 64-128 GB RAM, 12-24 cores, 10 Γ— 4 TB drives (JBOD, not RAID)
NameNode spec: 32-128 GB RAM (depends on file count!), fast SSDs
NAMENODE MEMORY FORMULA
Each file/block = ~150 bytes in NameNode heap
10 million files→10M × 150 bytes = 1.5 GB
100 million files→100M × 150 bytes = 15 GB minimum
Add 50% safety buffer→22.5 GB → round to 32 GB
NODE COUNT (rough guideline)
NameNode: 2 (Active + Standby)
ZooKeeper: 3 or 5
JournalNode: 3 (can co-locate with ZooKeeper)
DataNode: depends on storage needs
YARN ResourceManager: 2 (Active + Standby)
HiveServer2: 2-4 (multiple for load balancing)
HBase RegionServer: co-locate with DataNodes (data locality!)

Integrated quick recall

Merged from HD_03_Quick_Recall.md; the legacy source remains unchanged.

Day 3: Performance, Security + Cloud Migration β€” Quick Recall Guide

⚑Must rememberπŸ”‘Key concept⚠️Common trap🧠Memory MapπŸ“One-liner

🧠 MASTER MEMORY MAP β€” Day 3

🧠 HADOOP SECURITY = "KRK" (Kerberos β†’ Ranger β†’ Knox):
HADOOP SECURITY"KRK" (Kerberos β†’ Ranger β†’ Knox):
KKerberos: AUTHENTICATION (who are you? β†’ TGT from KDC)
RRanger: AUTHORIZATION (what can you do? β†’ table/column/row policies)
KKnox: GATEWAY (how do you get in? β†’ SSL + single entry point)
PERFORMANCE TUNING"JYH-COMP":
JJVM: heap sizes (NN heap = 1 GB per million files!), G1GC
YYARN: container sizes, node memory, scheduler config
HHadoop: block size, handler count, short-circuit reads
CCompression: Snappy shuffle, GZIP/ZLIB archive
OOptimize sort buffer: 100 MB β†’ 512 MB (mapreduce.task.io.sort.mb)
MMore reducers: 1 β†’ nodesΓ—containersΓ—0.95
PParallel shuffle copies: parallelcopies default 5 β†’ 50
CLOUD MIGRATION"LRR":
LLift-and-Shift: HDFS β†’ S3/ADLS + same code (fastest, least benefit)
RReplatform: MapReduce β†’ Spark (same data, better processing)
RRefactor: Hive β†’ Delta Lake + Databricks (full modernization)
HADOOP vs SPARK = "Disk vs RAM":
MapReduce: disk-based, slow, Java only, fault-tolerant
Spark: can retain reused data in memory; Python/SQL/Scala, streaming+batch

SECTION 1: SECURITY β€” DIRECT QUESTIONS

⚑ Q1What is Kerberos in Hadoop?

Authentication protocol. Users/services prove identity to KDC (Key Distribution Center) and get cryptographic tickets. Without Kerberos, Hadoop accepts any claimed identity β€” zero security.

Q2What is a keytab file?

File containing pre-stored Kerberos credentials for a service account. Used by automated processes (Oozie jobs, cron) to authenticate without a password prompt. kinit -kt /etc/keytabs/hive.keytab hive/host@REALM

⚠️ Q3What happens if a Kerberos ticket expires during a long-running job?

Job fails with "Authentication failure" mid-execution. Fix: use long-lived keytabs + configure kinit -R (renewal) before jobs start, or set hadoop.security.auth_to_local token delegation for MapReduce/Spark jobs.

Q4What does Apache Ranger do?

Centralized fine-grained authorization for ALL Hadoop services. Policies define: who can do what on which resource. Supports table/column/row-level policies, column masking (show last 4 digits of SSN), full audit logging.

Q5What does Apache Knox do?

API Gateway and SSL proxy for Hadoop cluster. Single HTTPS entry point β€” users never connect directly to internal services. Simplifies firewall rules, provides SSO, terminates SSL at edge.

⚑ Q6Kerberos vs Ranger β€” what's the difference?

Kerberos = AUTHENTICATION (verifies who you are). Ranger = AUTHORIZATION (decides what you can do). Both are needed: Kerberos proves identity, Ranger enforces permissions. Like: Kerberos = ID check at door, Ranger = bouncer with guest list.

SECTION 2: PERFORMANCE β€” FLASH CARDS

⚑ Q7NameNode heap sizing rule?

1 GB per 1 million files/blocks. 10 million files β†’ 10 GB minimum. Add 50% buffer. Use G1GC for low-pause GC: -Xmx32g -Xms32g -XX:+UseG1GC. ⚠️ Default heap is only 1 GB β€” way too small for production!

Q8What is dfs.namenode.handler.count?

Number of RPC handler threads in NameNode. Default: 10 (too small for large clusters!). Rule: 20 Γ— log2(cluster_nodes). 100 nodes β†’ ~132 β†’ set to 100-150. Low handler count β†’ RPC queue builds up β†’ timeouts.

⚑ Q9What setting has the biggest MapReduce performance impact?

mapreduce.task.io.sort.mb β€” the in-memory sort buffer. Default 100 MB causes constant disk spills during shuffle. Increase to 512 MB β†’ fewer spills β†’ much faster shuffle. This one change often reduces job time 30-60%.

Q10What is mapreduce.reduce.shuffle.parallelcopies?

Number of parallel threads each reducer uses to copy map outputs. Default: 5 (very low). Increase to 50 β†’ reducers fetch shuffle data faster β†’ reduce phase starts sooner.

⚠️ Q11Why is G1GC preferred over default CMS GC for NameNode?

The premise is version-specific: do not assume CMS is the current JVM default. Choose a collector supported by the deployed JDK, then compare pause-time and throughput evidence under the real NameNode heap and metadata load. G1 is commonly evaluated for large heaps, but no fixed pause target is guaranteed.

Q12What is short-circuit read in HDFS?

dfs.client.read.shortcircuit=true β€” if client runs on SAME node as DataNode, it reads the block file directly from local disk (bypasses network stack). Faster local reads for jobs with data locality.

SECTION 3: DATA SKEW β€” FLASH CARDS

⚑ Q13What is data skew symptom in MapReduce?

99 reducers finish in 20 minutes. 1 reducer runs for 6 hours. One key (like "US") has millions of values β†’ all sent to one reducer β†’ bottleneck.

Q14How do you fix skew in MapReduce?
βœ… Pro Tip
Salting: append random suffix to hot key ("US" β†’ "US_0" to "US_99"). Distributes across 100 reducers. Then second pass to merge partial results. Or: custom Partitioner that splits hot keys across multiple reducers.
Q15How do you fix skew in Hive?

SET hive.groupby.skewindata=true β†’ Hive runs 2-phase GROUP BY. SET hive.optimize.skewjoin=true for skewed JOIN. ⚠️ NULL values all go to one reducer by default β€” use COALESCE(key, CONCAT('null_', RAND())).

SECTION 4: CLOUD MIGRATION β€” FLASH CARDS

⚑ Q16Three migration patterns from Hadoop to cloud?

Lift-and-Shift: copy HDFS β†’ S3/ADLS with DistCp, keep same code. Replatform: keep cloud storage, replace MapReduce with Spark. Refactor: full rebuild with Delta Lake + Databricks + Unity Catalog.

Q17What is DistCp?

Distributed Copy β€” MapReduce-based tool to copy data between HDFS paths or HDFS to cloud. hdfs distcp hdfs://namenode/data/ s3a://bucket/data/. Use -update flag for incremental copies (skip already-copied files).

⚠️ Q18Why use -skipcrccheck with DistCp to S3/ADLS?

HDFS uses CRC32 checksums; S3/ADLS use MD5-based ETags. They're incompatible β€” DistCp sees them as mismatches and re-copies everything on each run. -skipcrccheck skips checksum comparison β†’ only copies genuinely new/changed files.

Q19What is Databricks Lakebridge?
πŸ“ Note
A vendor migration accelerator referenced by the legacy notes for assessment and translation work. Verify its current supported sources, targets, and guarantees before planning; generated DDL or SQL still needs semantic validation and reconciliation.
⚑ Q20Hadoop MapReduce vs Spark β€” key difference?

MapReduce normally materializes job boundaries; Spark can pipeline stages and persist reused data, which often helps iterative workloads. The speedup is workload-dependent. Spark supports Python/SQL, streaming, and ML APIs; MapReduce is a batch model with APIs beyond only handwritten Java, including Streaming.

SECTION 5: HADOOP 3 + ERASURE CODING β€” FLASH CARDS

⚑ Q21What is Erasure Coding in Hadoop 3?

Alternative to 3x replication for cold data. RS-6-3: 6 data blocks + 3 parity blocks = 9 blocks total. Storage overhead: 1.5x vs 3x replication. Saves ~50% storage on archive data. Cost: higher CPU for reconstruction.

Q22When to use Erasure Coding vs Replication?

EC: cold/archive data (accessed rarely), large files, /archive directories. Replication: hot production data, small files, data locality needed for MapReduce jobs. Never use EC for frequently-accessed data (reconstruction is slow!).

Q23New YARN features in Hadoop 3?
βœ… Pro Tip
Opportunistic Containers (run low-priority tasks in spare capacity), Timeline Server v2 (better job history), Multiple Standby NameNodes (not just 1 standby), Intra-DataNode Balancer (balance disks within one DataNode).

SECTION 6: CAPACITY PLANNING β€” FLASH CARDS

Q24NameNode memory formula?

150 bytes per file/block in NameNode heap. 100 million files β†’ 15 GB minimum. Add 50% buffer β†’ 22.5 GB β†’ round up to 32 GB. Plus OS overhead. Use dedicated high-memory server for NameNode.

Q25DataNode hardware recommendation?

64-128 GB RAM, 12-24 CPU cores, 10-12 Γ— 4 TB SATA drives (JBOD β€” no RAID, HDFS handles redundancy), 10GbE network. Co-locate HBase RegionServers on DataNodes for data locality.

🧠 HADOOP ULTRA CHEAT SHEET β€” ALL 3 DAYS

sql
╔══════════════════════════════════════════════════════════════════════╗
β•‘                  HADOOP COMPLETE CHEAT SHEET                          β•‘
β•‘                    3-Day Interview Prep                                β•‘
╠══════════════════════════════════════════════════════════════════════╣
β•‘                                                                      β•‘
β•‘  β–  DAY 1: HDFS + YARN + MAPREDUCE                                    β•‘
β•‘                                                                      β•‘
β•‘  HDFS KEY NUMBERS: 128 MB blocks, 3x replication, 3s heartbeat        β•‘
β•‘  NameNode: live namespace/block maps in RAM; persistent image+edits β•‘
β•‘  DataNode: actual blocks, heartbeat every 3s, block report every 6h  β•‘
β•‘                                                                      β•‘
β•‘  NameNode HA = "JZ-FENCE":                                           β•‘
β•‘    JournalNodes (quorum log) + ZooKeeper (election) + FENCING        β•‘
β•‘    Fencing = kill old Active BEFORE promoting Standby (split-brain!) β•‘
β•‘                                                                      β•‘
β•‘  YARN = RM + NM + AM:                                                β•‘
β•‘    ResourceManager: cluster boss (Scheduler + AppManager)            β•‘
β•‘    NodeManager: per-node (runs containers, monitors resources)       β•‘
β•‘    ApplicationMaster: per-JOB (negotiates resources, handles fails)  β•‘
β•‘  Schedulers: FIFO (dev) / Capacity (multi-tenant) / Fair (mixed)     β•‘
β•‘                                                                      β•‘
β•‘  MapReduce = "I-Map-CBS-Reduce-O":                                   β•‘
β•‘    Input β†’ Map β†’ Combiner β†’ Buffer+Sort β†’ Shuffle β†’ Reduce β†’ Output  β•‘
β•‘    Shuffle = BOTTLENECK (disk + network + sort)                      β•‘
β•‘    Combiner: cut shuffle 60-80% (only commutative+associative!)       β•‘
β•‘    Speculative: duplicate slow tasks (DISABLE if side effects!)       β•‘
β•‘                                                                      β•‘
β•‘  Optimizations = "MCJ-COMP":                                         β•‘
║    Memory: sort buffer 100 MB→512 MB (biggest single win)              ║
β•‘    Combiner: pre-aggregate locally                                    β•‘
β•‘    JVM Reuse: jvm.numtasks=10 for many small tasks                   β•‘
β•‘    Compression: Snappy shuffle, GZIP output                          β•‘
β•‘    Output: LZO if output is input to next MR job (splittable!)       β•‘
β•‘    More Reducers: nodesΓ—containersΓ—0.95 (not 1!)                    β•‘
β•‘    Partitioner: custom for skewed keys                               β•‘
β•‘                                                                      β•‘
╠══════════════════════════════════════════════════════════════════════╣
β•‘                                                                      β•‘
β•‘  β–  DAY 2: HIVE + ECOSYSTEM                                           β•‘
β•‘                                                                      β•‘
β•‘  Hive Architecture = "DMCTE":                                        β•‘
β•‘    Driver β†’ Metastore β†’ Compiler β†’ Tez Engine β†’ Execution            β•‘
β•‘    Metastore = MySQL backend, stores schema+HDFS paths               β•‘
β•‘    ⚠️ Metastore DOWN β†’ ALL Hive queries FAIL                         β•‘
β•‘                                                                      β•‘
β•‘  Internal vs External:                                               β•‘
β•‘    Internal: DROP TABLE = data DELETED from HDFS!                    β•‘
β•‘    External: DROP TABLE = metadata only, data SAFE                   β•‘
β•‘    Usually External for raw/shared data when Hive must not own it    β•‘
β•‘                                                                      β•‘
β•‘  Partitioning:                                                       β•‘
β•‘    Static: PARTITION (date='..') β€” one partition at a time           β•‘
β•‘    Dynamic: nonstrict mode, Hive reads value from data               β•‘
β•‘    MSCK REPAIR TABLE β†’ sync new partitions from HDFS to Metastore    β•‘
β•‘    Pruning: filter DIRECTLY on partition column (not YEAR(date)!)    β•‘
β•‘                                                                      β•‘
β•‘  Hive Optimization = "VECTOR-TOP":                                   β•‘
β•‘    Engine=Tez (5-10x vs MapReduce), Vectorization (1024-row batches) β•‘
β•‘    CBO + ANALYZE TABLE, Map Join (< 25 MB β†’ broadcast)                β•‘
β•‘    ORC format + predicate pushdown (skip stripes by min/max)         β•‘
β•‘    skewindata=true (2-phase GROUP BY for hot keys)                   β•‘
β•‘    SORT BY not ORDER BY (unless global order needed)                 β•‘
β•‘    Merge small files: hive.merge.mapredfiles=true                    β•‘
β•‘                                                                      β•‘
β•‘  File Formats = "OPTA":                                              β•‘
β•‘    ORC: Hive-native, ACID, predicate pushdown (best for Hive)        β•‘
β•‘    Parquet: cross-tool Spark+Impala+Hive (best for multi-tool)       β•‘
β•‘    Text: can compress; row-oriented, no column pruning                β•‘
β•‘          use for landing/interchange; check codec splittability       β•‘
β•‘    Avro: schema evolution, Kafka/Sqoop landing (row-based)           β•‘
β•‘                                                                      β•‘
β•‘  HBase: NoSQL random R/W on HDFS                                     β•‘
β•‘    Row key: NEVER monotonic (hotspot!) β†’ use salt/reverse timestamp  β•‘
β•‘    Write: WAL β†’ MemStore β†’ HFile flush at 128 MB                      β•‘
β•‘                                                                      β•‘
β•‘  Sqoop: RDBMS ↔ HDFS                                                 β•‘
β•‘    Incremental: --incremental append (new rows) or lastmodified      β•‘
β•‘    --num-mappers: parallel DB connections (4-8 max!)                 β•‘
β•‘    Export NOT atomic β†’ use staging table!                            β•‘
β•‘                                                                      β•‘
β•‘  Oozie: Workflow (run once) + Coordinator (time+data trigger)        β•‘
β•‘  ZooKeeper: leader election (NameNode/HMaster/YARN RM)               β•‘
β•‘    Always odd nodes (3/5/7), ephemeral znodes for leader detection   β•‘
β•‘  Flume: Source β†’ Channel β†’ Sink for log ingestion                    β•‘
β•‘    File channel = durable; Memory channel = fast but lossy           β•‘
β•‘                                                                      β•‘
╠══════════════════════════════════════════════════════════════════════╣
β•‘                                                                      β•‘
β•‘  β–  DAY 3: PERFORMANCE, SECURITY, MIGRATION                           β•‘
β•‘                                                                      β•‘
β•‘  Security = "KRK":                                                   β•‘
β•‘    Kerberos: Authentication (kinit β†’ TGT β†’ Service Ticket)           β•‘
β•‘    Ranger: Authorization (table/column/row-level policies + audit)   β•‘
β•‘    Knox: Gateway (single HTTPS entry + SSL + SSO)                    β•‘
β•‘                                                                      β•‘
β•‘  JVM Tuning:                                                         β•‘
β•‘    NameNode: -Xmx32g -Xms32g -XX:+UseG1GC                           β•‘
β•‘    NameNode heap: 1 GB per 1 million files (150 bytes/file)           β•‘
β•‘    G1GC: short predictable pauses vs CMS long stop-the-world         β•‘
β•‘                                                                      β•‘
β•‘  MapReduce Critical Settings:                                        β•‘
β•‘    mapreduce.task.io.sort.mb=512     (default 100 = too small!)      β•‘
β•‘    mapreduce.map.output.compress=true + Snappy codec                 β•‘
β•‘    mapreduce.reduce.shuffle.parallelcopies=50 (default 5)            β•‘
β•‘    mapreduce.job.jvm.numtasks=10 (JVM reuse for small task jobs)     β•‘
β•‘    mapreduce.job.reduces=N (never leave at default 1!)               β•‘
β•‘                                                                      β•‘
β•‘  Data Skew Solutions:                                                β•‘
β•‘    MapReduce: salting (US β†’ US_0...US_99) + custom Partitioner       β•‘
β•‘    Hive GROUP BY: hive.groupby.skewindata=true (2-phase agg)         β•‘
β•‘    Hive JOIN: hive.optimize.skewjoin=true                            β•‘
β•‘    NULL keys: COALESCE(key, CONCAT('null_', RAND()))                 β•‘
β•‘                                                                      β•‘
β•‘  Erasure Coding (Hadoop 3):                                          β•‘
β•‘    RS-6-3: 6 data + 3 parity blocks = 1.5x overhead vs 3x           β•‘
β•‘    50% storage savings for cold/archive data                         β•‘
β•‘    ⚠️ High CPU for reconstruction β†’ cold data only!                  β•‘
β•‘                                                                      β•‘
β•‘  Cloud Migration = "LRR":                                            β•‘
║    Lift-and-Shift: DistCp HDFS→S3/ADLS, same code                   ║
β•‘    Replatform: MapReduce β†’ Spark (benchmark representative jobs)     β•‘
β•‘    Refactor: Hive β†’ Delta Lake; evaluate current migration tooling   β•‘
β•‘    Always: parallel run β†’ compare β†’ cutover (never big-bang!)        β•‘
β•‘                                                                      β•‘
β•‘  HADOOP vs SPARK:                                                    β•‘
β•‘    MapReduce: disk-based, Java, batch, slow (minutes to hours)       β•‘
β•‘    Spark: in-memory, Python/SQL, streaming+batch (seconds-minutes)   β•‘
β•‘    New work: choose by requirements; MapReduce may remain in estates β•‘
β•‘                                                                      β•‘
╠══════════════════════════════════════════════════════════════════════╣
β•‘                                                                      β•‘
β•‘  TOP 10 THINGS TO SAY IN INTERVIEW:                                  β•‘
β•‘                                                                      β•‘
β•‘  1. "NameNode HA: JournalNodes + ZooKeeper + FENCING (splits-brain)" β•‘
β•‘  2. "Shuffle is bottleneck: sort buffer 100 MB β†’ 512 MB is biggest win"β•‘
β•‘  3. "External tables for all raw/shared data β€” DROP TABLE is safe"   β•‘
β•‘  4. "MSCK REPAIR TABLE when Sqoop adds partitions outside Hive"      β•‘
β•‘  5. "Tez + vectorization + ORC can cut I/O and CPU; benchmark"      β•‘
β•‘  6. "HBase row key: NEVER monotonic (hotspot) β†’ use salting"         β•‘
β•‘  7. "Kerberos=authentication, Ranger=authorization, Knox=gateway"    β•‘
β•‘  8. "Erasure Coding saves 50% storage β€” use for cold/archive data"   β•‘
║  9. "Migration: Lift-Shift→ Replatform→ Refactor (never big-bang)"  ║
β•‘  10. "skewindata=true for GROUP BY skew, custom partitioner for MR"  β•‘
β•‘                                                                      β•‘
β•‘  10-YEAR ENGINEER FRAMING:                                           β•‘
β•‘  "I've not just run Hadoop queries β€” I've tuned NameNode heap,       β•‘
β•‘   fixed GC pauses causing DataNode timeouts, debugged ZKFC failover, β•‘
β•‘   implemented salting for skewed keys, and migrated pipelines from   β•‘
β•‘   MapReduce to Spark and then to Databricks lakehouses."             β•‘
β•‘                                                                      β•‘
β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•
Intermediate

Hadoop Commands Reference

#

Command recall map

Answer First: Choose the command family by the system boundary you are inspecting: hdfs dfs for namespace data operations, hdfs dfsadmin and fsck for HDFS health, yarn for applications and resources, Beeline/Hive SQL for metadata and queries, and sqoop for legacy RDBMS transfer.

Memory Map: namespace -> blocks -> cluster -> applications -> SQL metadata -> ingestion.

Run destructive commands only after confirming the path, ownership, trash policy, and recovery plan. Examples below retain their operational caveats and expected output.

πŸ“ Note
Legacy-tool note: Apache Sqoop was retired to the Apache Attic in 2021. The Sqoop section is retained for operating and migrating existing estates; prefer a supported connector or ingestion service for new systems.

Canonical source guide

Merged from HD_04_Commands_Reference.md; the legacy source remains unchanged.

Hadoop Commands Reference β€” Interview Quick-Fire Guide

⚠️ Common Trap
Purpose: Every command interviewers test, with real examples and traps to avoid Interviewers expect you to type these from memory Levels: ⬜ Direct (what/define) | 🟨 Mid-level (how/why) | πŸŸ₯ Scenario (debug/fix) Format: What it does β†’ Command syntax β†’ Practical example β†’ Interview tip

SECTION 1: HDFS COMMANDS (hadoop fs / hdfs dfs)

Key distinction: hdfs dfs invokes the Hadoop FileSystem shell and is the conventional spelling when working with HDFS. It is not HDFS-only: commands resolve the URI scheme or configured default filesystem, so explicit hdfs://, file://, and supported object-store connectors can be addressed. hadoop fs invokes the same shell and is documented as a synonym for hdfs dfs when HDFS is in use.

ls / ls -R β€” List files and directories

What it does: Lists files and directories in HDFS, similar to Linux ls.

Syntax:

bash
hdfs dfs -ls <path>
hdfs dfs -ls -R <path>          # Recursive listing (all subdirectories)
hdfs dfs -ls -h <path>          # Human-readable file sizes (KB, MB, GB)

Practical example:

bash
# List all files in the bookings directory
hdfs dfs -ls /data/travelco/bookings/
# Output:
# -rw-r--r--   3 krishna hadoop  1073741824 2026-03-25 14:30 /data/travelco/bookings/booking_2026.orc

# Recursive list to see all partitions under a Hive table
hdfs dfs -ls -R /user/hive/warehouse/bookings_db.db/flights/

# List with human-readable sizes
hdfs dfs -ls -h /data/travelco/bookings/
# Output: shows 1.0 G instead of 1073741824

Interview tip: The output columns are: permissions, replication factor, owner, group, size (bytes), date, time, path. The replication factor column is what catches people β€” they forget it's there. Files show replication (e.g., 3), directories show -.

mkdir / mkdir -p β€” Create directories

What it does: Creates directories in HDFS. -p creates parent directories if they don't exist.

Syntax:

bash
hdfs dfs -mkdir <path>
hdfs dfs -mkdir -p <path>       # Create parents (like Linux mkdir -p)

Practical example:

bash
# Create a single directory (parent must exist)
hdfs dfs -mkdir /data/travelco/

# Create full directory tree in one shot
hdfs dfs -mkdir -p /data/travelco/bookings/year=2026/month=03/day=25

# Common pattern: create staging + final directories
hdfs dfs -mkdir -p /data/staging/flights/
hdfs dfs -mkdir -p /data/processed/flights/

Interview tip: Without -p, the command fails if the parent doesn't exist. Always use -p in scripts and pipelines β€” it's idempotent (safe to run multiple times).

put / copyFromLocal β€” Upload files to HDFS

What it does: Copies a file from the local filesystem to HDFS. put and copyFromLocal are almost identical; put also reads from stdin.

Syntax:

bash
hdfs dfs -put <localPath> <hdfsPath>
hdfs dfs -copyFromLocal <localPath> <hdfsPath>
hdfs dfs -put -f <localPath> <hdfsPath>     # Overwrite if exists

Practical example:

bash
# Upload a local CSV to HDFS
hdfs dfs -put /home/krishna/booking_data.csv /data/travelco/staging/

# Upload and overwrite if file already exists
hdfs dfs -put -f /home/krishna/daily_export.csv /data/travelco/staging/daily_export.csv

# Upload multiple files at once
hdfs dfs -put /home/krishna/logs/*.log /data/travelco/raw_logs/

Interview tip: put fails if the destination file already exists (unless you use -f). The trap question: "What's the difference between put and copyFromLocal?" Answer: put can also read from stdin (echo "test" | hdfs dfs -put - /data/test.txt), while copyFromLocal only works with local files. In practice, they're interchangeable for file uploads.

get / copyToLocal β€” Download files from HDFS

What it does: Copies a file from HDFS to the local filesystem.

Syntax:

bash
hdfs dfs -get <hdfsPath> <localPath>
hdfs dfs -copyToLocal <hdfsPath> <localPath>

Practical example:

bash
# Download a single file from HDFS
hdfs dfs -get /data/travelco/reports/monthly_summary.csv /home/krishna/

# Download an entire directory
hdfs dfs -get /data/travelco/bookings/year=2026/month=03/ /home/krishna/march_data/

# Download and overwrite existing local file
hdfs dfs -get -f /data/travelco/reports/latest.csv /home/krishna/latest.csv

Interview tip: get downloads to the edge node's local filesystem, not to your laptop. For large files, prefer processing in HDFS rather than downloading β€” that defeats the purpose of distributed storage.

cat / head / tail β€” View file content

What it does: Reads and displays file content from HDFS.

Syntax:

bash
hdfs dfs -cat <hdfsPath>
hdfs dfs -head <hdfsPath>           # First 1 KB of file
hdfs dfs -tail <hdfsPath>           # Last 1 KB of file
hdfs dfs -cat <hdfsPath> | head -20 # First 20 lines (pipe to local head)

Practical example:

bash
# Quick peek at a small file
hdfs dfs -cat /data/travelco/config/etl_params.json

# View first 1 KB of a large log file
hdfs dfs -head /data/travelco/raw_logs/access.log

# View last 1 KB (check latest entries)
hdfs dfs -tail /data/travelco/raw_logs/access.log

# Practical: view first 20 lines of a CSV to check schema
hdfs dfs -cat /data/travelco/staging/bookings.csv | head -20

Interview tip: NEVER cat a large file (GBs) β€” it will stream the entire file to your terminal and kill your session. Always pipe to head for large files. head and tail in HDFS show only 1 KB, not lines β€” different from Linux.

mv / cp β€” Move and copy within HDFS

What it does: mv moves/renames files within HDFS. cp copies files within HDFS.

Syntax:

bash
hdfs dfs -mv <source> <destination>
hdfs dfs -cp <source> <destination>

Practical example:

bash
# Move processed files from staging to final location
hdfs dfs -mv /data/staging/bookings_2026.orc /data/processed/bookings_2026.orc

# Rename a file
hdfs dfs -mv /data/travelco/old_name.csv /data/travelco/new_name.csv

# Copy a file (creates a new copy with full replication)
hdfs dfs -cp /data/travelco/bookings/current.orc /data/travelco/bookings/backup_current.orc

# Move entire directory
hdfs dfs -mv /data/staging/batch_20260325/ /data/processed/batch_20260325/

Interview tip: mv within HDFS is a metadata-only operation (instant, no data movement) as long as source and destination are in the same filesystem. cp actually copies the data blocks β€” slow for large files. This is why Hive partition operations using ALTER TABLE ... SET LOCATION are fast β€” it's just a metadata change.

rm / rm -r β€” Delete files and directories

What it does: Deletes files or directories from HDFS. Deleted items go to the HDFS Trash (if enabled).

Syntax:

bash
hdfs dfs -rm <filePath>                 # Delete a file
hdfs dfs -rm -r <directoryPath>         # Delete directory recursively
hdfs dfs -rm -r -skipTrash <path>       # Permanent delete (bypass Trash)
hdfs dfs -rm -r -f <path>              # Force delete (no error if path missing)

Practical example:

bash
# Delete a single file
hdfs dfs -rm /data/staging/temp_file.csv

# Delete a directory and all contents
hdfs dfs -rm -r /data/staging/batch_20260324/

# Permanent delete when disk is full (bypass trash)
hdfs dfs -rm -r -skipTrash /data/old_logs/2024/

# Safe delete in scripts (no error if already deleted)
hdfs dfs -rm -r -f /data/staging/temp_dir/

Interview tip: By default, deleted files go to /user//.Trash/. The Trash auto-purge interval is set by fs.trash.interval in core-site.xml (default: 0 = disabled, common setting: 1440 = 24 hours). If the cluster is running low on space, use -skipTrash. Interview trap: "A DataNode disk is 95% full but you deleted files yesterday β€” why?" Answer: files are still in Trash.

du / du -s / du -h β€” Disk usage

What it does: Shows disk space used by files and directories in HDFS.

Syntax:

bash
hdfs dfs -du <path>                  # Size of each item in the path
hdfs dfs -du -s <path>              # Summary (total size of directory)
hdfs dfs -du -s -h <path>           # Human-readable summary

Practical example:

bash
# Check size of each subdirectory
hdfs dfs -du -h /data/travelco/
# Output:
# 12.5 G  37.4 G  /data/travelco/bookings
# 3.2 G   9.6 G   /data/travelco/flights
# 156.7 M 470.1 M /data/travelco/config
# First number = raw size, Second number = space with replication

# Total size of one directory
hdfs dfs -du -s -h /data/travelco/bookings/
# Output: 12.5 G  37.4 G  /data/travelco/bookings

# Check which partitions are largest (find data skew)
hdfs dfs -du -h /user/hive/warehouse/bookings_db.db/flights/year=2026/

Interview tip: du shows TWO numbers: raw file size and actual disk consumed (raw x replication factor). If replication=3, the second number is 3x the first. Interviewers ask: "Your HDFS is 80% full but data is only 10 TB β€” why?" Answer: with replication 3, 10 TB actually consumes 30 TB of disk.

chmod / chown β€” Permissions management

What it does: Changes file/directory permissions (chmod) or ownership (chown) in HDFS.

Syntax:

bash
hdfs dfs -chmod <permissions> <path>
hdfs dfs -chmod -R <permissions> <path>     # Recursive
hdfs dfs -chown <owner>:<group> <path>
hdfs dfs -chown -R <owner>:<group> <path>   # Recursive

Practical example:

bash
# Give read-write-execute to owner, read-execute to group and others
hdfs dfs -chmod 755 /data/travelco/bookings/

# Recursively set permissions for a Hive table directory
hdfs dfs -chmod -R 770 /user/hive/warehouse/bookings_db.db/

# Change ownership (for service accounts)
hdfs dfs -chown -R hive:hadoop /user/hive/warehouse/bookings_db.db/

# Give only the ETL service account write access
hdfs dfs -chown etl_user:etl_group /data/staging/
hdfs dfs -chmod 750 /data/staging/

Interview tip: HDFS permissions work like POSIX (Unix) permissions but with an important difference: there's no setuid/setgid concept. Also, HDFS has ACLs (Access Control Lists) for fine-grained permissions beyond the basic owner/group/others model. In production, Apache Ranger is used instead of raw chmod/chown for enterprise authorization.

count β€” File and directory count

What it does: Counts the number of directories, files, and total bytes under a path.

Syntax:

bash
hdfs dfs -count <path>
hdfs dfs -count -q <path>          # Include quota information
hdfs dfs -count -h <path>          # Human-readable sizes

Practical example:

bash
# Count files under a Hive table directory
hdfs dfs -count /user/hive/warehouse/bookings_db.db/flights/
# Output: 365  4380  45231965798  /user/hive/warehouse/bookings_db.db/flights/
# Meaning: 365 directories, 4380 files, 45.2 GB total

# Human-readable format
hdfs dfs -count -h /user/hive/warehouse/bookings_db.db/flights/
# Output: 365  4380  42.1 G  /user/hive/warehouse/bookings_db.db/flights/

# Check quota usage
hdfs dfs -count -q -h /data/travelco/

Interview tip: This is the go-to command for detecting the small files problem. If count shows 100,000 files but only 5 GB total, you have a small files problem (average file size = 50 KB, should be 128-256 MB). Each file consumes ~150 bytes of NameNode memory, so 100 million small files can crash the NameNode.

stat β€” File statistics

What it does: Displays statistics about a file or directory in a custom format.

Syntax:

bash
hdfs dfs -stat <format> <path>
# Format specifiers:
# %b = file size (bytes), %n = name, %o = block size
# %r = replication factor, %y = modification date

Practical example:

bash
# Get replication factor of a file
hdfs dfs -stat %r /data/travelco/bookings/booking_2026.orc
# Output: 3

# Get block size
hdfs dfs -stat %o /data/travelco/bookings/booking_2026.orc
# Output: 134217728  (128 MB)

# Get file size and modification time
hdfs dfs -stat "%b %y" /data/travelco/bookings/booking_2026.orc
# Output: 1073741824 2026-03-25 14:30:22

# Quick check: is replication factor correct?
hdfs dfs -stat "%n: replication=%r, blocksize=%o" /data/travelco/bookings/booking_2026.orc
# Output: booking_2026.orc: replication=3, blocksize=134217728

Interview tip: Use stat to quickly verify replication factor and block size during troubleshooting. If a critical file has replication=1, it's a single point of failure. Default block size is 128 MB (Hadoop 2+), was 64 MB in Hadoop 1.

touchz β€” Create empty file

What it does: Creates a zero-length (empty) file in HDFS. Fails if the file already exists.

Syntax:

bash
hdfs dfs -touchz <path>

Practical example:

bash
# Create a _SUCCESS flag file to signal ETL completion
hdfs dfs -touchz /data/travelco/bookings/year=2026/month=03/day=25/_SUCCESS

# Create a lock file for job coordination
hdfs dfs -touchz /data/travelco/locks/daily_etl.lock

# Create marker file for downstream pipelines
hdfs dfs -touchz /data/staging/batch_complete_20260325

Interview tip: touchz is commonly used to create _SUCCESS flag files that signal job completion. Oozie and custom ETL pipelines check for these files before triggering downstream jobs. Unlike Linux touch, HDFS touchz fails if the file already exists β€” it's NOT idempotent.

setrep β€” Set replication factor

What it does: Changes the replication factor of a file or directory in HDFS.

Syntax:

bash
hdfs dfs -setrep <replication> <path>
hdfs dfs -setrep -R <replication> <path>    # Recursive
hdfs dfs -setrep -w <replication> <path>    # Wait until replication completes

Practical example:

bash
# Increase replication for critical booking data
hdfs dfs -setrep 5 /data/travelco/bookings/current_month.orc

# Reduce replication for cold/archive data to save space
hdfs dfs -setrep -R 2 /data/travelco/archive/2024/

# Set replication for hot data and wait for completion
hdfs dfs -setrep -w 3 /data/travelco/bookings/today.orc

# Reduce replication on staging data (temporary, don't need 3 copies)
hdfs dfs -setrep -R 1 /data/staging/

Interview tip: Changing replication factor is async β€” the command returns immediately but blocks are replicated/removed in the background. Use -w to wait. Interview question: "How do you handle hot vs cold data in HDFS?" Answer: hot data at replication 3, cold/archive data at replication 2, staging at replication 1. In Hadoop 3, use erasure coding instead of reducing replication β€” it gives fault tolerance with only 1.5x overhead vs 3x.

getmerge β€” Merge HDFS files to local

What it does: Merges multiple HDFS files into a single local file. Useful for exporting MapReduce/Hive output.

Syntax:

bash
hdfs dfs -getmerge <hdfsDir> <localFile>
hdfs dfs -getmerge -nl <hdfsDir> <localFile>   # Add newline between files

Practical example:

bash
# Merge all MapReduce output parts into one file
hdfs dfs -getmerge /output/job_20260325/ /home/krishna/merged_output.csv

# Merge Hive query output (multiple part-00000 files)
hdfs dfs -getmerge /user/hive/warehouse/temp_results/ /home/krishna/query_results.txt

# Add newline separator between merged files
hdfs dfs -getmerge -nl /output/daily_reports/ /home/krishna/full_report.csv

Interview tip: getmerge downloads to the LOCAL filesystem, not HDFS. It's useful for getting MapReduce/Hive output that's split across many part-00000, part-00001 files into one usable file. Warning: don't use this on huge directories β€” it's pulling everything to one machine.

fsck β€” Filesystem check

What it does: Checks the health of the HDFS filesystem, reports missing blocks, under-replicated blocks, and corrupt files.

Syntax:

bash
hdfs fsck <path> [options]
hdfs fsck <path> -files              # List all files
hdfs fsck <path> -blocks             # Show block information
hdfs fsck <path> -locations          # Show block locations (which DataNodes)
hdfs fsck <path> -racks              # Show rack information
hdfs fsck <path> -files -blocks -locations   # Full detail

Practical example:

bash
# Check overall cluster health
hdfs fsck /

# Check health of a specific directory
hdfs fsck /data/travelco/bookings/ -files -blocks -locations
# Output shows:
# Total files: 4380
# Total blocks: 13140
# Minimally replicated blocks: 13140 (100.0%)
# Under-replicated blocks: 0 (0.0%)
# Missing blocks: 0 (0.0%)
# Corrupt blocks: 0

# Find which DataNodes hold blocks of a specific file
hdfs fsck /data/travelco/bookings/booking_2026.orc -files -blocks -locations
# Output:
# /data/travelco/bookings/booking_2026.orc 1073741824 bytes, 8 block(s):
#   blk_1073741825 len=134217728 [10.0.0.5:9866, 10.0.0.7:9866, 10.0.0.12:9866]
#   blk_1073741826 len=134217728 [10.0.0.3:9866, 10.0.0.8:9866, 10.0.0.15:9866]

# Check for corrupt or missing blocks across the cluster
hdfs fsck / -list-corruptfileblocks

Interview tip: hdfs fsck is THE command for diagnosing data loss and under-replication. If you see "Missing blocks" > 0, data is potentially lost. "Under-replicated" means blocks have fewer copies than the replication factor β€” not yet lost but at risk. Interviewers love: "You get an alert that HDFS has missing blocks β€” what do you do?" Answer: run fsck, identify affected files, check DataNode health with dfsadmin -report, check DataNode logs for disk failures.

balancer β€” Rebalance blocks across DataNodes

What it does: Redistributes blocks across DataNodes to achieve even disk usage. Required after adding new nodes or when some nodes are significantly fuller than others.

Syntax:

bash
hdfs balancer
hdfs balancer -threshold <percentage>     # Default 10%
hdfs balancer -policy datanode            # Balance by DataNode usage

Practical example:

bash
# Run balancer with default 10% threshold
# (stops when all nodes are within 10% of average utilization)
hdfs balancer

# Tighter balance β€” within 5% of average
hdfs balancer -threshold 5

# Run with bandwidth limit to avoid impacting production jobs
# (set in hdfs-site.xml: dfs.datanode.balance.bandwidthPerSec)
hdfs balancer -threshold 10

# Check balance status β€” look at utilization spread
hdfs dfsadmin -report | grep "DFS Used%"

Interview tip: The balancer runs as a background process and is bandwidth-limited to avoid saturating the network. Default bandwidth is 10 MB/s per DataNode (dfs.datanode.balance.bandwidthPerSec). Interview question: "You added 10 new DataNodes but new data still goes to old nodes β€” why?" Answer: existing data is not automatically rebalanced. New writes are balanced, but you need to run the balancer for existing data. Also, HDFS prefers writing to local DataNode first (data locality), so new data naturally goes to wherever the writers run.

dfsadmin -report β€” Cluster health report

What it does: Displays a comprehensive report of the HDFS cluster including capacity, usage, and DataNode status.

Syntax:

bash
hdfs dfsadmin -report
hdfs dfsadmin -report -live           # Only live DataNodes
hdfs dfsadmin -report -dead           # Only dead DataNodes

Practical example:

bash
# Full cluster health report
hdfs dfsadmin -report
# Output:
# Configured Capacity: 500 TB
# Present Capacity: 480 TB
# DFS Remaining: 200 TB (41.67%)
# DFS Used: 280 TB (58.33%)
# Under replicated blocks: 0
# Blocks with corrupt replicas: 0
# Missing blocks: 0
#
# ----- Live DataNodes (50) -----
# Name: 10.0.0.5:9866 (datanode05.cluster.local)
# Decommission Status: Normal
# Configured Capacity: 10 TB
# DFS Used: 5.6 TB (56.00%)
# ...

# Quick check: are any DataNodes dead?
hdfs dfsadmin -report -dead

Interview tip: This is the FIRST command you run when troubleshooting any HDFS issue. It shows you dead DataNodes, disk usage, under-replicated blocks β€” everything at a glance. Interviewers ask: "How do you monitor HDFS health?" Answer: dfsadmin -report for manual checks, plus Ambari/Cloudera Manager/Grafana dashboards for continuous monitoring with alerting on missing blocks, capacity thresholds, and dead DataNodes.

dfsadmin -safemode β€” Safe mode operations

What it does: Safe mode is a read-only state where HDFS doesn't allow any modifications. NameNode enters safe mode on startup until enough DataNodes report their blocks.

Syntax:

bash
hdfs dfsadmin -safemode get            # Check if safe mode is ON/OFF
hdfs dfsadmin -safemode enter          # Manually enter safe mode
hdfs dfsadmin -safemode leave          # Manually leave safe mode
hdfs dfsadmin -safemode wait           # Block until safe mode exits

Practical example:

bash
# Check safe mode status
hdfs dfsadmin -safemode get
# Output: Safe mode is OFF

# Enter safe mode before maintenance
hdfs dfsadmin -safemode enter
# Do maintenance (e.g., snapshot, config change)
hdfs dfsadmin -safemode leave

# In scripts: wait for safe mode to finish after cluster restart
hdfs dfsadmin -safemode wait
echo "HDFS is ready, starting ETL jobs..."

Interview tip: NameNode auto-enters safe mode on startup and waits until 99.9% of blocks are reported by DataNodes (configurable via dfs.namenode.safemode.threshold-pct). Classic interview scenario: "Your ETL job fails with 'Cannot create file, NameNode is in safe mode' β€” what happened?" Answer: the NameNode restarted (or is still starting up), or someone manually entered safe mode for maintenance. Fix: check why NameNode restarted, wait for safe mode to auto-exit, or manually leave with safemode leave (only if you understand why it was in safe mode).

SECTION 2: YARN COMMANDS

YARN = Yet Another Resource Negotiator. It manages cluster resources (CPU + memory) across all applications.

yarn application -list β€” List running applications

What it does: Lists all running (or filtered by state) YARN applications.

Syntax:

bash
yarn application -list                               # Running apps
yarn application -list -appStates ALL                # All states
yarn application -list -appStates FINISHED           # Completed apps
yarn application -list -appStates FAILED,KILLED      # Failed or killed
yarn application -list -appTypes SPARK               # Only Spark apps

Practical example:

bash
# See what's currently running on the cluster
yarn application -list
# Output:
# Application-Id          Name                  State    Queue     Progress
# application_1234_0001   daily_booking_etl     RUNNING  default   65%
# application_1234_0002   hive_query_xyz        RUNNING  adhoc     30%

# Check how many jobs finished today
yarn application -list -appStates FINISHED

# Find all failed Spark jobs
yarn application -list -appStates FAILED -appTypes SPARK

Interview tip: This is your first command when the cluster seems slow β€” check if rogue applications are consuming all resources. Look for apps stuck at 0% progress (possible data skew or deadlock) or apps running for hours in a queue that should take minutes.

yarn application -status β€” Application details

What it does: Shows detailed status of a specific YARN application.

Syntax:

bash
yarn application -status <applicationId>

Practical example:

bash
# Check status of a specific application
yarn application -status application_1711350000000_0042
# Output:
# Application Report:
#   Application-Id: application_1711350000000_0042
#   Application-Name: daily_booking_etl
#   Application-Type: SPARK
#   State: RUNNING
#   Final-Status: UNDEFINED
#   Progress: 65%
#   Queue: production
#   AM Host: datanode15.cluster.local
#   Allocated Resources: <memory:40960 MB, vCores:16>
#   Running Containers: 8
#   Start-Time: 1711350120000

Interview tip: Key things to check: the Queue (is it in the right queue?), Allocated Resources (is it hogging too much?), Running Containers (are they as expected?), and Start-Time (has it been running too long?). If Final-Status is UNDEFINED while State is RUNNING, the job is still in progress.

yarn application -kill β€” Kill an application

What it does: Forcefully kills a running YARN application.

Syntax:

bash
yarn application -kill <applicationId>

Practical example:

bash
# Kill a stuck Hive query that's consuming all cluster resources
yarn application -kill application_1711350000000_0042
# Output: Killing application application_1711350000000_0042
# Application application_1711350000000_0042 has been killed.

# Common scenario: kill all stuck applications in a loop
for app_id in $(yarn application -list -appStates RUNNING | grep "stuck_job" | awk '{print $1}'); do
    yarn application -kill $app_id
done

Interview tip: You need sufficient permissions to kill an application β€” either be the owner or have admin rights. In a production environment, always check what the application is doing BEFORE killing it. Killing a Hive INSERT OVERWRITE mid-way can leave partial data. Interview scenario: "A Spark job is using 80% of cluster resources and blocking other jobs β€” what do you do?" Answer: check the queue configuration first (Capacity Scheduler limits), then kill if necessary, then fix the root cause (add resource limits, use separate queues).

yarn logs β€” Application logs

What it does: Retrieves logs for a completed or running YARN application.

Syntax:

bash
yarn logs -applicationId <appId>
yarn logs -applicationId <appId> -containerId <containerId>   # Specific container
yarn logs -applicationId <appId> -nodeAddress <nodeAddress>    # Specific node
yarn logs -applicationId <appId> -log_files stderr             # Only stderr

Practical example:

bash
# Get all logs for a failed application
yarn logs -applicationId application_1711350000000_0042 > /home/krishna/job_logs.txt

# Get only stderr (where exceptions appear)
yarn logs -applicationId application_1711350000000_0042 -log_files stderr

# Get logs from a specific container (useful for debugging specific task failures)
yarn logs -applicationId application_1711350000000_0042 \
  -containerId container_1711350000000_0042_01_000005

# Get logs from a specific node
yarn logs -applicationId application_1711350000000_0042 \
  -nodeAddress datanode15.cluster.local:8041

Interview tip: Logs are available AFTER the application finishes (unless log aggregation is enabled). Log aggregation (yarn.log-aggregation-enable=true) collects logs from all NodeManagers and stores them in HDFS (/app-logs/ by default). Without log aggregation, you must SSH to each NodeManager to read logs. Interview trap: "Your Spark job failed yesterday but you can't find the logs β€” why?" Answer: log aggregation might be disabled, or the aggregated logs have been cleaned up (check yarn.log-aggregation.retain-seconds).

yarn node -list β€” List cluster nodes

What it does: Lists all NodeManagers in the YARN cluster with their status and resources.

Syntax:

bash
yarn node -list                    # All nodes
yarn node -list -states RUNNING    # Only active nodes
yarn node -list -all               # Include decommissioned/lost nodes

Practical example:

bash
# List all active NodeManagers
yarn node -list -states RUNNING
# Output:
# Node-Id                  Node-State  Node-Http-Address     Containers
# datanode01:45454         RUNNING     datanode01:8042       4
# datanode02:45454         RUNNING     datanode02:8042       6
# datanode03:45454         RUNNING     datanode03:8042       3

# Check for unhealthy or lost nodes
yarn node -list -all

Interview tip: Healthy NodeManagers regularly heartbeat to the ResourceManager. If a NodeManager stops heartbeating past the configured expiry interval, the ResourceManager marks it LOST and reports its containers as completed/lost. Replacement behavior is application-specific: retry policy belongs to the framework-specific ApplicationMaster, which may request new containers and relaunch task attempts. MapReduce does this for eligible failed attempts; other applications may not. The scheduler does not automatically restart arbitrary work or guarantee recovery by itself.

yarn queue -status β€” Queue information

What it does: Shows the status and resource allocation of a specific YARN queue.

Syntax:

bash
yarn queue -status <queueName>

Practical example:

bash
# Check the production queue status
yarn queue -status production
# Output:
# Queue Name: production
# State: RUNNING
# Capacity: 60.0%
# Current Capacity: 45.0%
# Maximum Capacity: 80.0%
# Default Node Label: <DEFAULT>
# Number of Applications: 3

# Check the adhoc queue
yarn queue -status adhoc

Interview tip: Queue configuration is how enterprises control resource sharing. Capacity Scheduler (default in HDP) defines percentage-based queues. Fair Scheduler (default in CDH) shares resources equally. Interview question: "How do you prevent one team from monopolizing cluster resources?" Answer: configure separate queues with capacity limits (e.g., production=60%, analytics=30%, adhoc=10%) and set maximum-capacity to prevent elastic growth beyond a threshold.

yarn top β€” Resource usage overview

What it does: Shows real-time cluster resource usage, similar to Linux top.

Syntax:

bash
yarn top

Practical example:

bash
# Real-time resource monitoring
yarn top
# Output (refreshes every 3 seconds):
# JEEP CLUSTER SUMMARY: 50 NodeManagers
# Memory: 500 GB / 800 GB used (62.5%)
# VCores: 200 / 400 used (50.0%)
# Queue    Capacity  Used  Apps  Containers
# root.prod  60%     45%    3      24
# root.adhoc 30%     15%    2      8
# root.dev   10%     2%     1      2

Interview tip: yarn top gives you the real-time bird's eye view. If memory usage is at 95%, new applications will be queued (pending). If vCores are maxed out, jobs will run but slower. The balance between memory and vCores matters β€” you can have free memory but no vCores, or vice versa.

SECTION 3: HIVE COMMANDS (beeline / hive CLI)

πŸ“ Note
Note: The hive CLI is deprecated since Hive 2.0. Use beeline for all production work. beeline connects to HiveServer2 via JDBC, supports authentication and concurrent sessions.

beeline β€” Connection string

What it does: Connects to HiveServer2 for executing Hive queries.

Syntax:

bash
beeline -u "jdbc:hive2://<host>:<port>/<database>"
beeline -u "jdbc:hive2://<host>:<port>/<database>" -n <username> -p <password>
beeline -u "jdbc:hive2://<host>:10000/default" --hiveconf hive.execution.engine=tez

Practical example:

bash
# Connect to HiveServer2 on default port
beeline -u "jdbc:hive2://hiveserver.cluster.local:10000/default"

# Connect with Kerberos authentication
beeline -u "jdbc:hive2://hiveserver.cluster.local:10000/default;principal=hive/_HOST@REALM.COM"

# Connect and run a single query (non-interactive)
beeline -u "jdbc:hive2://hiveserver.cluster.local:10000/default" \
  -e "SELECT count(*) FROM bookings WHERE year=2026"

# Connect and run a script file
beeline -u "jdbc:hive2://hiveserver.cluster.local:10000/default" \
  -f /home/krishna/etl_daily.hql

Interview tip: beeline vs hive CLI β€” know the difference. hive CLI runs an embedded Metastore and doesn't go through HiveServer2, so it bypasses security (no authentication). beeline connects via JDBC to HiveServer2, supports Kerberos, LDAP, and concurrent users. In interviews, always say you use beeline.

SHOW / DESCRIBE β€” Metadata exploration

What it does: Explores databases, tables, and schema metadata.

Syntax:

sql
SHOW DATABASES;
SHOW TABLES;
SHOW TABLES IN <database>;
DESCRIBE <table>;
DESCRIBE FORMATTED <table>;        -- Full metadata including location, format, partitions
DESCRIBE EXTENDED <table>;         -- Similar but less readable
SHOW PARTITIONS <table>;
SHOW CREATE TABLE <table>;         -- DDL to recreate the table

Practical example:

sql
-- List all databases
SHOW DATABASES;

-- Switch to bookings database
USE bookings_db;

-- List all tables
SHOW TABLES;

-- Quick schema check
DESCRIBE flights;
-- Output:
-- flight_id    int
-- origin       string
-- destination  string
-- departure    timestamp
-- year         int        (partition column)
-- month        int        (partition column)

-- Full metadata (CRITICAL for interviews)
DESCRIBE FORMATTED flights;
-- Shows: location (HDFS path), InputFormat, OutputFormat, SerDe,
-- partition columns, table type (MANAGED/EXTERNAL), creation time

-- See all partitions
SHOW PARTITIONS flights;
-- Output:
-- year=2025/month=01
-- year=2025/month=02
-- ...
-- year=2026/month=03

-- Get exact DDL
SHOW CREATE TABLE flights;

Interview tip: DESCRIBE FORMATTED is the most powerful metadata command β€” it shows the HDFS location, file format (ORC/Parquet), SerDe, partition columns, and whether it's MANAGED or EXTERNAL. Interview question: "How do you find where a Hive table's data is stored?" Answer: DESCRIBE FORMATTED table_name β€” look for the Location field.

CREATE TABLE β€” Internal, external, partitioned, bucketed

What it does: Creates Hive tables with various storage configurations.

Syntax and examples:

sql
-- INTERNAL (Managed) TABLE: Hive owns the data. DROP TABLE = data deleted.
CREATE TABLE bookings (
    booking_id   BIGINT,
    passenger    STRING,
    flight_code  STRING,
    amount       DOUBLE,
    booking_time TIMESTAMP
)
STORED AS ORC
TBLPROPERTIES ('orc.compress'='SNAPPY');

-- EXTERNAL TABLE: Hive only manages metadata. DROP TABLE = data stays.
CREATE EXTERNAL TABLE flights_raw (
    flight_id    INT,
    origin       STRING,
    destination  STRING,
    departure    STRING
)
ROW FORMAT DELIMITED
FIELDS TERMINATED BY ','
STORED AS TEXTFILE
LOCATION '/data/travelco/raw/flights/';

-- PARTITIONED TABLE (most common in production)
CREATE EXTERNAL TABLE bookings_partitioned (
    booking_id   BIGINT,
    passenger    STRING,
    flight_code  STRING,
    amount       DOUBLE
)
PARTITIONED BY (year INT, month INT, day INT)
STORED AS ORC
LOCATION '/data/travelco/bookings/';

-- BUCKETED TABLE (for optimized joins)
CREATE TABLE bookings_bucketed (
    booking_id   BIGINT,
    passenger    STRING,
    flight_code  STRING,
    amount       DOUBLE
)
CLUSTERED BY (booking_id) INTO 32 BUCKETS
STORED AS ORC;

Interview tip: The #1 Hive interview question: "Internal vs External table β€” when to use which?" Answer: Use EXTERNAL for raw/shared data (dropping table won't delete data, safe for multiple consumers). Use INTERNAL/MANAGED for intermediate/temp tables where Hive should manage lifecycle. In production, 90% of tables are EXTERNAL. Bucketing: use when you frequently join two large tables on the same key β€” bucketed tables enable bucket map join (no shuffle).

LOAD DATA / INSERT β€” Loading data into tables

What it does: Loads data from files or query results into Hive tables.

Syntax:

sql
-- LOAD DATA: moves a file into the table's HDFS directory (no transformation)
LOAD DATA INPATH '<hdfs_path>' INTO TABLE <table>;
LOAD DATA INPATH '<hdfs_path>' OVERWRITE INTO TABLE <table>;
LOAD DATA LOCAL INPATH '<local_path>' INTO TABLE <table>;

-- INSERT INTO: appends query results
INSERT INTO TABLE <target> SELECT * FROM <source>;

-- INSERT OVERWRITE: replaces all data (or partition)
INSERT OVERWRITE TABLE <target> SELECT * FROM <source>;

-- DYNAMIC PARTITION INSERT
INSERT OVERWRITE TABLE bookings PARTITION (year, month, day)
SELECT booking_id, passenger, flight_code, amount, year, month, day
FROM staging_bookings;

Practical example:

sql
-- Load a CSV file from HDFS into a raw table
LOAD DATA INPATH '/data/staging/bookings_20260325.csv' INTO TABLE bookings_raw;

-- Load from local filesystem (copies to HDFS first)
LOAD DATA LOCAL INPATH '/home/krishna/test_data.csv' INTO TABLE test_table;

-- ETL pattern: transform and load into partitioned ORC table
SET hive.exec.dynamic.partition=true;
SET hive.exec.dynamic.partition.mode=nonstrict;

INSERT OVERWRITE TABLE bookings_orc PARTITION (year, month)
SELECT
    booking_id, passenger, flight_code, amount,
    year(booking_time) AS year,
    month(booking_time) AS month
FROM bookings_raw
WHERE booking_date = '2026-03-25';

-- Overwrite a specific partition only
INSERT OVERWRITE TABLE bookings_orc PARTITION (year=2026, month=3)
SELECT booking_id, passenger, flight_code, amount
FROM bookings_raw
WHERE year(booking_time) = 2026 AND month(booking_time) = 3;

Interview tip: LOAD DATA INPATH MOVES the file (not copies) β€” the source file is gone after the load. Use LOAD DATA LOCAL INPATH to copy from local. INSERT OVERWRITE with a partition spec only overwrites THAT partition, not the entire table. Dynamic partitioning requires hive.exec.dynamic.partition.mode=nonstrict β€” without this, Hive requires at least one static partition. Interview trap: "Your INSERT OVERWRITE deleted all data instead of just one partition" β€” you forgot the PARTITION clause.

ALTER TABLE β€” Modify table structure

What it does: Modifies table schema, properties, partitions, or location.

Syntax and examples:

sql
-- Add a partition manually (static partitioning)
ALTER TABLE bookings ADD PARTITION (year=2026, month=3, day=25)
LOCATION '/data/travelco/bookings/year=2026/month=03/day=25';

-- Drop a partition (data deleted for managed tables, kept for external)
ALTER TABLE bookings DROP PARTITION (year=2024, month=1);

-- Rename table
ALTER TABLE old_bookings RENAME TO bookings_archive;

-- Add a column
ALTER TABLE bookings ADD COLUMNS (loyalty_tier STRING);

-- Change column name/type
ALTER TABLE bookings CHANGE old_column_name new_column_name BIGINT;

-- Change table properties
ALTER TABLE bookings SET TBLPROPERTIES ('orc.compress'='ZLIB');

-- Change HDFS location
ALTER TABLE bookings SET LOCATION '/data/travelco/bookings_v2/';

Interview tip: Adding partitions with ALTER TABLE ADD PARTITION is called static partitioning β€” you manually define each partition. This is needed when data is already in HDFS but Hive doesn't know about it. More common: use MSCK REPAIR TABLE to auto-discover all partitions. ALTER TABLE on an external table only changes metadata β€” the data in HDFS is untouched.

MSCK REPAIR TABLE β€” Sync partitions

What it does: Scans the HDFS directory structure and automatically adds any partitions that exist in HDFS but not in the Hive Metastore.

Syntax:

sql
MSCK REPAIR TABLE <table>;

Practical example:

sql
-- Scenario: Spark/ETL wrote new partition directories to HDFS
-- HDFS has: /data/bookings/year=2026/month=03/day=25/
-- But Hive doesn't know about it yet

-- Sync Hive Metastore with HDFS
MSCK REPAIR TABLE bookings;
-- Output: Partitions not in metastore: bookings:year=2026/month=03/day=25
-- Now the partition is queryable

-- Verify
SHOW PARTITIONS bookings;

Interview tip: MSCK REPAIR TABLE is essential when external tools (Spark, Sqoop, manual hdfs dfs -put) create partition directories without going through Hive. It only ADDS partitions β€” it does NOT remove partitions whose HDFS directories were deleted. For large tables with thousands of partitions, MSCK REPAIR can be slow β€” prefer ALTER TABLE ADD PARTITION for specific partitions. Interview question: "Spark wrote data to HDFS but Hive query returns 0 rows β€” why?" Answer: partitions not registered in Metastore. Fix: MSCK REPAIR TABLE.

EXPLAIN β€” Query execution plan

What it does: Shows the execution plan of a Hive query without running it. Essential for optimization.

Syntax:

sql
EXPLAIN <query>;
EXPLAIN EXTENDED <query>;           -- More detail
EXPLAIN FORMATTED <query>;          -- Readable JSON format

Practical example:

sql
-- See execution plan for a join query
EXPLAIN
SELECT b.booking_id, f.origin, f.destination
FROM bookings b
JOIN flights f ON b.flight_code = f.flight_code
WHERE b.year = 2026 AND b.month = 3;

-- Output shows:
-- Stage-1: Map (reads bookings, applies partition filter)
-- Stage-2: Map (reads flights)
-- Stage-3: Reduce (shuffle join on flight_code)

-- Check if partition pruning is working
EXPLAIN
SELECT count(*) FROM bookings WHERE year = 2026;
-- Look for: filterExpr: (year = 2026) β€” means partition pruning is active

Interview tip: Always EXPLAIN before running expensive queries. Look for: (1) partition pruning β€” is Hive scanning only needed partitions? (2) join strategy β€” map join (broadcast) vs reduce join (shuffle). (3) number of stages β€” fewer stages = faster. Interview scenario: "Your Hive query scans 5 TB but should only scan 50 GB β€” what's wrong?" Answer: run EXPLAIN, check if partition pruning is happening. If WHERE clause uses a function on the partition column (e.g., WHERE year(dt) = 2026 instead of WHERE year = 2026), Hive can't do partition pruning.

SET β€” Configuration at runtime

What it does: Sets Hive configuration parameters for the current session.

Key settings for interviews:

sql
-- Select Tez for DAG execution; verify engine availability and benchmark the workload
SET hive.execution.engine=tez;

-- Enable vectorized execution (process 1024 rows at a time instead of 1)
SET hive.vectorized.execution.enabled=true;
SET hive.vectorized.execution.reduce.enabled=true;

-- Enable dynamic partitioning
SET hive.exec.dynamic.partition=true;
SET hive.exec.dynamic.partition.mode=nonstrict;

-- Enable map join (broadcast small table)
SET hive.auto.convert.join=true;
SET hive.mapjoin.smalltable.filesize=25000000;  -- 25 MB threshold

-- Enable CBO (Cost-Based Optimizer)
SET hive.cbo.enable=true;
SET hive.compute.query.using.stats=true;
SET hive.stats.fetch.column.stats=true;

-- Enable compression
SET hive.exec.compress.output=true;
SET mapreduce.output.fileoutputformat.compress.codec=org.apache.hadoop.io.compress.SnappyCodec;

-- Control parallelism
SET hive.exec.parallel=true;
SET hive.exec.parallel.thread.number=8;

Interview tip: The top 3 Hive performance settings interviewers expect you to know: (1) hive.execution.engine=tez β€” switch from MapReduce to Tez, (2) vectorized execution β€” processes batches of 1024 rows, (3) CBO with ANALYZE TABLE for statistics. These three alone can improve query performance by 10-50x.

SECTION 4: SQOOP COMMANDS

Sqoop = SQL-to-Hadoop. Imports data from RDBMS (Oracle, MySQL, PostgreSQL) into HDFS/Hive and exports back. Uses MapReduce under the hood for parallel data transfer.

sqoop import β€” Basic import

What it does: Imports a table from an RDBMS into HDFS or Hive.

Syntax and examples:

bash
# Basic import from MySQL to HDFS
sqoop import \
  --connect jdbc:mysql://db.travelco.local:3306/bookings_db \
  --username etl_user \
  --password-file /home/krishna/.sqoop_password \
  --table bookings \
  --target-dir /data/travelco/sqoop_import/bookings/ \
  --as-avrodatafile \
  --num-mappers 8

# Import into Hive table directly
sqoop import \
  --connect jdbc:mysql://db.travelco.local:3306/bookings_db \
  --username etl_user \
  --password-file /home/krishna/.sqoop_password \
  --table bookings \
  --hive-import \
  --hive-table bookings_db.bookings_raw \
  --hive-overwrite \
  --num-mappers 8

# Import with WHERE clause (subset of data)
sqoop import \
  --connect jdbc:mysql://db.travelco.local:3306/bookings_db \
  --username etl_user \
  --password-file /home/krishna/.sqoop_password \
  --table bookings \
  --where "booking_date >= '2026-03-01'" \
  --target-dir /data/travelco/sqoop_import/bookings_march/ \
  --num-mappers 4

# Import with custom query
sqoop import \
  --connect jdbc:mysql://db.travelco.local:3306/bookings_db \
  --username etl_user \
  --password-file /home/krishna/.sqoop_password \
  --query "SELECT b.*, f.origin, f.destination FROM bookings b JOIN flights f ON b.flight_code = f.flight_code WHERE \$CONDITIONS" \
  --split-by b.booking_id \
  --target-dir /data/travelco/sqoop_import/enriched_bookings/ \
  --num-mappers 8

Interview tip: --split-by determines how Sqoop parallelizes the import. By default, it uses the primary key. If no primary key, you MUST specify --split-by or use --num-mappers 1. The --split-by column should be numeric and evenly distributed β€” if it's skewed (e.g., 90% of values in one range), most mappers will be idle. With --query, you must include WHERE $CONDITIONS β€” Sqoop replaces this with range conditions for each mapper. Always use --password-file instead of --password to avoid credentials in process listings.

sqoop import --incremental β€” Incremental imports

What it does: Imports only new or modified rows, not the entire table.

Syntax:

bash
# APPEND mode: import only rows with ID greater than last imported
sqoop import \
  --connect jdbc:mysql://db.travelco.local:3306/bookings_db \
  --username etl_user \
  --password-file /home/krishna/.sqoop_password \
  --table bookings \
  --incremental append \
  --check-column booking_id \
  --last-value 1000000 \
  --target-dir /data/travelco/sqoop_import/bookings/ \
  --num-mappers 4

# LASTMODIFIED mode: import rows modified since last import
sqoop import \
  --connect jdbc:mysql://db.travelco.local:3306/bookings_db \
  --username etl_user \
  --password-file /home/krishna/.sqoop_password \
  --table bookings \
  --incremental lastmodified \
  --check-column updated_at \
  --last-value "2026-03-24 00:00:00" \
  --target-dir /data/travelco/sqoop_import/bookings/ \
  --merge-key booking_id \
  --num-mappers 4

Interview tip: Two modes β€” know the difference: append is for INSERT-only tables (new rows have higher ID, no updates). lastmodified is for tables with updates (uses a timestamp column). append just adds new files to HDFS. lastmodified with --merge-key does a MapReduce merge of old and new data β€” slower but handles updates. Interview question: "How do you do incremental loads from Oracle to HDFS?" Answer: Sqoop --incremental lastmodified with --check-column on updated_at and --merge-key on primary key. Store --last-value in a Sqoop job or external metadata table.

sqoop export β€” Export to RDBMS

What it does: Exports data from HDFS/Hive back to an RDBMS table.

Syntax:

bash
# Basic export from HDFS to MySQL
sqoop export \
  --connect jdbc:mysql://db.travelco.local:3306/reports_db \
  --username etl_user \
  --password-file /home/krishna/.sqoop_password \
  --table daily_summary \
  --export-dir /data/travelco/reports/daily_summary/ \
  --input-fields-terminated-by ',' \
  --num-mappers 4

# Export with update mode (upsert: insert or update existing rows)
sqoop export \
  --connect jdbc:mysql://db.travelco.local:3306/reports_db \
  --username etl_user \
  --password-file /home/krishna/.sqoop_password \
  --table booking_metrics \
  --export-dir /user/hive/warehouse/bookings_db.db/booking_metrics/ \
  --update-key booking_date \
  --update-mode allowinsert \
  --num-mappers 4

Interview tip: By default, Sqoop export does INSERT. If the target table has a unique key constraint and a row already exists, the export FAILS. Use --update-key with --update-mode allowinsert for upsert behavior. Sqoop export is NOT atomic β€” if it fails halfway, partial data is already in the RDBMS. Solution: export to a staging table, then do a SQL INSERT INTO final_table SELECT * FROM staging_table in a transaction.

sqoop eval β€” Test connection and run queries

What it does: Executes a SQL query on the source database. Used to test connectivity and verify schemas before import.

Syntax:

bash
sqoop eval \
  --connect jdbc:mysql://db.travelco.local:3306/bookings_db \
  --username etl_user \
  --password-file /home/krishna/.sqoop_password \
  --query "SELECT count(*) FROM bookings"

Practical example:

bash
# Test database connectivity
sqoop eval \
  --connect jdbc:mysql://db.travelco.local:3306/bookings_db \
  --username etl_user \
  --password-file /home/krishna/.sqoop_password \
  --query "SELECT 1"

# Check row count before import
sqoop eval \
  --connect jdbc:mysql://db.travelco.local:3306/bookings_db \
  --username etl_user \
  --password-file /home/krishna/.sqoop_password \
  --query "SELECT count(*) FROM bookings WHERE booking_date = '2026-03-25'"

# Check table schema
sqoop eval \
  --connect jdbc:mysql://db.travelco.local:3306/bookings_db \
  --username etl_user \
  --password-file /home/krishna/.sqoop_password \
  --query "DESCRIBE bookings"

Interview tip: Always run sqoop eval first to verify: (1) network connectivity to the database, (2) credentials work, (3) the table exists and schema is as expected. This saves you from debugging a failed 2-hour import that failed in the first second due to wrong credentials.

sqoop list-databases / list-tables β€” Discovery

What it does: Lists available databases or tables in the source RDBMS.

Syntax:

bash
# List all databases
sqoop list-databases \
  --connect jdbc:mysql://db.travelco.local:3306/ \
  --username etl_user \
  --password-file /home/krishna/.sqoop_password

# List all tables in a database
sqoop list-tables \
  --connect jdbc:mysql://db.travelco.local:3306/bookings_db \
  --username etl_user \
  --password-file /home/krishna/.sqoop_password

Practical example:

bash
# Discover what's available on a new database server
sqoop list-databases \
  --connect jdbc:mysql://db.travelco.local:3306/ \
  --username etl_user \
  --password-file /home/krishna/.sqoop_password
# Output:
# information_schema
# bookings_db
# flights_db
# reports_db

# List tables in the bookings database
sqoop list-tables \
  --connect jdbc:mysql://db.travelco.local:3306/bookings_db \
  --username etl_user \
  --password-file /home/krishna/.sqoop_password
# Output:
# bookings
# passengers
# flights
# airports
# booking_audit_log

Interview tip: These commands are useful during the discovery phase of a migration project. When migrating an entire Oracle/MySQL database to Hadoop, first run list-tables to inventory everything, then plan imports table by table with appropriate --split-by columns and file formats.

SECTION 5: QUICK-FIRE INTERVIEW QUESTIONS

πŸ’‘ Interview Tip
These are rapid-fire questions interviewers ask to check your hands-on experience. Answer in 1-2 sentences + the exact command.

Q1: How do you check HDFS cluster health?

Answer: Run hdfs dfsadmin -report β€” it shows total capacity, used space, remaining space, number of live/dead DataNodes, under-replicated blocks, and missing blocks. For a quick filesystem integrity check, run hdfs fsck /.

bash
hdfs dfsadmin -report
hdfs fsck /

Q2: How do you find which DataNode a specific block is on?

Answer: Use hdfs fsck with the -files -blocks -locations flags on the specific file. It shows every block ID and the DataNodes holding each replica.

bash
hdfs fsck /data/travelco/bookings/booking_2026.orc -files -blocks -locations
# Output shows:
# blk_1073741825 len=134217728 [10.0.0.5:9866, 10.0.0.7:9866, 10.0.0.12:9866]
# This block has 3 replicas on DataNodes at 10.0.0.5, 10.0.0.7, 10.0.0.12

Q3: How do you check if NameNode is in safe mode?

Answer: Run hdfs dfsadmin -safemode get. If it returns "Safe mode is ON", no write operations are allowed. The NameNode auto-enters safe mode on startup until enough blocks are reported.

bash
hdfs dfsadmin -safemode get
# Output: Safe mode is ON  (or OFF)

# To exit safe mode manually:
hdfs dfsadmin -safemode leave

Q4: How do you decommission a DataNode?

Answer: Decommissioning is a graceful removal β€” HDFS first replicates all blocks from that node to other nodes before shutting it down. This ensures no data loss.

bash
# Step 1: Add the DataNode hostname to the exclude file
# (configured in hdfs-site.xml as dfs.hosts.exclude)
echo "datanode15.cluster.local" >> /etc/hadoop/conf/dfs.exclude

# Step 2: Tell NameNode to refresh the node list
hdfs dfsadmin -refreshNodes

# Step 3: Monitor decommission progress
hdfs dfsadmin -report
# Look for: Decommission Status: Decommission in progress
# Wait until it says: Decommission Status: Decommissioned

# Step 4: Once decommissioned, stop the DataNode service
# (all blocks have been replicated to other nodes)

Key point: Never just shut down a DataNode without decommissioning. If replication factor is 3 and you kill a node, those blocks temporarily have only 2 replicas. If another node dies before HDFS re-replicates, you lose data.

Q5: How do you check YARN resource usage?

Answer: Use yarn top for real-time monitoring, or yarn node -list to see per-node container counts. For queue-level usage, use yarn queue -status .

bash
# Real-time cluster resource usage
yarn top

# Per-node resource usage
yarn node -list

# Queue-specific usage
yarn queue -status production

# List all running applications consuming resources
yarn application -list

Q6: How do you kill a stuck YARN application?

Answer: First identify the application ID with yarn application -list, then kill it with yarn application -kill. Always check what the application is doing before killing it.

bash
# Find the stuck application
yarn application -list
# Look for apps stuck at 0% progress or running too long

# Kill it
yarn application -kill application_1711350000000_0042

# Verify it's gone
yarn application -status application_1711350000000_0042
# State should be KILLED

Q7: How do you see Hive table partition information?

Answer: Use SHOW PARTITIONS to list all partitions, and DESCRIBE FORMATTED to see partition columns and table metadata including HDFS location.

sql
-- List all partitions
SHOW PARTITIONS bookings;
-- Output:
-- year=2025/month=01
-- year=2025/month=02
-- ...
-- year=2026/month=03

-- See partition columns and full table metadata
DESCRIBE FORMATTED bookings;

-- Check physical HDFS data for a specific partition
-- (from beeline, then check HDFS)
bash
# Verify the HDFS directory structure matches partitions
hdfs dfs -ls -R /user/hive/warehouse/bookings_db.db/bookings/ | head -20

# Check size of each partition
hdfs dfs -du -h /user/hive/warehouse/bookings_db.db/bookings/

MEMORY MAP: COMMAND CATEGORIES

sql
HDFS COMMANDS β€” Remember: "CRUD + Health"
═════════════════════════════════════════
C = Create     β†’ mkdir, touchz, put/copyFromLocal
R = Read       β†’ ls, cat, head, tail, stat, count, du
U = Update     β†’ mv, cp, chmod, chown, setrep
D = Delete     β†’ rm, rm -r
Health         β†’ fsck, balancer, dfsadmin -report, dfsadmin -safemode

YARN COMMANDS β€” Remember: "LASK-N-Q-T"
═══════════════════════════════════════
L = List       β†’ yarn application -list
A = App status β†’ yarn application -status
S = Stop (kill)β†’ yarn application -kill
K = Know logs  β†’ yarn logs -applicationId
N = Nodes      β†’ yarn node -list
Q = Queues     β†’ yarn queue -status
T = Top        β†’ yarn top

HIVE COMMANDS β€” Remember: "SCALD-ME"
═════════════════════════════════════
S = Show       β†’ SHOW DATABASES, TABLES, PARTITIONS
C = Create     β†’ CREATE TABLE (internal, external, partitioned, bucketed)
A = Alter      β†’ ALTER TABLE (add partition, rename, add column)
L = Load       β†’ LOAD DATA, INSERT INTO, INSERT OVERWRITE
D = Describe   β†’ DESCRIBE FORMATTED (the power command)
M = MSCK       β†’ MSCK REPAIR TABLE (sync partitions)
E = Explain    β†’ EXPLAIN (query plan)

SQOOP COMMANDS β€” Remember: "I-I-E-E-L"
═══════════════════════════════════════
I = Import          β†’ sqoop import (full table)
I = Incremental     β†’ sqoop import --incremental (append/lastmodified)
E = Export          β†’ sqoop export (HDFS to RDBMS)
E = Eval            β†’ sqoop eval (test connection)
L = List            β†’ sqoop list-databases, list-tables
βœ… Pro Tip
Final Interview Tip: When asked "What commands do you use daily?", frame it as a senior engineer: "On a typical day, I check cluster health with dfsadmin -report, monitor jobs with yarn application -list and yarn top, optimize Hive queries using EXPLAIN, and manage data pipelines that use Sqoop for RDBMS ingestion with incremental loads. For troubleshooting, hdfs fsck and yarn logs are my go-to tools."
Advanced

Hadoop Scenarios, Labs, and Gotchas

#

Scenario method

Answer First: Diagnose Hadoop incidents as evidence -> scope -> component boundary -> hypothesis -> least-risk fix -> validation. Preserve counters, plans, logs, and filesystem state before changing configuration.

Memory Map: BLOCK-YARN-HIVE -> observe -> isolate -> repair -> prove.

Canonical source guide

Merged from HD_05_Confusions_Labs_MockInterview.md; the legacy source remains unchanged.

Hadoop β€” Confusions, Labs, Gotchas & Mock Interview

πŸ’‘ Interview Tip
The video-free pack. Read this end-to-end and you can walk into any Hadoop/Hive interview without opening YouTube.

🧠 Memory Map: BLOCK-YARN-HIVE

Hadoop interviews boil down to 3 pillars. Remember BYH:

LetterPillarWhat it controls
BBlock storage (HDFS)How data is SPLIT and REPLICATED across nodes
YYARN (resources)How CPU/RAM are SCHEDULED for jobs
HHive (SQL layer)How you QUERY data sitting on HDFS

Master these 3 and you can explain 90% of Hadoop questions.

SECTION 1 β€” TOP 8 CONFUSIONS CLEARED

Confusion #1 β€” HDFS Block vs OS Block vs Split

All three sound similar but are different layers:

ConceptSizeControlled byPurpose
OS block4 KB (typical)Linux/filesystemPhysical disk I/O unit
HDFS block128 MB (default)HDFS configStorage + replication unit
Input split~= HDFS blockInputFormatUnit of work per mapper

Why HDFS block is huge: seeks are expensive. Bigger blocks = less metadata pressure on NameNode + more sequential reads.

Interview one-liner: "HDFS block is the storage unit; split is the computation unit. They're usually the same size so one mapper = one block = no network shuffle for reading."

Confusion #2 β€” NameNode vs DataNode vs Secondary NameNode vs Standby NameNode

Common trap: Secondary β‰  Standby.

NodeRoleHA?
NameNode (active)Holds filesystem metadata (where blocks live)Single point of failure in Hadoop 1
DataNodeStores actual blocks, sends heartbeatsHorizontal scale, N copies
Secondary NameNodePeriodically merges fsimage + edits log. NOT a backup.Housekeeping helper
Standby NameNode (HA)Hot replica of Active NameNode. Can take over instantly.True HA (Hadoop 2+)

Memory trick: Secondary = "Scroll edits" helper. Standby = "Stand-by takeover."

Confusion #3 β€” Replication factor vs Rack awareness

Default replication = 3. But WHERE do those 3 copies go?

πŸ“ Architecture Diagram
Rack 1                      Rack 2
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  DN1    β”‚ β”‚  DN2    β”‚    β”‚  DN3    β”‚ β”‚  DN4    β”‚
β”‚ Block A β”‚ β”‚         β”‚    β”‚ Block A β”‚ β”‚ Block A β”‚
β”‚ (rep 1) β”‚ β”‚         β”‚    β”‚ (rep 2) β”‚ β”‚ (rep 3) β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Common default policy when the writer is a DataNode:

  1. First replica β†’ writer's local node
  2. Second replica β†’ a node on a REMOTE rack
  3. Third replica β†’ a different node on that SAME REMOTE rack

If the writer is not a DataNode, HDFS chooses the first target according to topology and load rather than promising a writer-local replica. Pluggable block-placement policies can also differ from this default.

Why this matters: survives BOTH a node failure AND a full-rack power outage.

Interview one-liner: "With the common default three-replica policy, one copy is local and two copies share a remote rack, reducing cross-rack write traffic while surviving a node or single-rack failure."

Confusion #4 β€” MapReduce vs Tez vs Spark (execution engines under Hive)

Hive can run on 3 engines. Know the differences:

EngineDAG modelIntermediate dataSpeedStill used?
MapReduceRigid map→reduceDisk between every stageSlowestLegacy only
TezFlexible DAGMemory + diskCan reduce stage/materialization overheadCommon with Hive where installed
SparkDAG + optional persistenceMemory + diskStrong for iterative and general data processingSeparate engine; benchmark and govern explicitly

Set in Hive:

sql
SET hive.execution.engine=tez;   -- or mr, spark

Interview gold: "MapReduce materializes job boundaries; Tez can pipeline a DAG and Spark can persist reused data. Both may spill, so prove the benefit from plans and runtime metrics."

Confusion #5 β€” Managed (Internal) vs External Hive Tables

Huge interview favorite.

AspectManaged (internal)External
CREATE syntaxCREATE TABLE ...CREATE EXTERNAL TABLE ...
Data locationHive warehouse pathAny HDFS/S3 path you specify
DROP TABLEDeletes data + metadataDeletes ONLY metadata β€” data stays
Use caseHive owns the dataData shared with other tools
sql
-- Managed: Hive owns everything
CREATE TABLE managed_orders (id INT, amount DOUBLE);
DROP TABLE managed_orders;  -- data GONE

-- External: Hive is just a pointer
CREATE EXTERNAL TABLE ext_orders (id INT, amount DOUBLE)
LOCATION '/data/orders/';
DROP TABLE ext_orders;  -- data SAFE in /data/orders/

Rule of thumb: raw landing zone = EXTERNAL. Curated/derived = MANAGED.

Confusion #6 β€” Partitioning vs Bucketing

Both split data, but differently.

FeaturePartitionBucket
Based onColumn VALUE (e.g., year='2026')HASH of column
Physical layoutEach value β†’ separate directoryEach hash mod N β†’ separate file
CardinalityLow-to-medium (date, country)High (user_id, order_id)
Query benefitPartition pruning (skip dirs)Bucket pruning for JOINs + SMB join
How to setPARTITIONED BY (dt STRING)CLUSTERED BY (id) INTO 10 BUCKETS
sql
-- Partitioned: per-date folders
CREATE TABLE sales (amount DOUBLE)
PARTITIONED BY (sale_date STRING);

-- Bucketed: hash-split within partition
CREATE TABLE users (id BIGINT, name STRING)
CLUSTERED BY (id) INTO 32 BUCKETS;

Interview one-liner: "Partition reduces data scanned by pruning directories. Bucketing enables faster JOINs by co-locating matching keys."

Confusion #7 β€” ORC vs Parquet vs Avro vs Text (file formats)

FormatTypeBest forSchema evolution
TextFile / CSVRow-basedDebuggingPoor
AvroRow-based binaryKafka / streaming writesExcellent
ParquetColumnarAnalytical reads (Spark/Impala)Good
ORCColumnarHive analytical readsGood + indexes

ORC vs Parquet (the real question):

  • ORC β†’ born in Hive, best Hive/Tez perf, has lightweight indexes + bloom filters
  • Parquet β†’ ecosystem standard (Spark, Trino, Athena, BigQuery external)

Decision shortcut, not a rule: ORC is often a strong Hive-centric choice; Parquet often has broad multi-engine interoperability. Confirm engine/version feature support, statistics, codecs, and representative query performance.

Confusion #8 β€” YARN Containers vs Mappers vs Reducers vs Slots (MR1 legacy)

TermEraWhat it is
SlotMR1 (pre-YARN)Fixed map-slot or reduce-slot per node
ContainerYARNDynamic allocation of (RAM, CPU) to any task
MapperMR job phaseReads split, emits (K,V)
ReducerMR job phaseGroups by K, aggregates

Why YARN won: slots were fixed (e.g., 4 map + 2 reduce) β†’ idle slots wasted. Containers reshape on demand.

Tuning: mapreduce.map.memory.mb, yarn.scheduler.maximum-allocation-mb.

SECTION 2 β€” PRACTICE LABS

Lab 1: HDFS basics drill (10 mins, works on any sandbox cluster)

bash
# Create a local test file
echo -e "id,name,amount\n1,alice,100\n2,bob,200\n3,carol,300" > /tmp/orders.csv
cat /tmp/orders.csv
# Output:
# id,name,amount
# 1,alice,100
# 2,bob,200
# 3,carol,300

# Put into HDFS
hdfs dfs -mkdir -p /user/lab/orders
hdfs dfs -put /tmp/orders.csv /user/lab/orders/

# List + check
hdfs dfs -ls /user/lab/orders
hdfs dfs -cat /user/lab/orders/orders.csv

# See block locations (which DataNodes hold replicas)
hdfs fsck /user/lab/orders/orders.csv -files -blocks -locations
# Output shows: block ID, replica count, which DNs store each replica

# Change replication factor
hdfs dfs -setrep -w 2 /user/lab/orders/orders.csv
# -w means WAIT until replication completes

What you proved: You can read/write HDFS, inspect block placement, and control replication.

Lab 2: Hive partition pruning (15 mins)

sql
-- Create partitioned table
CREATE TABLE sales_part (
  order_id INT,
  amount DOUBLE
)
PARTITIONED BY (sale_date STRING)
STORED AS ORC;

-- Load 3 days of data
INSERT INTO sales_part PARTITION (sale_date='2026-04-01')
  VALUES (1, 100.0), (2, 200.0);
INSERT INTO sales_part PARTITION (sale_date='2026-04-02')
  VALUES (3, 150.0), (4, 250.0);
INSERT INTO sales_part PARTITION (sale_date='2026-04-03')
  VALUES (5, 300.0), (6, 400.0);

-- See partition directory structure
SHOW PARTITIONS sales_part;
-- Output:
-- sale_date=2026-04-01
-- sale_date=2026-04-02
-- sale_date=2026-04-03

-- Query WITH pruning (only reads 1 partition)
EXPLAIN
SELECT SUM(amount) FROM sales_part WHERE sale_date = '2026-04-02';
-- Look for "partitions=1" in plan β†’ pruning worked

-- Query WITHOUT pruning (scans all)
EXPLAIN
SELECT SUM(amount) FROM sales_part;
-- Plan shows "partitions=3"

SELECT SUM(amount) FROM sales_part WHERE sale_date = '2026-04-02';
-- Output: 400.0

What you proved: filter on partition column β†’ Hive skips entire directories.

Lab 3: Hive bucketing for fast JOINs (15 mins)

sql
-- Bucketed tables (both bucketed on join key with SAME bucket count)
SET hive.enforce.bucketing=true;

CREATE TABLE users_b (id INT, name STRING)
CLUSTERED BY (id) INTO 4 BUCKETS;

CREATE TABLE orders_b (order_id INT, user_id INT, amount DOUBLE)
CLUSTERED BY (user_id) INTO 4 BUCKETS;

INSERT INTO users_b VALUES (1,'alice'),(2,'bob'),(3,'carol'),(4,'dan');
INSERT INTO orders_b VALUES
  (100,1,50.0),(101,2,75.0),(102,3,120.0),(103,4,200.0),(104,1,30.0);

-- Enable sort-merge-bucket join
SET hive.optimize.bucketmapjoin = true;
SET hive.optimize.bucketmapjoin.sortedmerge = true;
SET hive.input.format = org.apache.hadoop.hive.ql.io.BucketizedHiveInputFormat;

SELECT u.name, SUM(o.amount)
FROM users_b u JOIN orders_b o ON u.id = o.user_id
GROUP BY u.name;
-- Output:
-- alice | 80.0
-- bob   | 75.0
-- carol | 120.0
-- dan   | 200.0

What you proved: matching bucket counts on join keys = no shuffle needed (SMB join).

SECTION 3 β€” LIVE VISUAL ANIMATIONS

Animation 1: HDFS write path (client β†’ 3 replicas)

πŸ“ Architecture Diagram
   CLIENT
     β”‚
     β”‚ 1. ask NameNode: "where do I write block A?"
     β–Ό
 NAMENODE ────returns: [DN1, DN2, DN3]
     β”‚
     β”‚
     β–Ό
   CLIENT ──packet stream──▢ DN1 ──forward──▢ DN2 ──forward──▢ DN3
                              β”‚                β”‚                β”‚
                              └─ackβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                      β”‚
                                      β–Ό
                                   CLIENT

Key: client writes to ONE DataNode; the pipeline forwards between DNs. Ack travels back through the pipeline.

Animation 2: MapReduce word count (classic)

πŸ“ Architecture Diagram
INPUT:  "the cat sat on the mat"
          β”‚
          β–Ό
     [ SPLIT ]
          β”‚
          β–Ό
 β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
 β”‚    MAPPER      β”‚  emits (word, 1) for each word
 β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
          β”‚
          β–Ό
  (the,1) (cat,1) (sat,1) (on,1) (the,1) (mat,1)
          β”‚
          β–Ό
     [ SHUFFLE + SORT ]  groups by key
          β”‚
          β–Ό
  (cat,[1]) (mat,[1]) (on,[1]) (sat,[1]) (the,[1,1])
          β”‚
          β–Ό
 β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
 β”‚    REDUCER     β”‚  sums values per key
 β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
          β”‚
          β–Ό
OUTPUT:  cat=1  mat=1  on=1  sat=1  the=2

Shuffle is the expensive step β€” network I/O across all nodes. Spark's advantage: keep intermediate data in memory.

Animation 3: YARN container lifecycle

πŸ“ Architecture Diagram
  CLIENT                       RESOURCE MANAGER
    β”‚                                β”‚
    β”‚ 1. submit app                  β”‚
    β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Άβ”‚
    β”‚                                β”‚
    β”‚ 2. RM allocates Container-0   β”‚
    β”‚    for ApplicationMaster       β”‚
    β”‚                                β”‚
    β”‚                  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
    β”‚                  β–Ό             β”‚
    β”‚              NODE MANAGER      β”‚
    β”‚              β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”‚
    β”‚              β”‚ Container-0β”‚    β”‚
    β”‚              β”‚ (AppMaster)β”‚    β”‚
    β”‚              β””β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”˜    β”‚
    β”‚                    β”‚           β”‚
    β”‚                    β”‚ 3. request more containers (map/reduce tasks)
    β”‚                    β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Άβ”‚
    β”‚                    β”‚           β”‚
    β”‚                    β”‚ 4. RM grants containers on various NMs
    β”‚                    β”‚           β”‚
    β”‚                    β–Ό           β”‚
    β”‚              NM1 NM2 NM3  ...  β”‚
    β”‚             [C1][C2][C3]       β”‚

Terms:

  • ResourceManager (cluster-wide) β€” grants containers
  • ApplicationMaster (per-app) β€” negotiates containers for its tasks
  • NodeManager (per-node) β€” launches/monitors containers

SECTION 4 β€” GOTCHAS (REAL PRODUCTION FAILURES)

Gotcha 1: Small files problem

Millions of tiny files (< 128 MB) overwhelm NameNode memory (each file = ~150 bytes metadata). Fix: compact into larger files; use HAR, SequenceFile, or Hive INSERT OVERWRITE to rewrite.

Gotcha 2: SELECT COUNT(*) on huge external table with no stats = slow

Without stats, Hive counts row-by-row. Fix: ANALYZE TABLE t COMPUTE STATISTICS; β€” then Hive returns from metastore.

Gotcha 3: Data skew in reducer (one key has 90% of data)

One reducer gets all skewed keys β†’ stuck at 99%. Fix: SET hive.groupby.skewindata=true; (two-stage aggregation) OR salt the key manually.

Gotcha 4: Dynamic partition inserts fail with "too many partitions"

Default limits: 100 per node, 1000 per query. Fix:

sql
SET hive.exec.dynamic.partition=true;
SET hive.exec.dynamic.partition.mode=nonstrict;
SET hive.exec.max.dynamic.partitions=10000;
SET hive.exec.max.dynamic.partitions.pernode=1000;

Gotcha 5: DROP TABLE on External table still deletes metadata (not data)

If you CREATE EXTERNAL TABLE pointing to same location later, you must MSCK REPAIR TABLE to recover partition metadata.

Gotcha 6: NameNode safe mode on startup

After restart NN enters safe mode until 99.9% of blocks report. Writes are blocked. Fix: hdfs dfsadmin -safemode leave (only if you understand why).

SECTION 5 β€” TIMED MOCK INTERVIEW (45 MIN)

Q1 (8 min) β€” "Design HDFS storage for 10 TB/day of clickstream logs"

Strong answer:

  1. Ingest raw JSON β†’ HDFS landing zone (external Hive table), partitioned by dt=YYYY-MM-DD
  2. Compaction job converts to ORC/Parquet, partitioned by date + hour
  3. Retention policy: raw = 7 days, curated = 2 years (lifecycle script)
  4. Replication factor 3; place hot data on an SSD tier where the cluster's HDFS storage policies and hardware support it
  5. File size target: 256–512 MB per file (avoid small files)

Q2 (6 min) β€” "Hive query takes 2 hours. How to debug?"

Checklist:

  1. EXPLAIN EXTENDED query β†’ look at # partitions scanned + stages
  2. Check if table is ORC/Parquet (text is slow)
  3. Is it skewed? SELECT key, COUNT(*) FROM t GROUP BY key ORDER BY 2 DESC LIMIT 10
  4. Try Tez/Spark engine instead of MR
  5. Compute stats: ANALYZE TABLE t COMPUTE STATISTICS FOR COLUMNS
  6. Enable vectorization: SET hive.vectorized.execution.enabled=true;
  7. Enable CBO: SET hive.cbo.enable=true;

Q3 (5 min) β€” "Difference between NameNode HA and NameNode Federation"

  • HA (High Availability): Active + Standby NameNodes. Both know the SAME namespace. Standby takes over on failure. Solves: single point of failure.
  • Federation: MULTIPLE NameNodes, each owns a DIFFERENT namespace (e.g., /finance, /marketing). DataNodes serve all. Solves: NameNode scalability (metadata memory pressure).

You can combine them: HA within each federated namespace.

Q4 (4 min) β€” "How does Hive integrate with other tools (Spark, Presto)?"

Hive's Metastore is the secret: it's just a database (MySQL/Postgres) holding table β†’ location mappings.

  • Spark reads Hive Metastore β†’ can read/write Hive tables without Hive runtime
  • Presto/Trino β†’ reads Metastore + SerDe, executes with its own engine
  • So: Hive tables live in storage, Metastore is the directory, any engine can query.

Q5 (4 min) β€” "When would you NOT use Hadoop?"

  • Low-latency (< 1 second) queries β†’ use Druid, Trino, or data warehouse
  • Random record lookup β†’ use HBase or KV store
  • Small data (< 1 TB) β†’ use Postgres / cloud warehouse
  • Update-heavy workloads β†’ HDFS is append-only
  • Real-time stream processing β†’ use Flink/Spark Streaming/Kafka Streams

SECTION 6 β€” FINAL READINESS CHECKLIST

  • Can I draw HDFS write pipeline with 3 replicas and rack awareness?
  • Do I know NameNode vs DataNode vs Secondary vs Standby?
  • Can I explain MapReduce word count phases (Map β†’ Shuffle β†’ Reduce)?
  • Do I know 4 differences between Managed and External Hive tables?
  • Can I explain when to use partition vs bucket?
  • Do I know ORC vs Parquet tradeoffs?
  • Can I list 3 Hive performance tunables (engine, vectorization, CBO, stats)?
  • Do I know YARN Resource Manager / App Master / Node Manager roles?
  • Can I recite 3 solutions for the small-files problem?
  • Can I name 3 scenarios where Hadoop is the WRONG choice?

If all 10 = YES, you're Hadoop interview-ready.

Remember BLOCK-YARN-HIVE. Everything else is details.

Intermediate

Hadoop Interview Questions

#

Hadoop interview question index

Use this as a prompt deck: answer aloud, then follow the owner link. It intentionally stores original question wording and pointers only; canonical explanations, commands, and labs stay with their concept owners.

Answer pattern

  1. Give the direct answer first.
  2. Draw the data, metadata, or control path.
  3. Name the failure mode or trade-off.
  4. Cite the command, counter, log, or plan that would verify it.

Canonical Q-HAD index

Q-HAD-001: What is HDFS Architecture? Explain every component.

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_01_HDFS_YARN_MapReduce.md#L22.

Q-HAD-002: How does HDFS WRITE work? Step-by-step.

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_01_HDFS_YARN_MapReduce.md#L83.

Q-HAD-003: How does HDFS READ work? (Data Locality)

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_01_HDFS_YARN_MapReduce.md#L150.

Q-HAD-004: What is NameNode High Availability (HA)? β€” CRITICAL QUESTION

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_01_HDFS_YARN_MapReduce.md#L182.

Q-HAD-005: What is HDFS Federation? When do you need it?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_01_HDFS_YARN_MapReduce.md#L270.

Q-HAD-006: Q12 INTERVIEW ANSWER β€” "How to optimize a 6-hour MapReduce job?"

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_01_HDFS_YARN_MapReduce.md#L975.

Q-HAD-007: What is HDFS?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_01_Quick_Recall.md#L52.

Q-HAD-008: What does NameNode store?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_01_Quick_Recall.md#L55.

Q-HAD-009: What does DataNode store?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_01_Quick_Recall.md#L58.

Q-HAD-010: What is replication factor?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_01_Quick_Recall.md#L61.

Q-HAD-011: What is the default HDFS block size?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_01_Quick_Recall.md#L64.

Q-HAD-012: What is the small files problem?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_01_Quick_Recall.md#L67.

Q-HAD-013: Solutions to the small files problem?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_01_Quick_Recall.md#L70.

Q-HAD-014: Explain the HDFS Write Path step by step.

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_01_Quick_Recall.md#L77.

Q-HAD-015: Explain the HDFS Read Path.

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_01_Quick_Recall.md#L80.

Q-HAD-016: What happens when a DataNode dies?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_01_Quick_Recall.md#L83.

Q-HAD-017: SECTION 1: HDFS β€” SCENARIO QUESTIONS

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_01_Quick_Recall.md#L88.

Q-HAD-018: A DataNode is dead and your replication factor is 3. What happens?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_01_Quick_Recall.md#L90.

Q-HAD-019: Someone accidentally deleted a critical file from HDFS. How do you recover?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_01_Quick_Recall.md#L93.

Q-HAD-020: NameNode is in safe mode and cluster is not accepting writes. Fix it?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_01_Quick_Recall.md#L96.

Q-HAD-021: What is NameNode Single Point of Failure (SPOF)?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_01_Quick_Recall.md#L103.

Q-HAD-022: How does NameNode HA work?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_01_Quick_Recall.md#L106.

Q-HAD-023: What is split-brain in NameNode HA? How does fencing prevent it?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_01_Quick_Recall.md#L109.

Q-HAD-024: What are JournalNodes?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_01_Quick_Recall.md#L112.

Q-HAD-025: What is YARN?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_01_Quick_Recall.md#L119.

Q-HAD-026: YARN components β€” explain each.

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_01_Quick_Recall.md#L122.

Q-HAD-027: What is a Container in YARN?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_01_Quick_Recall.md#L125.

Q-HAD-028: YARN Scheduler types β€” when to use each?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_01_Quick_Recall.md#L128.

Q-HAD-029: What happens when a NodeManager dies?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_01_Quick_Recall.md#L131.

Q-HAD-030: Explain MapReduce phases in order.

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_01_Quick_Recall.md#L138.

Q-HAD-031: What is the Shuffle phase? Why is it the most expensive?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_01_Quick_Recall.md#L141.

Q-HAD-032: What is a Combiner? Rules for using it?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_01_Quick_Recall.md#L144.

Q-HAD-033: Why can't you use a Combiner for calculating Average?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_01_Quick_Recall.md#L147.

Q-HAD-034: What is a Partitioner?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_01_Quick_Recall.md#L150.

Q-HAD-035: What is Speculative Execution?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_01_Quick_Recall.md#L153.

Q-HAD-036: What is mapreduce.task.io.sort.mb and why does it matter?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_01_Quick_Recall.md#L160.

Q-HAD-037: How do you compress map output and why?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_01_Quick_Recall.md#L163.

Q-HAD-038: GZIP vs Snappy vs LZO β€” when to use each?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_01_Quick_Recall.md#L166.

Q-HAD-039: What is JVM Reuse and when should you use it?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_01_Quick_Recall.md#L169.

Q-HAD-040: How to fix a slow MapReduce job that has 99 reducers done but 1 still running for hours?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_01_Quick_Recall.md#L172.

Q-HAD-041: What is the optimal number of reducers formula?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_01_Quick_Recall.md#L175.

Q-HAD-042: How to check HDFS file system health?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_01_Quick_Recall.md#L182.

Q-HAD-043: How to check cluster usage?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_01_Quick_Recall.md#L185.

Q-HAD-044: How to check safe mode status?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_01_Quick_Recall.md#L188.

Q-HAD-045: How to run the HDFS balancer?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_01_Quick_Recall.md#L191.

Q-HAD-046: What is Hive?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_02_Hive_Ecosystem.md#L48.

Q-HAD-047: SCENARIO 1: Data deleted manually from HDFS (most common interview question!)

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_02_Hive_Ecosystem.md#L539.

Q-HAD-048: SCENARIO 2: New data added to HDFS but Hive doesn't see it

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_02_Hive_Ecosystem.md#L569.

Q-HAD-049: SCENARIO 3: Hive query is very slow β€” debug and fix

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_02_Hive_Ecosystem.md#L590.

Q-HAD-050: What is HBase?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_02_Hive_Ecosystem.md#L618.

Q-HAD-051: HBase Row Key Design β€” CRITICAL INTERVIEW TOPIC

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_02_Hive_Ecosystem.md#L669.

Q-HAD-052: SECTION 13: DESIGN SCENARIO β€” End-to-End Travel Pipeline

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_02_Hive_Ecosystem.md#L930.

Q-HAD-053: "Design a Hadoop pipeline to process 100 million daily flight bookings"

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_02_Hive_Ecosystem.md#L932.

Q-HAD-054: What is the Hive Metastore?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_02_Quick_Recall.md#L52.

Q-HAD-055: Internal vs External table β€” key difference?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_02_Quick_Recall.md#L55.

Q-HAD-056: When to use External table?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_02_Quick_Recall.md#L58.

Q-HAD-057: What is a Hive partition?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_02_Quick_Recall.md#L61.

Q-HAD-058: Common partition column trap?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_02_Quick_Recall.md#L64.

Q-HAD-059: Static vs Dynamic partitioning?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_02_Quick_Recall.md#L67.

Q-HAD-060: Sqoop wrote new data to HDFS but Hive shows 0 rows. Fix?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_02_Quick_Recall.md#L74.

Q-HAD-061: Someone ran hdfs dfs -rm -r on a Hive partition. Now what?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_02_Quick_Recall.md#L77.

Q-HAD-062: Hive query runs for hours. Top 5 things to check?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_02_Quick_Recall.md#L80.

Q-HAD-063: What does hive.execution.engine=tez do?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_02_Quick_Recall.md#L87.

Q-HAD-064: What does vectorization do?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_02_Quick_Recall.md#L90.

Q-HAD-065: What is a Map Join and when does Hive use it?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_02_Quick_Recall.md#L93.

Q-HAD-066: ORDER BY vs SORT BY β€” when to use each?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_02_Quick_Recall.md#L96.

Q-HAD-067: What is MSCK REPAIR TABLE?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_02_Quick_Recall.md#L99.

Q-HAD-068: What is ORC predicate pushdown?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_02_Quick_Recall.md#L102.

Q-HAD-069: What is hive.groupby.skewindata=true?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_02_Quick_Recall.md#L105.

Q-HAD-070: What is HBase and when do you use it?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_02_Quick_Recall.md#L112.

Q-HAD-071: What is a Row Key in HBase?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_02_Quick_Recall.md#L115.

Q-HAD-072: Why is timestamp as row key bad?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_02_Quick_Recall.md#L118.

Q-HAD-073: HBase write path?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_02_Quick_Recall.md#L121.

Q-HAD-074: What is Sqoop incremental import?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_02_Quick_Recall.md#L128.

Q-HAD-075: What does --num-mappers do in Sqoop?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_02_Quick_Recall.md#L131.

Q-HAD-076: Sqoop export data safety issue?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_02_Quick_Recall.md#L134.

Q-HAD-077: Oozie Workflow vs Coordinator job?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_02_Quick_Recall.md#L141.

Q-HAD-078: What's the advantage of Oozie Coordinator data trigger?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_02_Quick_Recall.md#L144.

Q-HAD-079: What does ZooKeeper do in Hadoop?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_02_Quick_Recall.md#L151.

Q-HAD-080: Why must ZooKeeper have an odd number of nodes?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_02_Quick_Recall.md#L154.

Q-HAD-081: Flume Memory Channel vs File Channel?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_02_Quick_Recall.md#L157.

Q-HAD-082: SECTION 7: MOCK INTERVIEW β€” Top 10 Questions for 10-Year Engineers

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_03_Performance_Security_Migration.md#L747.

Q-HAD-083: "How did you handle data skew in a production pipeline?"

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_03_Performance_Security_Migration.md#L771.

Q-HAD-084: "HDFS NameNode HA failed. Active NameNode is dead, Standby is not taking over. Debug?"

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_03_Performance_Security_Migration.md#L787.

Q-HAD-085: "How would you migrate our 500 TB Hadoop cluster to Databricks on Azure?"

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_03_Performance_Security_Migration.md#L814.

Q-HAD-086: "What are the biggest performance problems you've seen in Hadoop at scale?"

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_03_Performance_Security_Migration.md#L849.

Q-HAD-087: What is Kerberos in Hadoop?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_03_Quick_Recall.md#L39.

Q-HAD-088: What is a keytab file?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_03_Quick_Recall.md#L42.

Q-HAD-089: What happens if a Kerberos ticket expires during a long-running job?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_03_Quick_Recall.md#L45.

Q-HAD-090: What does Apache Ranger do?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_03_Quick_Recall.md#L48.

Q-HAD-091: What does Apache Knox do?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_03_Quick_Recall.md#L51.

Q-HAD-092: Kerberos vs Ranger β€” what's the difference?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_03_Quick_Recall.md#L54.

Q-HAD-093: NameNode heap sizing rule?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_03_Quick_Recall.md#L61.

Q-HAD-094: What is dfs.namenode.handler.count?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_03_Quick_Recall.md#L64.

Q-HAD-095: What setting has the biggest MapReduce performance impact?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_03_Quick_Recall.md#L67.

Q-HAD-096: What is mapreduce.reduce.shuffle.parallelcopies?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_03_Quick_Recall.md#L70.

Q-HAD-097: Why is G1GC preferred over default CMS GC for NameNode?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_03_Quick_Recall.md#L73.

Q-HAD-098: What is short-circuit read in HDFS?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_03_Quick_Recall.md#L76.

Q-HAD-099: What is data skew symptom in MapReduce?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_03_Quick_Recall.md#L83.

Q-HAD-100: How do you fix skew in MapReduce?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_03_Quick_Recall.md#L86.

Q-HAD-101: How do you fix skew in Hive?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_03_Quick_Recall.md#L89.

Q-HAD-102: Three migration patterns from Hadoop to cloud?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_03_Quick_Recall.md#L96.

Q-HAD-103: What is DistCp?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_03_Quick_Recall.md#L99.

Q-HAD-104: Why use -skipcrccheck with DistCp to S3/ADLS?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_03_Quick_Recall.md#L102.

Q-HAD-105: What is Databricks Lakebridge?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_03_Quick_Recall.md#L105.

Q-HAD-106: Hadoop MapReduce vs Spark β€” key difference?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_03_Quick_Recall.md#L108.

Q-HAD-107: What is Erasure Coding in Hadoop 3?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_03_Quick_Recall.md#L115.

Q-HAD-108: When to use Erasure Coding vs Replication?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_03_Quick_Recall.md#L118.

Q-HAD-109: New YARN features in Hadoop 3?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_03_Quick_Recall.md#L121.

Q-HAD-110: NameNode memory formula?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_03_Quick_Recall.md#L128.

Q-HAD-111: DataNode hardware recommendation?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_03_Quick_Recall.md#L131.

Q-HAD-112: EXPLAIN β€” Query execution plan

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_04_Commands_Reference.md#L1060.

Q-HAD-113: How do you check HDFS cluster health?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_04_Commands_Reference.md#L1358.

Q-HAD-114: How do you find which DataNode a specific block is on?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_04_Commands_Reference.md#L1369.

Q-HAD-115: How do you check if NameNode is in safe mode?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_04_Commands_Reference.md#L1382.

Q-HAD-116: How do you decommission a DataNode?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_04_Commands_Reference.md#L1396.

Q-HAD-117: How do you check YARN resource usage?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_04_Commands_Reference.md#L1421.

Q-HAD-118: How do you kill a stuck YARN application?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_04_Commands_Reference.md#L1441.

Q-HAD-119: How do you see Hive table partition information?

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_04_Commands_Reference.md#L1460.

Q-HAD-120: Hadoop β€” Confusions, Labs, Gotchas & Mock Interview

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_05_Confusions_Labs_MockInterview.md#L1.

Q-HAD-121: Confusion #1 β€” HDFS Block vs OS Block vs Split

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_05_Confusions_Labs_MockInterview.md#L23.

Q-HAD-122: Confusion #2 β€” NameNode vs DataNode vs Secondary NameNode vs Standby NameNode

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_05_Confusions_Labs_MockInterview.md#L39.

Q-HAD-123: Confusion #3 β€” Replication factor vs Rack awareness

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_05_Confusions_Labs_MockInterview.md#L54.

Q-HAD-124: Confusion #4 β€” MapReduce vs Tez vs Spark (execution engines under Hive)

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_05_Confusions_Labs_MockInterview.md#L78.

Q-HAD-125: Confusion #5 β€” Managed (Internal) vs External Hive Tables

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_05_Confusions_Labs_MockInterview.md#L97.

Q-HAD-126: Confusion #6 β€” Partitioning vs Bucketing

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_05_Confusions_Labs_MockInterview.md#L123.

Q-HAD-127: Confusion #7 β€” ORC vs Parquet vs Avro vs Text (file formats)

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_05_Confusions_Labs_MockInterview.md#L149.

Q-HAD-128: Confusion #8 β€” YARN Containers vs Mappers vs Reducers vs Slots (MR1 legacy)

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_05_Confusions_Labs_MockInterview.md#L166.

Q-HAD-129: Lab 1: HDFS basics drill (10 mins, works on any sandbox cluster)

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_05_Confusions_Labs_MockInterview.md#L183.

Q-HAD-130: Lab 2: Hive partition pruning (15 mins)

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_05_Confusions_Labs_MockInterview.md#L216.

Q-HAD-131: Lab 3: Hive bucketing for fast JOINs (15 mins)

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_05_Confusions_Labs_MockInterview.md#L260.

Q-HAD-132: Gotcha 1: Small files problem

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_05_Confusions_Labs_MockInterview.md#L393.

Q-HAD-133: Gotcha 2: SELECT COUNT(*) on huge external table with no stats = slow

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_05_Confusions_Labs_MockInterview.md#L399.

Q-HAD-134: Gotcha 3: Data skew in reducer (one key has 90% of data)

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_05_Confusions_Labs_MockInterview.md#L405.

Q-HAD-135: Gotcha 4: Dynamic partition inserts fail with "too many partitions"

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_05_Confusions_Labs_MockInterview.md#L411.

Q-HAD-136: Gotcha 5: DROP TABLE on External table still deletes metadata (not data)

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_05_Confusions_Labs_MockInterview.md#L423.

Q-HAD-137: Gotcha 6: NameNode safe mode on startup

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_05_Confusions_Labs_MockInterview.md#L428.

Q-HAD-138: SECTION 5 β€” TIMED MOCK INTERVIEW (45 MIN)

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_05_Confusions_Labs_MockInterview.md#L434.

Q-HAD-139: Q1 (8 min) β€” "Design HDFS storage for 10 TB/day of clickstream logs"

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_05_Confusions_Labs_MockInterview.md#L436.

Q-HAD-140: Q2 (6 min) β€” "Hive query takes 2 hours. How to debug?"

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_05_Confusions_Labs_MockInterview.md#L447.

Q-HAD-141: Q3 (5 min) β€” "Difference between NameNode HA and NameNode Federation"

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_05_Confusions_Labs_MockInterview.md#L460.

Q-HAD-142: Q4 (4 min) β€” "How does Hive integrate with other tools (Spark, Presto)?"

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_05_Confusions_Labs_MockInterview.md#L469.

Q-HAD-143: Q5 (4 min) β€” "When would you NOT use Hadoop?"

Answer owner: Open the canonical concept or runnable pattern.

Alternate source wording: content/hadoop/HD_05_Confusions_Labs_MockInterview.md#L478.

90 seconds

Practice sprint

Close the atlas. Rebuild the map.

Name the path from API to files, then explain where shuffle, skew, and serialization enter the system.

Open interview prompts