The head chef who never cooks
It is the college fest, and the canteen must serve 3,000 plates of pav bhaji in two hours. Arjun Sir takes Riya and Kabir into the kitchen. Eight cooks are working at eight stoves. One person, the head chef, is not cooking at all. She holds a clipboard, calls out orders, and keeps looking at every stove.
Sir, why isn't the head chef cooking? With nine people cooking, we'd be faster.
Watch what happens when cook 3 burns his hand. Who notices? Who gives his order to cook 4? Who knows that 2,400 plates are done and 600 are left?
The head chef. Without her, the cooks would make the same order twice, or forget some.
Exactly. A cluster works the same way. Many computers, the workers, do the real work. One or two computers, the masters, keep track of everything: which worker is alive, which piece of work is where, what is finished.
And the workers tell the master they are still alive?
Every few seconds. It's called a heartbeat. In Hadoop, a worker that stays silent for long enough is treated as dead, and its work is given to someone else. That's the whole lesson today: what makes a group of computers a cluster, and how masters and workers share the job.
What is a cluster?
A cluster is a set of independent computers (nodes) connected by a network and managed by software so that they work together as a single system. In the master–worker (also called master–slave or coordinator–worker) architecture, one or more master nodes hold the cluster's metadata, monitor worker health through periodic heartbeats and assign work, while many worker nodes store data and execute tasks. Hadoop uses this architecture twice: in HDFS (NameNode and DataNodes) and in YARN (ResourceManager and NodeManagers).
A cluster is a team of computers that behaves like one big computer. The master is the team leader: it remembers where everything is and gives out the work. The workers do the work and keep saying “I'm alive and here's my progress”. If a worker goes quiet, the master gives its work to another worker.
Words you'll meet in this lesson
Masters and workers in Hadoop
| Storage (HDFS) | Master: NameNode (file names, blocks, locations). Workers: DataNodes (store the blocks). |
|---|---|
| Compute (YARN) | Master: ResourceManager (hands out CPU and memory). Workers: NodeManagers (run tasks in containers). |
| Per job | An ApplicationMaster runs on one worker and manages that one job's tasks. |
| HDFS heartbeat interval | every 3 seconds by default (dfs.heartbeat.interval) |
| DataNode declared dead after | about 10 minutes 30 seconds without a heartbeat, by default |
| Typical worker node usage | One machine usually runs both a DataNode and a NodeManager, so the compute sits next to the data. |
Clusters at three levels
Beginner A team with a leader
- One leader (master) and many members (workers).
- The leader keeps a list: who is present, who is doing what, what is done.
- Members report in regularly (heartbeat). Someone who stops reporting is assumed absent, and their work is given to others.
- To the outside world, the team looks like one unit: you give the job to the leader, not to each member.
Intermediate What the master keeps, and what the workers send
- The master's table: worker list, last heartbeat time of each, resources free on each, which task is on which worker, and (for storage) which piece of data is on which worker.
- The heartbeat: “I'm alive”, plus useful numbers: free disk, free memory, running tasks, finished tasks. In HDFS, DataNodes also send a full block report (the list of blocks on their disks) every few hours, and on start-up.
- The reply: the master often answers a heartbeat with instructions: “start this task”, “copy this block to node 9”, “delete that block”.
- Timeouts: the master doesn't declare a worker dead after one missed heartbeat; networks hiccup. It waits for a timeout, then acts.
Advanced Design choices behind Hadoop's clusters
- Master–worker vs peer-to-peer: Hadoop uses masters because one source of truth for metadata is simple and consistent. Systems like Cassandra are peer-to-peer (no master); every node is equal and they agree using gossip, which avoids a master bottleneck but makes coordination harder.
- The master can be a bottleneck: the NameNode keeps all metadata in RAM (very roughly 150 bytes per file, directory or block object), so millions of tiny files can exhaust it. That's the “small files problem” (Module 7).
- The master can be a SPOF: early Hadoop had one NameNode. Hadoop 2 added High Availability: an active and a standby NameNode with automatic failover via ZooKeeper (Module 7).
- Shared-nothing lets the cluster grow just by adding nodes, unlike HPC clusters that share a central storage system.
- Workers are cattle, masters are pets: a dead worker is replaced without fuss; masters are protected and backed up carefully.
Exam tip: For “Explain the master–slave architecture of Hadoop”, draw two pictures: NameNode + DataNodes (storage) and ResourceManager + NodeManagers (compute). Mention heartbeats, what the master stores (metadata), what workers do (store blocks, run tasks), and that the master is a potential single point of failure solved by HA.
Kinds of clusters, and two ways to organise them
Big data cluster
Shared-nothing nodes, each with its own disks. Data is spread over the nodes and processed where it is stored. Hadoop, Spark, Kafka.
This courseHPC cluster
High-performance computing for science and weather. Very fast networks and a central shared file system; programs (often MPI) work closely together.
SupercomputersHigh-availability (HA) cluster
Two or more machines where a standby takes over if the active one fails. Used for databases and for Hadoop's own NameNode.
FailoverLoad-balanced web cluster
Many identical web servers behind a load balancer; each request goes to any free server. Used by shopping and ticketing sites.
Web trafficContainer cluster
Kubernetes runs many small applications (containers) across nodes. It also has a master (control plane) and workers.
KubernetesMaster–worker vs peer-to-peer
| Master–worker | Peer-to-peer (masterless) | |
|---|---|---|
| Who decides | The master | All nodes agree among themselves |
| Metadata | In one place: simple and consistent | Spread over all nodes |
| Weak point | Master can be a bottleneck or SPOF (solved with HA) | Coordination is more complex |
| Examples | HDFS, YARN, Spark, HBase, Kubernetes | Cassandra, Riak, BitTorrent |
Older books and some exam papers say “master–slave”. Today most projects say master–worker, primary–replica or coordinator–worker. They mean the same structure. Use the term your exam expects.
How a master and its workers run one job
Workers join and register
When a worker starts, it contacts the master: “I am
The master adds a row to its worker table. In HDFS, the DataNode also sends a block report: the list of every block on its disks.dn4, on/rack2, with 32 cores, 256 GB RAM and 144 TB of disk.”Heartbeats every few seconds
The master only stores when it last heard from each worker. Silence for a few seconds is normal. Silence past the timeout means trouble.last_seen = {"dn1": 120.0, "dn2": 121.5, "dn3": 119.0} # time of last heartbeat (seconds) now = 122.0 for w, t in last_seen.items(): print(w, "silent for", now - t, "s")dn1 silent for 2.0 s dn2 silent for 0.5 s dn3 silent for 3.0 sA job arrives and is split into tasks
A user submits a job on the master. The job is divided into many small, independent tasks, for example one per 128 MB piece of the input.
Small tasks are the secret: if one fails, only that small piece is redone, not the whole job.The master assigns tasks to free workers
Each worker gets as many tasks as it has free slots. The rest wait in a queue.
In YARN, a “slot” is a container: a fixed amount of memory and CPU on one node. The master picks workers that are free and, ideally, already hold the task's data (Lesson 1.5).Workers report progress
Heartbeats now carry “task 7: 60% done”, “task 3: finished”.
This is how you seemap 45% reduce 0%in your terminal: the master adds up progress from all workers.A worker dies: its tasks are re-run
Worker 3 loses power. Its heartbeats stop. After the timeout, the master marks it dead and gives its unfinished tasks to other workers.
The job finishes a little later, but it finishes, and nobody had to do anything by hand. That is the core promise of a cluster built from ordinary machines.
A job with a dying worker: what Riya sees, and what the master does
Riya runs a job on a 3-worker cluster. Halfway through, worker 2 crashes. Left: her terminal. Right: the master's view.
- Riya submits a job from the edge node. It is split into 6 tasks, one per piece of input.
- The job starts. No task has finished yet.
- Half the tasks are done: map 50%.
- Progress stops for a while. To Riya it looks stuck. Something has happened on the cluster.
- A message says a task attempt FAILED: “Container released on a lost node”. Then progress moves again.
- The job completes successfully. The failure was handled entirely by the cluster.
- The master splits the job into 6 tasks and puts them in a queue. Each worker has room for one task at a time here.
- The master gives T1, T2, T3 to the three workers. T4–T6 wait.
- T1 and T3 finish. Worker 2 reported T2 done too, but its output lives on worker 2's disk. T4, T5, T6 start.
- Worker 2 loses power. Its heartbeats stop. The master waits for the timeout before deciding, because a short silence can be a network hiccup.
- Timeout: worker 2 is dead. Its task T5 was unfinished, and T2's output was on the dead disk, so both are re-run (T2′, T5′) on healthy workers.
- Every task is done. The job completes. The cluster healed itself.
Try it yourself: break a worker during a job
Now do it for real in the Cluster Playground. Run the job, then stop a node while its task bars are filling.
Masters and workers everywhere
1. HDFS: NameNode and DataNodes
The NameNode knows every file's blocks and where they are. DataNodes store the blocks and send heartbeats every 3 seconds. You'll build and break this in Modules 5–7.
2. YARN: ResourceManager and NodeManagers
Every Hadoop and Spark-on-YARN job asks the ResourceManager for containers, and NodeManagers run them. One cluster can serve hundreds of jobs from different teams at once (Module 11).
3. Spark: driver and executors
A Spark application has a driver (the master for that job) that plans the work and many executors (workers) that process the data. Same pattern, one level down.
4. Kubernetes runs your favourite apps
Food delivery and ride apps often run on Kubernetes clusters: a control plane (masters) decides where each container runs; worker nodes run them and are replaced when they fail.
5. Cassandra: a cluster with no master
Some databases, like Apache Cassandra, are peer-to-peer: every node is equal and any node can answer a request. It is a useful contrast when an interviewer asks why Hadoop chose masters.
Examples are simplified. Real deployments add more components (backups, monitoring, security) around these basic roles.
A tiny master and its workers in Python
This program plays the master. It has a queue of tasks and three workers, and gives each free worker the next task, round after round, until the queue is empty. Then try the challenges, including a worker that dies.
from collections import deque
queue = deque(["T1", "T2", "T3", "T4", "T5", "T6", "T7"])
workers = ["W1", "W2", "W3"]
done = {w: [] for w in workers}
round_no = 0
while queue:
round_no += 1
for w in workers:
if queue:
done[w].append(queue.popleft())
print("after round", round_no, "->", done)queue = deque([...])Adeque(double-ended queue) gives the next item quickly withpopleft(): first in, first out, like a real job queue.done = {w: [] for w in workers}The master's table: for each worker, the list of tasks it has run.while queue:Keep going while tasks are waiting. An empty deque counts asFalse.
Run it on your PC: a master with real worker processes
Your computer can be a tiny cluster too: one master process and one worker process per CPU core. Python's ProcessPoolExecutor keeps a task queue and gives tasks to whichever worker is free, exactly like a cluster master. Save this as workers.py and run it.
Watch tasks go to different worker processes
# workers.py: a master process hands out tasks to worker processes on your own PC
import os, time
from concurrent.futures import ProcessPoolExecutor, as_completed
def task(n):
"""One task: count the even numbers in its own range of 20 lakh numbers."""
start = n * 2_000_000
evens = sum(1 for x in range(start, start + 2_000_000) if x % 2 == 0)
return n, os.getpid(), evens
if __name__ == "__main__": # this part runs only in the master
workers = os.cpu_count()
print("Master PID", os.getpid(), "starting", workers, "workers")
t0 = time.time()
with ProcessPoolExecutor(max_workers=workers) as pool:
futures = [pool.submit(task, n) for n in range(8)] # 8 tasks in the queue
total = 0
for f in as_completed(futures):
n, pid, evens = f.result()
total += evens
print(f" task {n} done by worker PID {pid}")
print("Total evens:", total)
print(f"Time: {time.time() - t0:.1f} s")
# In a terminal: python workers.pyRecorded on a 2-core machine, so there are 2 workers. With 8 cores you'll see 8 different worker PIDs, and the order of finished tasks will change from run to run: whichever worker is free takes the next task. The if __name__ == "__main__": line matters on Windows: without it, each worker would start its own master.
The master's timeout check, one line at a time
The master loops over its table of last heartbeats. Watch silent change for each worker and see which ones end up in the dead list.
Worked examples: real problems, solved and traced in memory
Three jobs a cluster master really does: share out work, notice dead workers, and recover their tasks. Each solution runs live, and the trace shows the master's table changing in memory.
Share 7 input files among 3 workers
Problem statement
A report job has 7 input files. Give them to 3 workers in turn (file 1 to W1, file 2 to W2, …) and print each worker's list.
files part-1 … part-7 · workers W1, W2, W3
W1 ['part-1', 'part-4', 'part-7'] W2 ['part-2', 'part-5'] W3 ['part-3', 'part-6']
Approach
- Create an empty list for each worker.
- For file number
i, the worker isi % 3: 0, 1, 2, 0, 1, 2, 0. - Print the lists.
Solution: run it live
What happens in memory, step by step
Recorded from a real Python run: press Next to execute one line at a time. Watch variables change in each frame, and lists and dictionaries (numbered #1, #2 …) fill up as objects.
Which DataNodes are dead?
Problem statement
HDFS declares a DataNode dead after 630 seconds (10 min 30 s) without a heartbeat. Given the last heartbeat time of each node and the current time, print the dead nodes and how many are alive.
now = 2000 s · dn1 1998, dn2 1200, dn3 1999, dn4 1500, dn5 1360
Dead : ['dn2', 'dn5'] Alive: 3 of 5
Approach
- Silence = now − last heartbeat.
- Dead if silence > 630 seconds.
- Count the rest as alive.
Solution: run it live
What happens in memory, step by step
Recorded from a real Python run: press Next to execute one line at a time. Watch variables change in each frame, and lists and dictionaries (numbered #1, #2 …) fill up as objects.
Re-run a dead worker's tasks on the least-loaded workers
Problem statement
Workers report their running tasks. W2 has died. Move each of its tasks, one at a time, to whichever live worker currently has the fewest tasks, marking it as a new attempt.
W1 [T1, T4] · W2 [T2, T5, T6] · W3 [T3] · dead W2
{'W1': ['T1', 'T4', "T5'"], 'W3': ['T3', "T2'", "T6'"]}Approach
- Remove the dead worker from the table and keep its task list.
- For each lost task, find the live worker with the fewest tasks using
min(…, key=…). - Add the task there as attempt 2 (written with ′).
Solution: run it live
What happens in memory, step by step
Recorded from a real Python run: press Next to execute one line at a time. Watch variables change in each frame, and lists and dictionaries (numbered #1, #2 …) fill up as objects.
Check yourself
Quick revision
Lesson 1.2 in one screen
- Cluster: networked nodes that work together as one system.
- Master coordinates (metadata, health, assignment). Workers store data and run tasks.
- HDFS: NameNode + DataNodes. YARN: ResourceManager + NodeManagers. Per job: ApplicationMaster.
- Heartbeat: worker → master every few seconds (HDFS: 3 s). The reply can carry instructions.
- Dead after a timeout (HDFS default ≈ 10 min 30 s), not after one missed heartbeat.
- Jobs → many small tasks: parallel, and a failure only redoes one piece.
- Dead worker → its tasks are re-run elsewhere automatically.
- Master can be a bottleneck and a SPOF: Hadoop 2+ uses an active and a standby NameNode.
- Hadoop clusters are shared-nothing. Cassandra is a peer-to-peer contrast.
Interview and viva questions
Explain the master–slave (master–worker) architecture of Hadoop.
Hadoop has two master–worker systems. In HDFS, the NameNode stores the namespace and the location of every block, and DataNodes store the blocks and send heartbeats and block reports. In YARN, the ResourceManager allocates cluster resources and NodeManagers launch and monitor containers on each worker; each application also gets an ApplicationMaster that manages its own tasks. A worker node normally runs both a DataNode and a NodeManager.
What is a heartbeat and why is it needed?
A small periodic message from a worker to the master. It tells the master the worker is alive and carries status such as free space or task progress. Without heartbeats the master could not detect failures and would keep sending work to dead nodes. The master replies with commands, for example to copy or delete blocks.
What happens when a DataNode stops sending heartbeats?
After the timeout (about 10.5 minutes by default) the NameNode marks it dead, stops sending it requests, and re-replicates every block that now has fewer copies than required, using the surviving replicas. Running tasks on that node fail and are rescheduled by the ApplicationMaster.
Why not declare a node dead immediately after one missed heartbeat?
Short pauses are common: garbage collection, a busy disk, a switch restarting. Declaring a node dead triggers heavy work (re-copying all its blocks over the network). A timeout avoids false alarms that would waste bandwidth.
Is the master a single point of failure in Hadoop?
In Hadoop 1, yes: one NameNode. Since Hadoop 2, HDFS High Availability runs an active and a standby NameNode sharing edits through JournalNodes, with ZooKeeper-based automatic failover. The ResourceManager can also run in HA mode.
Practice problems
Small programs that do the master's job: count, check health, assign and recover. The business problems are taken from real cluster operations.
Count workers and masters
Given a list of (node, role), print how many nodes have each role.
[("nn1","master"),("rm1","master"),("dn1","worker"),("dn2","worker"),("dn3","worker")]{'master': 2, 'worker': 3}Show solution and explanation
nodes = [("nn1", "master"), ("rm1", "master"), ("dn1", "worker"), ("dn2", "worker"), ("dn3", "worker")]
count = {}
for name, role in nodes:
count[role] = count.get(role, 0) + 1
print(count)How it works: count.get(role, 0) returns 0 the first time a role is seen. Real clusters have a handful of masters and many workers.
Heartbeats per hour
A DataNode sends a heartbeat every 3 seconds. How many does one node send per hour, and how many does the NameNode receive per hour from 500 nodes?
3 s interval · 500 nodes
One node: 1200 500 nodes: 600000
Show solution and explanation
per_node = 3600 // 3
print("One node:", per_node)
print("500 nodes:", per_node * 500)How it works: 1,200 per node per hour; 6 lakh per hour for 500 nodes. Heartbeats are tiny, but this is one reason the master must be efficient.
The HDFS dead-node timeout
The timeout is 2 × recheck interval + 10 × heartbeat interval. Calculate it in seconds for the defaults: recheck 300 s, heartbeat 3 s. Print it as minutes and seconds.
recheck 300 s · heartbeat 3 s
630 seconds = 10 min 30 s
Show solution and explanation
t = 2 * 300 + 10 * 3
print(t, "seconds =", t // 60, "min", t % 60, "s")How it works: 630 s = 10 min 30 s. Administrators can lower the recheck interval to detect failures faster.
Rounds needed
A job has N tasks and the cluster has W workers with S slots each. Each round, every slot runs one task. Print how many rounds (“waves”) are needed for N = 50, W = 6, S = 4.
N = 50, W = 6, S = 4
3 waves
Show solution and explanation
import math
N, W, S = 50, 6, 4
print(math.ceil(N / (W * S)), "waves")How it works: 24 tasks run at once, so 50 tasks need 3 waves (24 + 24 + 2). Hadoop users call these map “waves”.
Find the slow worker
Given each worker's finished task times in seconds, print the worker whose average is more than 1.5 times the cluster average.
W1 [30, 32, 31] · W2 [29, 30] · W3 [95, 90] · W4 [33]
W3 is slow: 92 s vs cluster 46 s
Show solution and explanation
times = {"W1": [30, 32, 31], "W2": [29, 30], "W3": [95, 90], "W4": [33]}
all_t = [t for ts in times.values() for t in ts]
avg = sum(all_t) / len(all_t)
for w, ts in times.items():
a = sum(ts) / len(ts)
if a > 1.5 * avg:
print(w, "is slow:", round(a), "s vs cluster", round(avg), "s")How it works: A worker that is alive but much slower is a straggler (bad disk, overheating). Hadoop can launch a backup copy of its tasks elsewhere: speculative execution.
Blacklist a flaky node
Tasks failed on these nodes in the last hour. Print the nodes with 3 or more failures, which the scheduler should stop using.
["dn4","dn2","dn4","dn7","dn4","dn2","dn9","dn2","dn2"]
Stop using: ['dn2', 'dn4'] {'dn4': 3, 'dn2': 4, 'dn7': 1, 'dn9': 1}Show solution and explanation
failures = ["dn4", "dn2", "dn4", "dn7", "dn4", "dn2", "dn9", "dn2", "dn2"]
count = {}
for n in failures:
count[n] = count.get(n, 0) + 1
bad = sorted(n for n, c in count.items() if c >= 3)
print("Stop using:", bad, count)How it works: MapReduce does something similar: if many tasks of a job fail on one node, that node is blacklisted for the job.
Will the job finish before 6 am?
A nightly job has 400 tasks of about 6 minutes each. The cluster has 20 workers with 8 slots each. One worker usually fails during the night, losing 8 running tasks that must be redone. The job starts at 1 am. Print the estimated finish time.
400 tasks × 6 min · 20 workers × 8 slots · 8 tasks redone
Waves: 3 | minutes: 18 Finish at about 1:18 am
Show solution and explanation
import math
tasks, minutes = 400 + 8, 6
slots = 19 * 8 # plan for one worker lost
waves = math.ceil(tasks / slots)
total = waves * minutes
print("Waves:", waves, "| minutes:", total)
print(f"Finish at about {1 + total // 60}:{total % 60:02d} am")How it works: Plan with one worker fewer and the redone tasks included. 408 tasks on 152 slots = 3 waves = 18 minutes, well before 6 am.
How much does a dead node cost in re-copying?
A dead DataNode held 60 TB of block replicas. The cluster can spend 2 GB/s in total on re-replication. How many hours until every block has its full number of copies again?
60 TB lost · 2 GB/s
8.5 hours
Show solution and explanation
tb = 60
gb_per_s = 2
hours = tb * 1024 / gb_per_s / 3600
print(round(hours, 1), "hours")How it works: About 8.5 hours of network and disk work. This is why the NameNode does not declare nodes dead too quickly, and why very large nodes make recovery slow.
Real-world scenario questions (asked in company interviews)
Interview situations about masters, workers and heartbeats. Think of your answer, then compare it with the model answer.
“The NameNode server crashed. Is our data gone?”
At 2 am the only NameNode of a 40-node cluster crashes. The DataNodes are all fine. A manager panics: “Have we lost all the data?”
The interviewer is checking: do you know what the master stores, what the workers store, and why masters need protection?
Show a strong answer
- The file contents are safe: the blocks are on the DataNodes' disks.
- But without the NameNode, nobody knows which blocks form which file, so the file system is unavailable until it comes back.
- The NameNode's metadata is saved on its own disk (the fsimage and edit log). Restart it on the same or a new machine from that saved metadata, and the DataNodes re-register with block reports.
- Long-term fix: NameNode High Availability with a standby that takes over automatically, and backups of the metadata directories.
Avoid saying: “The Secondary NameNode will take over.” It doesn't. It only helps with checkpoints (Module 5).
The job is stuck at 99% for 20 minutes
A sales job always reaches 99% in 10 minutes, then waits 20 more minutes for the last task. The node running that task is alive and sending heartbeats.
The interviewer is checking: can you tell a slow worker (straggler) from a dead one, and do you know the remedies?
Show a strong answer
- Check which task is slow and on which node. If one node is always slow (failing disk, overheating), it is a straggler: fix or remove it. Speculative execution runs a backup copy of the slow task on another node and uses whichever finishes first.
- If it is always the same piece of data, it is data skew: one task gets far more data than others (for example one huge city or one product). Fix the partitioning or split the hot key.
Avoid: “Add more nodes.” That doesn't help one big task.
Make the dead-node timeout 10 seconds?
A teammate wants failures detected faster, so he proposes changing HDFS to declare a DataNode dead after 10 seconds of silence instead of about 10 minutes.
The interviewer is checking: do you understand the trade-off between fast detection and false alarms?
Show a strong answer
- A 10-second timeout would mark nodes dead during harmless pauses: a long garbage-collection pause, a switch reboot, a busy disk.
- Each false “death” makes the NameNode re-copy all of that node's blocks (often many TB), flooding the network. When the node returns, the extra copies must be deleted again.
- Reading data is already protected: clients and tasks simply use another replica if one node does not respond. Re-replication can safely wait a few minutes.
- If faster detection is truly needed, lower it moderately and test, and look at stale-node settings that avoid slow nodes without declaring them dead.
Avoid: treating faster as always better. Detection speed has a cost.
“Why does Hadoop need a master at all?”
The interviewer says: “Cassandra works without a master. Why didn't Hadoop do the same?”
The interviewer is checking: do you understand the trade-offs, not just the definitions?
Show a strong answer
- HDFS must know exactly which blocks make up each file and where they are. One master gives a single, consistent answer and makes decisions (placement, re-replication) simple.
- The master is also where scheduling decisions are easy: one place sees all free resources.
- The costs: the master can become a bottleneck (memory for metadata) and a single point of failure. Hadoop answers with High Availability and federation.
- Cassandra is built for a different job: always-on reads and writes of small records, where avoiding a master improves availability.
Avoid: saying one design is simply “better”. Each fits a different problem.