Safe mode

Every time a NameNode starts, it spends a little while in safe mode: it can list files but won't change anything until DataNodes have reported where the blocks are. This lesson shows real restarts with all, none and some DataNodes running, explains the threshold and extension behind the countdown, and teaches you to read a stuck safe mode as a symptom rather than an obstacle to force away.

Module 5 · HDFS architecture⏱ 22 minBeginner → IntermediateReal restart timelinesThreshold calculatorRuns in your browser (Python)8 practice problems
1 The story

“Name node is in safe mode”

Kabir restarts the NameNode and, without waiting, uploads a file. HDFS refuses: put: Cannot create file … Name node is in safe mode. He tries again a minute later and it works. Riya does a nastier experiment: she stops all four DataNodes and restarts the NameNode. Now hdfs dfs -ls lists every file with its size, but hdfs dfs -cat fails with Zero blocklocations … Name node is in safe mode. “It knows the files but can't find them?”

1. load fsimage+ replay edits 2. SAFE MODEread-only; wait forblock reports (99.9%) 3. extension30 more seconds 4. normalwrites allowed Real restart in our lab: safe mode for about 40 seconds, then OFF automatically. myphatshala.in
Arjun Sir

Remember: after a restart the NameNode knows every file from its fsimage and edits, but not where the blocks are. That map comes only from DataNode block reports. Until enough blocks have been reported, the NameNode protects you: it allows reading the namespace, but no changes, and it won't start re-replicating blocks just because their DataNodes haven't reported yet.

Kabir

So it's waiting for the roll call.

Arjun Sir

Exactly. When 99.9% of blocks have at least one reported replica, it waits 30 more seconds for the stragglers, then leaves safe mode by itself. With no DataNodes at all, the threshold can never be reached, so it waits for ever, unless an admin forces it out, which you should do only when you understand why it's stuck.

2 Definition

Safe mode

Formal definition (write this in exams)

Safe mode is a read-only state of the NameNode in which the namespace can be read but not modified (no create, delete, rename or append) and no blocks are replicated or deleted. The NameNode enters it automatically at start-up, after loading the fsimage and edit log, while it collects block reports from DataNodes. It leaves automatically when (1) the fraction of blocks that have at least dfs.namenode.replication.min (1) reported replicas reaches dfs.namenode.safemode.threshold-pct (0.999), and (2) the number of live DataNodes reaches dfs.namenode.safemode.min.datanodes (0), followed by an extension period of dfs.namenode.safemode.extension (30,000 ms). Administrators can control it with hdfs dfsadmin -safemode get | enter | leave | wait; manual safe mode (entered with enter) must be left manually.

In simple words

Right after starting, HDFS is in a careful read-only mode until DataNodes have reported almost all blocks. Then it waits 30 seconds more and opens for writing. Admins can also switch it on and off.

Words you'll meet in this lesson

Safe modeNameNode read-only state: list and read metadata, no changes, no replication.
ThresholdShare of blocks that must be reported (with ≥ 1 replica): 0.999 by default.
ExtensionExtra wait after reaching the threshold: 30 s by default.
Safe blockA block with at least the minimum number of reported replicas (1).
SafeModeExceptionThe error a write gets during safe mode.
-safemode waitBlocks a script until safe mode is off. Use it after starting HDFS.
Manual safe modeEntered with -safemode enter, e.g. for saveNamespace; never leaves on its own.
Missing blockA block with no live replica. Enough of them keep the NameNode in safe mode.

Safe mode settings (Hadoop 3.5.0 defaults)

threshold-pct0.999: the NameNode computes the needed count as the whole number part of total × 0.999
extension30,000 ms
min.datanodes0 (“The minimum number of live datanodes is not required”)
replication.min1 replica counts a block as safe
Allowed in safe models, stat, cat/get of blocks already reported, getconf, fsck, saveNamespace
Refusedput, mkdir, rm, mv, setrep, append; no replication or deletion of blocks

Safe mode at three levels

Pick your level. New to this? Start at Beginner and climb.

Beginner The morning roll call

  • The school opens, but the principal doesn't start classes until almost every teacher has signed in.
  • Students can look at the timetable (read the namespace) but no room changes are allowed (no writes).
  • When 99.9% have signed in, she waits a little for latecomers, then rings the bell.

Intermediate Why it exists

  • Without it, a restarting NameNode would see “no replicas” for every block and immediately order lakhs of copies, then delete them again as reports arrived.
  • It stops clients from writing while the NameNode can't yet choose good DataNodes or confirm space.
  • The 30 s extension avoids leaving the moment the threshold is touched, while a few DataNodes are still reporting.
  • Scripts that start HDFS and then write data should run hdfs dfsadmin -safemode wait first.

Advanced Stuck in safe mode: what it tells you

  • Stuck means too many blocks have no reported replica: DataNodes down, disks lost, or a wrong dfs.datanode.data.dir.
  • The threshold uses a whole-number count: with 9 blocks, int(9 × 0.999) = 8, so one missing block is tolerated (we saw exactly this). With 10 lakh blocks, only 1,000 may be missing.
  • -safemode leave lets the cluster work, but files with missing blocks stay unreadable; first bring DataNodes back or accept the loss.
  • Low disk space on the NameNode's metadata disks (dfs.namenode.resource.du.reserved) also puts it into safe mode.

Exam tip: “What is safe mode in Hadoop?”: a read-only state of the NameNode at start-up while it receives block reports; no modifications or replication; exits automatically when 99.9% of blocks have the minimum replicas, after a 30 s extension. Commands: hdfs dfsadmin -safemode get|enter|leave|wait.

3 Types and ways to use it

Ways into and out of safe mode

Automatic (start-up)ManualResource low
How it startsEvery NameNode starthdfs dfsadmin -safemode enterMetadata disk nearly full
How it endsThreshold + extension reachedOnly -safemode leaveFree space, then leave
Typical useWaiting for block reportssaveNamespace, maintenance, freezing changes before upgradesProtecting the edit log from running out of disk
Seen in our labAbout 40 s after each restartAround saveNamespace (Lesson 5.4)Not tested

The four safemode commands

-safemode get

Prints “Safe mode is ON” or “OFF”.

Check

-safemode wait

Waits until it is OFF. Put it in start-up scripts before any writes.

Scripts

-safemode enter

Freeze changes manually (stays until you leave).

Admin

-safemode leave

Force it off. Only after you know why it's on.

Careful

The NameNode explains itself. The web UI's Overview, or the Safemode field in /jmx, says how many blocks have been reported, how many are needed, and how many seconds are left. Read it before forcing anything.

4 Step by step

Restart the NameNode and watch safe mode

On the Module 5 lab cluster (8 blocks, 4 DataNodes). The NameNode's own explanation is read from its /jmx “Safemode” field.

  1. Read the settings

    for k in dfs.namenode.safemode.threshold-pct dfs.namenode.safemode.extension \
             dfs.namenode.safemode.min.datanodes dfs.namenode.replication.min; do
      echo "$k = $(docker compose exec namenode hdfs getconf -confKey $k)"
    done
    dfs.namenode.safemode.threshold-pct = 0.999f dfs.namenode.safemode.extension = 30000 dfs.namenode.safemode.min.datanodes = 0 dfs.namenode.replication.min = 1
    The f in 0.999f just means a floating-point number in the defaults file.
  2. Restart the NameNode with all DataNodes up

    docker restart lab5-namenode-1
    # every few seconds:
    docker compose exec namenode hdfs dfsadmin -safemode get
    t=5s Call From namenode/172.19.0.3 to namenode:8020 failed on connection exception: java.net.ConnectException: Connection refused t=10s Safe mode is ON | The reported blocks 8 has reached the threshold 0.9990 of total blocks 8. … In safe mode extension. Safe mode will be turned off automatically in 28 seconds. t=15s Safe mode is ON | … Safe mode will be turned off automatically in 23 seconds. t=28s Safe mode is ON | … Safe mode will be turned off automatically in 10 seconds. t=38s Safe mode is ON | … Safe mode will be turned off automatically in 0 seconds. t=43s Safe mode is OFF
    For the first seconds the NameNode isn't even listening yet (loading fsimage and edits). Then the four DataNodes report within moments, the threshold is reached, and the 30 s extension counts down.
  3. Try to write during safe mode

    docker compose exec namenode hdfs dfs -put /tmp/canteen_orders.csv data/during_safemode.csv
    put: Cannot create file/user/hadoop/data/during_safemode.csv._COPYING_. Name node is in safe mode.
    Writes are refused (SafeModeException). put first writes to a temporary ._COPYING_ name, which is what it tried to create.
  4. Restart with no DataNodes at all

    docker stop lab5-datanode-1 lab5-datanode-2 lab5-datanode-3 lab5-datanode-4
    docker restart lab5-namenode-1
    docker compose exec namenode hdfs dfsadmin -safemode get
    docker compose exec namenode hdfs dfs -ls data
    docker compose exec namenode hdfs dfs -cat data/canteen_orders.csv
    Safe mode is ON NameNode says: The minimum number of live datanodes is not required. Safe mode will be turned off automatically once the thresholds have been reached. Found 2 items -rw-r--r-- 3 hadoop supergroup 4692009 2026-10-21 06:49 data/canteen_1mb.csv -rw-r--r-- 3 hadoop supergroup 4692009 2026-10-21 06:49 data/canteen_orders.csv cat: Zero blocklocations for /user/hadoop/data/canteen_orders.csv. Name node is in safe mode.
    The namespace is all there (from the fsimage), so ls works. But no block has a known location, so the data can't be read. The threshold can't be reached, so it waits.
  5. Bring the DataNodes back

    docker start lab5-datanode-1 lab5-datanode-2 lab5-datanode-3 lab5-datanode-4
    docker compose logs namenode | grep "STATE\*"
    t=13s Safe mode is ON | … Safe mode will be turned off automatically once the thresholds have been reached. t=19s Safe mode is ON | The reported blocks 8 has reached the threshold 0.9990 of total blocks 8. … turned off automatically in 24 seconds. t=37s Safe mode is ON | … turned off automatically in 5 seconds. t=49s Safe mode is OFF INFO StateChange:406 - STATE* Safe mode is OFF INFO StateChange:411 - STATE* Leaving safe mode after 70 secs
    As soon as the DataNodes register and report, the threshold is met, the extension runs, and the NameNode leaves safe mode on its own: 70 s after its start in total.
  6. A missing block: what safe mode does and doesn't catch

    docker compose exec namenode hdfs dfs -D dfs.replication=1 -put /tmp/canteen_orders.csv data/scratch_r1.csv
    # its only replica is on lab5-datanode-1: stop it, restart the NameNode
    docker stop lab5-datanode-1
    docker restart lab5-namenode-1
    docker compose logs namenode | grep -A1 "Safe mode ON"
    docker compose exec namenode hdfs fsck / | grep -E "MISSING|Missing blocks|Status"
    STATE* Safe mode ON, in safe mode extension. The reported blocks 8 has reached the threshold 0.9990 of total blocks 9. … /user/hadoop/data/scratch_r1.csv: MISSING 1 blocks of total size 4692009 B. Status: CORRUPT Missing blocks: 1
    The threshold is a whole number: int(9 × 0.999) = 8, so 8 of 9 blocks was “enough” and the NameNode left safe mode with a block missing. fsck reports it. Starting datanode-1 again made the file HEALTHY. On a big cluster the threshold is tighter (1,000 missing blocks out of 10 lakh), but safe mode is not a data-integrity check: fsck is.

Don't make hdfs dfsadmin -safemode leave a habit. If the NameNode is waiting, it is usually waiting for DataNodes that hold real data. Forcing it out turns “not reported yet” into “missing”, and can start unnecessary re-replication.

5 See it happen

A NameNode restart with no DataNodes, then four

Step 4 and step 5 from the real lab, frame by frame.

Safe mode from start to finish 6 steps
What you see riya@lab : ~/hdfs-lab $ docker restart lab5-namenode-1Call From namenode … to namenode:8020failed … Connection refused $ hdfs dfsadmin -safemode getSafe mode is ON$ hdfs dfs -ls data… 4692009 … data/canteen_orders.csv $ hdfs dfs -cat data/canteen_orders.csvcat: Zero blocklocations for …Name node is in safe mode.$ hdfs dfs -put …put: … Name node is in safe mode. $ docker start lab5-datanode-{1..4}The reported blocks 8 has reachedthe threshold 0.9990 of total blocks 8. In safe mode extension. Safe modewill be turned off automaticallyin 24 seconds. STATE* Safe mode is OFFSTATE* Leaving safe mode after 70 secs$ hdfs dfs -cat … | head -1order_id,item,amount myphatshala.in
Behind the screen NameNode memory namespace: 13 inodes ✓ block map: 0 of 8 located block map: 8 of 8 located loading fsimage + edits… SAFE MODE (read-only) normal: read + write needed: int(8 × 0.999) = 7 blocksreported: 0 needed: 7 · reported: 8 ✓ extension: 30 s countdown dn-1 dn-2 dn-3 dn-4 all stopped register + full block reports myphatshala.in
6 Real-world use

Safe mode at work

safemode waitthen load

1. Start-up scripts that wait

Automation that restarts a cluster and then loads data runs hdfs dfsadmin -safemode wait before the first write, instead of failing with SafeModeException or sleeping for a guessed time.

Start HDFS→safemode wait→Run jobs
stuck at 97%find the DataNodes

2. Diagnosing a stuck restart

When a large cluster stays in safe mode, admins compare reported vs total blocks in the NameNode UI and look for DataNodes that haven't registered (often a failed disk mount or a whole rack still powering up) before deciding anything.

Stuck→Which nodes missing?→Fix, don't force
enter → upgradefreeze changes

3. Freezing the namespace for maintenance

Before upgrades or metadata backups, admins enter safe mode so nothing changes, run saveNamespace, copy the metadata, and only then proceed.

safemode enter→saveNamespace + backup→Upgrade
disk 99% fullNameNode protects

4. When the NameNode's own disk fills

If the disk holding the edit log runs low, the NameNode enters safe mode to avoid corrupting its metadata. Free space on that disk, then leave safe mode.

Metadata disk full→Safe mode→Free space, leave

Simplified; organisations differ in tools and policies.

7 Run the code

Will the NameNode leave safe mode?

This function applies the safe mode rules: the needed count is the whole-number part of total blocks × threshold, plus the minimum number of live DataNodes. Run it on the real cases from Part 4.

def safe_mode(total_blocks, reported, live_dns, threshold=0.999, min_dns=0):
    needed = int(total_blocks * threshold)
    blocks_ok = reported >= needed
    dns_ok = live_dns >= min_dns
    if blocks_ok and dns_ok:
        return f"reported {reported}/{total_blocks} (needed {needed}): leaves after 30 s extension"
    return f"reported {reported}/{total_blocks} (needed {needed}): STAYS in safe mode"

print(safe_mode(8, 8, 4))       # restart, all DataNodes up
print(safe_mode(8, 0, 0))       # restart, no DataNodes
print(safe_mode(9, 8, 3))       # replication-1 file on a stopped DataNode
print(safe_mode(10_00_000, 998_000, 400))
reported 8/8 (needed 7): leaves after 30 s extension reported 0/8 (needed 7): STAYS in safe mode reported 8/9 (needed 8): leaves after 30 s extension reported 998000/1000000 (needed 999000): STAYS in safe mode
  • needed = int(total_blocks * threshold)int() keeps only the whole-number part: int(9 × 0.999) = int(8.991) = 8. That is why 8 of 9 was enough in our lab.
  • dns_ok = live_dns >= min_dnsdfs.namenode.safemode.min.datanodes is 0 by default, so this never blocks unless an admin sets it.

Run it on your PC: follow a NameNode restart

This script restarts the lab NameNode, then every few seconds asks for the safe mode state and reads the NameNode's own explanation from /jmx. Save it as safemode_watch.py in the hdfs-lab folder and run it while the DataNodes are up.

Safe mode from restart to OFF

# safemode_watch.py: restart the NameNode and follow safe mode until it ends.
# Run in the hdfs-lab folder while the cluster is up.
import json
import re
import subprocess
import time

URL = "http://namenode:9870/jmx?qry=Hadoop:service=NameNode,name=NameNodeInfo"

def nn(*cmd):
    return subprocess.run(["docker", "compose", "exec", "-T", "namenode", *cmd],
                          capture_output=True, text=True).stdout.strip()

def explanation():
    try:
        return json.loads(nn("curl", "-s", URL))["beans"][0]["Safemode"] or "(off)"
    except (ValueError, KeyError, IndexError):
        return "(NameNode not answering yet)"

subprocess.run(["docker", "restart", "lab5-namenode-1"], capture_output=True)
start = time.time()
while time.time() - start < 120:
    state = nn("hdfs", "dfsadmin", "-safemode", "get").splitlines()
    state = state[-1] if state else "(no answer)"
    why = explanation()
    blocks = re.search(r"reported blocks (\d+).*?total blocks (\d+)", why)
    left = re.search(r"in (\d+) seconds", why)
    detail = (f"reported {blocks.group(1)}/{blocks.group(2)} blocks" if blocks else why[:40]) + \
             (f", off in {left.group(1)} s" if left else "")
    print(f"t={time.time() - start:3.0f}s  {state:24} {detail}")
    if "OFF" in state:
        break
    time.sleep(5)

# In the hdfs-lab folder:
#   python3 safemode_watch.py
t= 4s (no answer) (NameNode not answering yet) t= 11s Safe mode is ON reported 8/8 blocks, off in 25 s t= 18s Safe mode is ON reported 8/8 blocks, off in 18 s t= 25s Safe mode is ON reported 8/8 blocks, off in 11 s t= 32s Safe mode is ON reported 8/8 blocks, off in 4 s t= 39s Safe mode is OFF (off)

Real output. Stop one or all DataNodes before running it to see the other cases from Part 4; with none running, the loop ends after 2 minutes with safe mode still ON.

8 Line by line

The NameNode counting block reports

Follow the safe-block count as three DataNodes report, and see the moment the threshold is reached.

Worked examples: real problems, solved and traced in memory

Three safe mode questions that come up in operations: how long a restart will keep the cluster read-only, how much missing data the threshold tolerates, and when forcing safe mode off is reasonable. Each runs live and is traced in memory.

Example 1BeginnerOperations · timing

How long will the cluster be read-only?

Problem statement

A NameNode takes 6 minutes to load its fsimage and edits. DataNodes then report over 4 minutes, with the threshold reached at 3 min 50 s. The extension is 30 s. How long after the restart can jobs write again?

Input
load 6 min · threshold at 3 min 50 s after reports start · extension 30 s
Expected output
writes allowed after 10 min 20 s

Approach

  1. Start of safe mode = after loading.
  2. Threshold time = load + 230 s.
  3. Add the extension.

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.

Example 2IntermediateRisk · threshold

How much data could be missing when it leaves?

Problem statement

A cluster has 2 crore blocks averaging 100 MB. With the default threshold, how many blocks (and roughly how much data) may still have no reported replica when the NameNode leaves safe mode?

Input
2,00,00,000 blocks · 100 MB each · 0.999
Expected output
up to 20,000 blocks, about 1.9 TB

Approach

  1. Missing allowed = total − int(total × 0.999).
  2. Data = missing × 100 MB.
  3. Convert to TB.

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.

Example 3AdvancedDecision · force leave

Should we force safe mode off?

Problem statement

Write a small decision helper: given total and reported blocks, the number of DataNodes expected and registered, and whether those missing DataNodes are known to be permanently lost, recommend “wait”, “investigate”, or “leave and accept loss”.

Input
case A: 1,000,000 / 990,000, 400 expected / 380 up, not lost · case B: same, nodes lost
Expected output
A: investigate: 20 DataNodes not registered yet
B: leave safe mode, then run fsck and restore/regenerate missing data

Approach

  1. If DataNodes are still missing and might return → wait/investigate.
  2. If they are permanently lost and data is accepted as lost (or other replicas exist elsewhere) → leave, then fsck.
  3. Print the reasoning.

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.

9 Quiz and revision

Check yourself

Quick revision

Lesson 5.6 in one screen

  • Safe mode = NameNode read-only: metadata reads OK; no create/delete/rename; no replication.
  • Entered automatically at start-up (after loading fsimage + edits) until block reports arrive.
  • Leaves when reported safe blocks ≥ int(total × 0.999) and live DNs ≥ min (0), then after a 30 s extension.
  • Real lab: ~40 s in safe mode per restart; with no DataNodes it waits for ever.
  • Commands: hdfs dfsadmin -safemode get | wait | enter | leave.
  • Manual (enter) safe mode only ends with leave. Also entered when metadata disk is low.
  • Errors: put → “Name node is in safe mode”; cat → “Zero blocklocations”.
  • Stuck = missing DataNodes/blocks. Investigate before forcing; check fsck after leaving.

Interview and viva questions

What is safe mode in HDFS?

A read-only state of the NameNode. At start-up it loads the namespace and then waits for DataNodes to report their blocks. Until enough blocks are reported, it allows reading metadata but no modifications and no replication, so it doesn't act on incomplete information.

How do I leave safe mode?

Normally you just wait: it ends automatically when 99.9% of blocks are reported plus 30 seconds. Use hdfs dfsadmin -safemode wait in scripts. hdfs dfsadmin -safemode leave forces it off, which is appropriate only after you know why it is stuck (or after a manual enter).

Why is my NameNode stuck in safe mode?

Usually because DataNodes holding a significant share of blocks have not registered: they are down, their disks are not mounted, or dfs.datanode.data.dir points to the wrong folder. It can also be caused by low disk space on the NameNode's metadata directories.

Can I read files in safe mode?

You can read metadata (ls, stat). File data can be read for blocks whose replicas have already been reported; blocks with no reported replica cannot be read yet.

What do threshold-pct and extension mean?

dfs.namenode.safemode.threshold-pct (0.999) is the fraction of blocks that must have at least dfs.namenode.replication.min reported replicas. dfs.namenode.safemode.extension (30,000 ms) is how long the NameNode stays in safe mode after reaching that threshold, to let late reports arrive.

Does leaving safe mode guarantee no data is missing?

No. The threshold allows a small fraction of blocks (0.1%, rounded) to be unreported. Run hdfs fsck / after restarts to find missing or corrupt blocks.

Practice problems

Safe mode exercises built on the real restarts from the lab.

P1Easy

Needed blocks

Compute the number of blocks that must be reported for totals 8, 9 and 1,000.

Input
8 · 9 · 1000
Expected output
8 -> 7
9 -> 8
1000 -> 999
Show solution and explanation
for t in [8, 9, 1000]:
    print(t, "->", int(t * 0.999))
8 -> 7 9 -> 8 1000 -> 999

How it works: 7, 8 and 999. For tiny clusters one block may be missing; at 1,000 blocks exactly one may be.

P2Easy

Extension end

A NameNode log line at 07:27:01 says “Safe mode will be turned off automatically in 9 seconds.” When should it turn off?

Input
07:27:01 + 9 s
Expected output
07:27:10
Show solution and explanation
from datetime import datetime, timedelta
print((datetime(2026, 10, 21, 7, 27, 1) + timedelta(seconds=9)).time())
07:27:10

How it works: 07:27:10. The real log shows “STATE* Safe mode is OFF” at 07:27:11, one second later because the check runs periodically.

P3Easy

Time in safe mode

A log says “Leaving safe mode after 70 secs”. The NameNode spent 25 s waiting for DataNodes to start and 30 s in the extension. How long was it waiting for block reports after the DataNodes started?

Input
70 · 25 · 30
Expected output
15 s
Show solution and explanation
print(70 - 25 - 30, "s")
15 s

How it works: About 15 s for registration and block reports.

P4Medium

Parse the NameNode message

Extract reported, total and seconds left from the real message.

Input
The reported blocks 8 has reached the threshold 0.9990 of total blocks 8. … in 24 seconds.
Expected output
8/8 reported, 24 s left
Show solution and explanation
import re
msg = ("The reported blocks 8 has reached the threshold 0.9990 of total blocks 8. "
       "The minimum number of live datanodes is not required. In safe mode extension. "
       "Safe mode will be turned off automatically in 24 seconds.")
r, t = re.search(r"reported blocks (\d+).*total blocks (\d+)", msg).groups()
left = re.search(r"in (\d+) seconds", msg).group(1)
print(f"{r}/{t} reported, {left} s left")
8/8 reported, 24 s left

How it works: 8/8 reported, 24 s left: the same parsing safemode_watch.py does.

P5Medium

Blocks per DataNode needed

600,000 blocks with replication 3 are spread evenly over 300 DataNodes. Roughly how many DataNodes must report before every block has at least one reported replica, if reports arrive from random nodes? Simulate it.

Input
600,000 blocks · 3 replicas · 300 nodes
Expected output
threshold reached after 270 of 300 DataNodes
Show solution and explanation
import random
random.seed(1)
nodes = 300
blocks = [random.sample(range(nodes), 3) for _ in range(60_000)]   # 1/10 sample
order = random.sample(range(nodes), nodes)
reported = set()
for i, n in enumerate(order, 1):
    reported.add(n)
    safe = sum(1 for b in blocks if reported.intersection(b))
    if safe >= int(len(blocks) * 0.999):
        print("threshold reached after", i, "of", nodes, "DataNodes")
        break
threshold reached after 270 of 300 DataNodes

How it works: The threshold was reached after 270 of 300 DataNodes: about 30 nodes (10%) could still be missing, because each block needs only one of its three replicas reported. Replication also shortens safe mode.

P6Medium

Manual or automatic?

For each situation, say whether safe mode will end by itself.

Input
restart · enter · disk low
Expected output
after restart          -> ends by itself
after -safemode enter  -> needs -safemode leave
metadata disk low      -> needs -safemode leave
Show solution and explanation
cases = {"after restart": True, "after -safemode enter": False, "metadata disk low": False}
for c, auto in cases.items():
    print(f"{c:22} -> {'ends by itself' if auto else 'needs -safemode leave'}")
after restart -> ends by itself after -safemode enter -> needs -safemode leave metadata disk low -> needs -safemode leave

How it works: Only start-up safe mode ends automatically; manual and resource-low safe mode need an admin.

P7Business problem

Cost of read-only minutes

Nightly pipelines restart the NameNode for patching. Safe mode lasts 12 minutes, blocking 40 ingestion jobs that each queue Rs 300 of SLA penalty per minute late after a 5-minute grace. What is the penalty, and what if checkpoints cut it to 4 minutes?

Input
12 vs 4 min · 40 jobs · Rs 300/min after 5 min
Expected output
12 min safe mode -> Rs 84,000
 4 min safe mode -> Rs 0
Show solution and explanation
for minutes in [12, 4]:
    late = max(0, minutes - 5)
    print(f"{minutes:>2} min safe mode -> Rs {late * 300 * 40:,}")
12 min safe mode -> Rs 84,000 4 min safe mode -> Rs 0

How it works: Rs 84,000 for 12 minutes, nothing for 4. Fast restarts (checkpoints, quick block reports) have real money value.

P8Advanced

Find missing blocks after leaving

Given the block → reported DataNodes map after leaving safe mode, list files with missing blocks.

Input
file → blocks · reported replicas
Expected output
orders.csv ok
scratch_r1.csv MISSING b9
users.csv ok
Show solution and explanation
files = {"orders.csv": ["b1", "b2"], "scratch_r1.csv": ["b9"], "users.csv": ["b5"]}
reported = {"b1": ["dn2"], "b2": ["dn3", "dn4"], "b5": ["dn2", "dn4"], "b9": []}
for f, blocks in files.items():
    missing = [b for b in blocks if not reported.get(b)]
    print(f, "MISSING " + ", ".join(missing) if missing else "ok")
orders.csv ok scratch_r1.csv MISSING b9 users.csv ok

How it works: Only scratch_r1.csv (its one replica was on the stopped DataNode), exactly as the real fsck reported.

Real-world scenario questions (asked in company interviews)

Safe mode questions check both knowledge and judgement: do you force it, or do you find out why?

HDFS · basicsFresher

“My job fails with ‘Name node is in safe mode’ right after starting HDFS”

A student's script runs start-dfs.sh and immediately hdfs dfs -put.

The interviewer is checking: what safe mode is and the right fix.

Show a strong answer
  • At start-up the NameNode stays read-only until DataNodes report 99.9% of blocks, plus 30 s.
  • Add hdfs dfsadmin -safemode wait after starting HDFS, before any write.
  • Don't add -safemode leave to the script: it would hide real problems.
Operations · incidentExperienced

Production NameNode stuck in safe mode at 96%

After a data-centre power cut, the NameNode reports 96% of blocks after 30 minutes. Users want you to force it out.

The interviewer is checking: calm, systematic recovery.

Show a strong answer
  • 4% unreported blocks means many DataNodes or disks are missing. Compare expected vs registered DataNodes (dfsadmin -report, UI).
  • Check those hosts: powered on? DataNode running? Disks mounted? Logs for clusterID or volume errors.
  • As nodes return, the count rises and safe mode ends by itself. Force it off only if the missing nodes are confirmed lost, then run fsck and restore data from backups/DR.
  • Communicate: the cluster is readable for reported data meanwhile.
HDFS · internalsExperienced

Why doesn't the NameNode just start re-replicating straight away?

A design question about the purpose of safe mode.

The interviewer is checking: understanding of the block map.

Show a strong answer
  • Right after start-up the block map is empty: every block looks like it has 0 replicas.
  • Acting on that would trigger copies of the whole cluster, followed by mass deletion when reports arrive.
  • Safe mode waits until the map is nearly complete, so replication decisions are based on real data.
Admin · maintenanceFresher

When would you put HDFS into safe mode on purpose?

An interviewer asks for real uses of -safemode enter.

The interviewer is checking: practical admin experience.

Show a strong answer
  • Before hdfs dfsadmin -saveNamespace (required), e.g. to create a clean checkpoint before maintenance.
  • To freeze the namespace while taking a metadata backup or before an upgrade.
  • Remember to run -safemode leave afterwards: manual safe mode never ends by itself.