Snapshots, quotas and trash

Replication protects data from broken disks, not from a wrong command or a runaway script. HDFS has three tools for that: snapshots (point-in-time views you can restore from), quotas (limits per folder) and trash (a recycle bin). This lesson uses all three on a real cluster, including two surprises that catch even experienced admins.

Module 7 · HDFS advanced⏱ 26 minIntermediateReal restore after -skipTrashThe 384 MB quota surpriseRuns in your browser (Python)8 practice problems
1 The story

The file that was deleted on purpose, by mistake

Result day. A tired operator cleaning old folders deletes /user/hadoop/results/2026/sem1.csv with -skipTrash. Ten minutes later the portal shows “file not found” to thousands of students. Two weeks earlier, a research student's script filled 40 TB of the shared cluster with temporary files overnight, and every other team's jobs failed with “disk full”. Replication protects against broken disks, not against people and runaway scripts. HDFS has three different tools for that, and today Riya tries all three.

Snapshots /results/.snapshot/before_results/2026/sem1.csv (read-only) a frozen view of a folder undo deletes and overwrites Quotas name quota: max files + foldersspace quota: max raw bytes one team can't fill the cluster or the NameNode's memory Trash /user/hadoop/.Trash/Current/…/f1.txt261021162255/ (checkpoint) -rm moves, not deletes (only if fs.trash.interval > 0) Replication protects against hardware. These three protect against people and programs. myphatshala.in
Arjun Sir

Trash catches ordinary deletes, but only if it's switched on and nobody uses -skipTrash. Snapshots are the real safety net: a read-only picture of a folder at a moment in time, taken in about a second however big the folder is, from which you can copy back anything. And quotas stop a single folder from eating the cluster's disk or the NameNode's memory.

Riya

If a snapshot keeps everything, doesn't it double the space?

Arjun Sir

No, that's the beauty. A snapshot stores no copies at creation; it only remembers what changed afterwards. Today we delete a file and bring it back from a snapshot, hit both kinds of quota (one of them in a very surprising way), and use the trash properly.

2 Definition

Snapshots, quotas and trash

Formal definition (write this in exams)

An HDFS snapshot is a read-only, point-in-time image of a directory subtree, created on a directory that an administrator has made snapshottable (hdfs dfsadmin -allowSnapshot). Creation is an O(1) metadata operation in the NameNode; no blocks are copied, and later changes are recorded as differences so that the snapshot's view (under dir/.snapshot/name) is preserved. Quotas limit a directory tree: the name quota caps the number of files and directories (including the directory itself), and the space quota caps raw bytes consumed including all replicas, with a full block's worth of space charged when a block is allocated. The trash is a client-side feature enabled by fs.trash.interval (minutes, default 0 = off): deleted paths are moved to /user/<name>/.Trash/Current, periodically rolled into timestamped checkpoints, and permanently removed after the interval.

In simple words

Snapshot: a photo of a folder you can always look back at. Quota: a limit on how many files or how many bytes a folder can have. Trash: a recycle bin for deleted files, if it is switched on.

Words you'll meet in this lesson

Snapshottable directoryA folder where snapshots are allowed (admin command).
.snapshotHidden path holding each snapshot: dir/.snapshot/name/…
snapshotDiffLists what changed between two snapshots: + - M R.
Name quotaMax number of files + folders in a tree (counts the folder itself).
Space quotaMax raw bytes in a tree, replicas included.
fs.trash.intervalMinutes deleted files stay in trash; 0 means trash is off.
Trash checkpointA timestamped folder in .Trash (e.g. 261021162255) holding older deletions.
expungehdfs dfs -expunge: checkpoint and remove expired trash.

From our lab (Hadoop 3.5.0)

Snapshot creation1.7 s for the command, almost all JVM start-up; a metadata operation
Snapshot limitlsSnapshottableDir shows 65536 as the per-directory snapshot limit
Name quota 3Only 2 files fit: the folder counts as 1 (“quota=3 file count=4”)
Space quota 10 MBEven a 2-byte file fails: a new block reserves 128 MB × 3 = 384 MB
fs.trash.interval0 (off) by default

Protection at three levels

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

Beginner Your phone's photos

  • Trash is the “Recently deleted” album: deleted photos wait there for a while. But “Delete permanently” skips it.
  • Snapshot is like a backup of the album at 9 am: whatever you do afterwards, you can open the 9 am version.
  • Quota is the storage limit on your cloud plan: you can't add more once it's full.

Intermediate How to use each one

  • Snapshots: hdfs dfsadmin -allowSnapshot /dir (admin, once), then hdfs dfs -createSnapshot /dir name. Restore by copying from /dir/.snapshot/name/…. Compare with hdfs snapshotDiff /dir s1 s2.
  • Quotas: hdfs dfsadmin -setQuota N /dir, -setSpaceQuota 1g /dir; check with hdfs dfs -count -q -h -v /dir; remove with -clrQuota, -clrSpaceQuota.
  • Trash: set fs.trash.interval (e.g. 1440 = 1 day) in core-site.xml; restore with -mv from .Trash/Current/….

Advanced Details that surprise people

  • Snapshots pin blocks: deleting a file doesn't free its space while any snapshot still refers to it. Old snapshots must be deleted (-deleteSnapshot) to reclaim disk.
  • Snapshots are not backups: they live on the same cluster. A lost cluster loses them too; use DistCp to another cluster (Module 12) for disaster recovery. DistCp can even use snapshot diffs to copy only changes.
  • Space quota and blocks: while a block is being written, the full block size × replication is reserved. A 10 MB quota with 128 MB blocks can't accept even one tiny file.
  • Trash is client-side: the Java API's delete(), many tools, and -skipTrash bypass it. Only a snapshot reliably protects against all deletes.
  • Name quotas protect the NameNode: they cap object counts in a tree, which matters more than bytes for small-file-heavy teams (Lesson 7.5).

Exam tip: Answer “HDFS snapshots” with: definition (read-only point-in-time copy of a directory), how to enable and create (-allowSnapshot, -createSnapshot), where they appear (.snapshot), that no data is copied at creation, and uses (accidental delete recovery, backups/DR via DistCp, consistent reads).

3 Types and ways to use it

Which protection for which problem?

ProblemTrashSnapshotQuota
hdfs dfs -rm by mistakeYes (if enabled)YesNo
-rm -skipTrash or API deleteNoYesNo
File overwritten with wrong dataNoYesNo
Runaway job filling the clusterNoNo (makes it worse)Yes (space quota)
Millions of tiny filesNoNoYes (name quota)
Whole cluster lostNoNoNo: needs a copy elsewhere

Commands at a glance

Snapshots

-allowSnapshot, -createSnapshot, -renameSnapshot, -deleteSnapshot, snapshotDiff, lsSnapshottableDir

recover

Quotas

-setQuota, -setSpaceQuota (optionally per storage type), -clrQuota, -count -q

limit

Trash

fs.trash.interval, fs.trash.checkpoint.interval, -expunge, -skipTrash

undo

Backups

Snapshots + DistCp to another cluster or cloud storage for disaster recovery.

off-cluster

A good default for important folders: trash on (1–7 days), daily snapshots kept for a week, weekly ones for a month, and quotas on every team's home and project folders.

4 Step by step

Delete, restore, limit, recycle

All commands ran on the namenode container of the lab cluster; the full script is in “Run it on your PC”.

  1. Make a folder snapshottable and take a snapshot

    hdfs dfsadmin -allowSnapshot /user/hadoop/results
    time hdfs dfs -createSnapshot /user/hadoop/results before_results
    Allowing snapshot on /user/hadoop/results succeeded Created snapshot /user/hadoop/results/.snapshot/before_results real 0m1.727s
    The NameNode only records the snapshot; no blocks are copied, so a folder with a million files snaps just as fast. The 1.7 s is the Java client starting.
  2. Delete for good, then restore

    hdfs dfs -rm -skipTrash /user/hadoop/results/2026/sem1.csv
    hdfs dfs -ls /user/hadoop/results/.snapshot/before_results/2026
    hdfs dfs -cp /user/hadoop/results/.snapshot/before_results/2026/sem1.csv /user/hadoop/results/2026/
    hdfs dfs -cat /user/hadoop/results/2026/sem1.csv
    Deleted /user/hadoop/results/2026/sem1.csv -rw-r--r-- 3 hadoop supergroup 25 2026-10-21 16:22 /user/hadoop/results/.snapshot/before_results/2026/sem1.csv roll,marks 101,78 102,91
    Even -skipTrash couldn't destroy the data: the snapshot still referenced the file's blocks. Restoring is a normal copy out of the read-only .snapshot view.
  3. What changed between two snapshots?

    printf '103,66\n' | hdfs dfs -appendToFile - /user/hadoop/results/2026/sem1.csv
    hdfs dfs -createSnapshot /user/hadoop/results after_append
    hdfs snapshotDiff /user/hadoop/results before_results after_append
    Difference between snapshot before_results and snapshot after_append under directory /user/hadoop/results: M ./2026 + ./2026/sem1.csv - ./2026/sem1.csv
    The folder was modified (M); the old sem1.csv was deleted (−) and a new one created (+), because our restore made a new file with the same name. DistCp uses exactly these diffs to copy only changes to a backup cluster.
  4. Snapshots protect themselves

    hdfs dfs -rm -r -skipTrash /user/hadoop/results/.snapshot/before_results
    hdfs dfs -rm -r -skipTrash /user/hadoop/results
    hdfs lsSnapshottableDir
    rm: Modification on a read-only snapshot is disallowed rm: The directory /user/hadoop/results cannot be deleted since /user/hadoop/results is snapshottable and already has snapshots drwxr-xr-x 0 hadoop supergroup 0 2026-10-21 16:22 2 65536 /user/hadoop/results
    Nobody can edit a snapshot, and a folder with snapshots can't be removed. lsSnapshottableDir shows 2 snapshots and the limit of 65,536. To free space, an admin must explicitly -deleteSnapshot.
  5. Name quota: count the folder too

    hdfs dfsadmin -setQuota 3 /user/hadoop/quota_lab/names
    for i in 1 2 3; do echo x | hdfs dfs -put - /user/hadoop/quota_lab/names/f$i.txt; done
    put f1 ok put f2 ok put: The NameSpace quota (directories and files) of directory /user/hadoop/quota_lab/names is exceeded: quota=3 file count=4
    The folder itself is one of the 3 names, so only 2 files fit. Name quotas protect the NameNode's memory from tree explosions.
  6. Space quota: the 384 MB surprise

    hdfs dfsadmin -setSpaceQuota 10m /user/hadoop/quota_lab/space
    echo x | hdfs dfs -put - /user/hadoop/quota_lab/space/tiny.txt
    hdfs dfsadmin -setSpaceQuota 1g /user/hadoop/quota_lab/space
    hdfs dfs -put /tmp/canteen_orders.csv /user/hadoop/quota_lab/space/
    hdfs dfs -count -q -h -v /user/hadoop/quota_lab/names /user/hadoop/quota_lab/space
    put: The DiskSpace quota of /user/hadoop/quota_lab/space is exceeded: quota = 10485760 B = 10 MB but diskspace consumed = 402653184 B = 384 MB put ok QUOTA REM_QUOTA SPACE_QUOTA REM_SPACE_QUOTA DIR_COUNT FILE_COUNT CONTENT_SIZE PATHNAME 3 0 none inf 1 2 4 /user/hadoop/quota_lab/names none inf 1 G 1010.6 M 1 1 4.5 M /user/hadoop/quota_lab/space
    A 2-byte file failed a 10 MB quota: when a block is allocated, HDFS reserves a full block (128 MB) × replication (3) = 384 MB until the block is finished. With 1 GB, the 4.5 MB file fits and uses 13.4 MB of quota (3 replicas), leaving 1010.6 M.
  7. Trash: move, restore, expunge

    hdfs getconf -confKey fs.trash.interval
    hdfs dfs -D fs.trash.interval=1440 -rm /user/hadoop/quota_lab/names/f1.txt
    hdfs dfs -mv /user/hadoop/.Trash/Current/user/hadoop/quota_lab/names/f1.txt /user/hadoop/quota_lab/names/
    hdfs dfs -D fs.trash.interval=1440 -rm /user/hadoop/quota_lab/names/f2.txt
    hdfs dfs -D fs.trash.interval=1440 -expunge -immediate
    0 Moved: 'hdfs://namenode/user/hadoop/quota_lab/names/f1.txt' to trash at: hdfs://namenode/user/hadoop/.Trash/Current/user/hadoop/quota_lab/names/f1.txt -rw-r--r-- 3 hadoop supergroup 2 2026-10-21 16:22 /user/hadoop/quota_lab/names/f1.txt -rw-r--r-- 3 hadoop supergroup 2 2026-10-21 16:22 /user/hadoop/quota_lab/names/f2.txt Moved: 'hdfs://namenode/user/hadoop/quota_lab/names/f2.txt' to trash at: hdfs://namenode/user/hadoop/.Trash/Current/user/hadoop/quota_lab/names/f2.txt Created trash checkpoint: /user/hadoop/.Trash/261021162255 Deleted trash checkpoint: /user/hadoop/.Trash/261021162255
    With trash on, -rm is a rename into .Trash/Current, so restoring is another rename. -expunge rolls Current into a timestamped checkpoint (yyMMddHHmmss) and deletes expired checkpoints; -immediate deletes them now.

A snapshot of a busy folder can quietly keep terabytes alive: data deleted from the live folder still counts on disk while snapshots refer to it. Monitor snapshot counts and ages, and delete old snapshots on a schedule.

5 See it happen

How a snapshot keeps a deleted file alive

Six steps inside the NameNode: the live tree, a snapshot, a delete, and a restore.

Snapshots in the NameNode 6 steps
What you see admin@namenode : ~ $ hdfs dfs -ls /results/2026sem1.csv 25 bytes $ hdfs dfs -createSnapshot /results \ before_resultsCreated snapshot …/.snapshot/before_results $ hdfs dfs -rm -skipTrash …/sem1.csvDeleted /results/2026/sem1.csv$ hdfs dfs -ls /results/2026(empty) $ hdfs dfs -ls …/.snapshot/before_results/2026sem1.csv 25 bytes $ hdfs dfs -cp …/.snapshot/…/sem1.csv …/2026/$ hdfs dfs -cat /results/2026/sem1.csvroll,marks / 101,78 / 102,91 $ hdfs dfs -rm -r …/.snapshot/before_resultsrm: Modification on a read-onlysnapshot is disallowed myphatshala.in
Behind the screen NameNode memory /results2026/ sem1.csv → blk Asem1.csv → blk B snapshot before_results(no copy at creation) diff: 2026/sem1.csv → blk A blk A blk B one file, one block (×3 replicas) snapshot = a marker in the tree; no blocks copied delete: the live entry goes, but the snapshot records it,so blk A is NOT freed .snapshot/before_results shows the old view restore = normal copy: a new file with a new block blk A lives until the snapshot is deleted(-deleteSnapshot by an admin) myphatshala.in
6 Real-world use

Protection at work

daily snapshotkeep 7

1. Scheduled snapshots of critical folders

Warehouse and results folders get a snapshot every night (named by date) from a scheduler, and a cleanup job deletes snapshots older than a week. Accidental deletes are fixed with a copy.

Nightly→createSnapshot + delete old→7 days of undo
diff only

2. Incremental copies to a DR cluster

DistCp can copy only the differences between two snapshots to a backup cluster, so daily DR copies of a 500 TB folder transfer just the day's changes (Module 12).

snapshot s1, s2→distcp -diff s1 s2→DR cluster
team quota

3. Quotas for every team

Shared clusters give each team's project folder a space quota and a name quota. A runaway job fails in its own folder instead of filling the cluster for everyone.

New project→setSpaceQuota + setQuota→Isolated growth
.Trash

4. Trash on by default

Most production clusters set fs.trash.interval to a day or more in core-site.xml and discourage -skipTrash except for scripted cleanup of temporary data.

rm→.Trash/Current→mv back if needed

Simplified; organisations differ in tools and policies.

7 Run the code

A copy-on-write snapshot in Python

The live folder is a dictionary of file names to block IDs. A snapshot records nothing at first; when a file is deleted or replaced, the old entry is saved into the snapshot's difference list. Blocks are freed only when nothing refers to them.

live = {"sem1.csv": "blkA", "sem2.csv": "blkB"}
snapshots = {}

def create_snapshot(name):
    snapshots[name] = {}                          # empty: nothing copied

def delete(fname):
    for diff in snapshots.values():
        diff.setdefault(fname, live[fname])       # remember the old version
    del live[fname]

def view(name):
    return {**live, **snapshots[name]}            # live tree + saved differences

def referenced_blocks():
    return set(live.values()) | {b for d in snapshots.values() for b in d.values()}

create_snapshot("before_results")
delete("sem1.csv")
print("live            :", live)
print("snapshot view   :", view("before_results"))
print("blocks kept     :", sorted(referenced_blocks()))
live : {'sem2.csv': 'blkB'} snapshot view : {'sem2.csv': 'blkB', 'sem1.csv': 'blkA'} blocks kept : ['blkA', 'blkB']
  • snapshots[name] = {} # empty: nothing copiedCreating a snapshot is instant because it copies nothing. Our real snapshot took 1.7 s, almost all Java start-up.
  • diff.setdefault(fname, live[fname]) # remember the old versionCopy-on-write: only when something changes is the old version recorded, and only once per snapshot.
  • return set(live.values()) | {b for d in snapshots.values() for b in d.values()}blkA is still referenced by the snapshot, so it isn't deleted. That is why snapshots can hold disk space after files are deleted.

Run it on your PC: snapshots, quotas and trash

Run this against the Module 5 lab cluster. Copy canteen_orders.csv into the namenode first (docker cp canteen_orders.csv lab5-namenode-1:/tmp/). The script cleans up its own folders from earlier runs, so you can run it again.

The protection lab

#!/usr/bin/env bash
# protect_lab.sh: snapshots, quotas and trash on the lab cluster.
NN="docker exec lab5-namenode-1"
run() { echo "\$ $1"; $NN bash -c "$1" 2>&1 | grep -v -E "^\s*$|WARN|^\s+at |INFO  (Configuration|deprecation)"; echo; }
D=/user/hadoop/results
run "for s in before_results after_append; do hdfs dfs -deleteSnapshot $D \$s > /dev/null 2>&1; done; hdfs dfsadmin -disallowSnapshot $D > /dev/null 2>&1; hdfs dfs -rm -r -f -skipTrash $D /user/hadoop/quota_lab > /dev/null; hdfs dfs -mkdir -p $D/2026 && printf 'roll,marks\n101,78\n102,91\n' | hdfs dfs -put - $D/2026/sem1.csv"
echo "=== SNAPSHOTS"
run "hdfs dfsadmin -allowSnapshot $D"
run "time hdfs dfs -createSnapshot $D before_results"
run "hdfs dfs -rm -skipTrash $D/2026/sem1.csv; hdfs dfs -ls $D/2026"
run "hdfs dfs -ls $D/.snapshot/before_results/2026"
run "hdfs dfs -cp $D/.snapshot/before_results/2026/sem1.csv $D/2026/ && hdfs dfs -cat $D/2026/sem1.csv"
run "printf '103,66\n' | hdfs dfs -appendToFile - $D/2026/sem1.csv; hdfs dfs -createSnapshot $D after_append > /dev/null; hdfs snapshotDiff $D before_results after_append"
run "hdfs dfs -rm -r -skipTrash $D/.snapshot/before_results"
run "hdfs dfs -rm -r -skipTrash $D"
run "hdfs lsSnapshottableDir"
echo "=== QUOTAS"
Q=/user/hadoop/quota_lab
run "hdfs dfs -mkdir -p $Q/names $Q/space && hdfs dfsadmin -setQuota 3 $Q/names && hdfs dfsadmin -setSpaceQuota 10m $Q/space"
run "for i in 1 2 3; do echo x | hdfs dfs -put - $Q/names/f\$i.txt && echo put f\$i ok; done 2>&1 | grep -E '^put'"
run "echo x | hdfs dfs -put - $Q/space/tiny.txt 2>&1 | grep -E '^put'"
run "hdfs dfsadmin -setSpaceQuota 1g $Q/space && hdfs dfs -put /tmp/canteen_orders.csv $Q/space/ && echo put ok"
run "hdfs dfs -count -q -h -v $Q/names $Q/space"
echo "=== TRASH"
run "hdfs getconf -confKey fs.trash.interval"
run "hdfs dfs -D fs.trash.interval=1440 -rm $Q/names/f1.txt"
run "hdfs dfs -ls -R /user/hadoop/.Trash | grep f1.txt"
run "hdfs dfs -mv /user/hadoop/.Trash/Current$Q/names/f1.txt $Q/names/ && hdfs dfs -ls $Q/names"
run "hdfs dfs -D fs.trash.interval=1440 -rm $Q/names/f2.txt"
run "hdfs dfs -D fs.trash.interval=1440 -expunge -immediate 2>&1 | grep -oE '(Created|Deleted) trash checkpoint: .*'; hdfs dfs -ls /user/hadoop/.Trash"

# Run:  bash protect_lab.sh
$ for s in before_results after_append; do hdfs dfs -deleteSnapshot /user/hadoop/results $s > /dev/null 2>&1; done; hdfs dfsadmin -disallowSnapshot /user/hadoop/results > /dev/null 2>&1; hdfs dfs -rm -r -f -skipTrash /user/hadoop/results /user/hadoop/quota_lab > /dev/null; hdfs dfs -mkdir -p /user/hadoop/results/2026 && printf 'roll,marks\n101,78\n102,91\n' | hdfs dfs -put - /user/hadoop/results/2026/sem1.csv === SNAPSHOTS $ hdfs dfsadmin -allowSnapshot /user/hadoop/results Allowing snapshot on /user/hadoop/results succeeded $ time hdfs dfs -createSnapshot /user/hadoop/results before_results Created snapshot /user/hadoop/results/.snapshot/before_results real 0m1.727s user 0m2.380s sys 0m0.204s $ hdfs dfs -rm -skipTrash /user/hadoop/results/2026/sem1.csv; hdfs dfs -ls /user/hadoop/results/2026 Deleted /user/hadoop/results/2026/sem1.csv $ hdfs dfs -ls /user/hadoop/results/.snapshot/before_results/2026 Found 1 items -rw-r--r-- 3 hadoop supergroup 25 2026-10-21 16:22 /user/hadoop/results/.snapshot/before_results/2026/sem1.csv $ hdfs dfs -cp /user/hadoop/results/.snapshot/before_results/2026/sem1.csv /user/hadoop/results/2026/ && hdfs dfs -cat /user/hadoop/results/2026/sem1.csv roll,marks 101,78 102,91 $ printf '103,66\n' | hdfs dfs -appendToFile - /user/hadoop/results/2026/sem1.csv; hdfs dfs -createSnapshot /user/hadoop/results after_append > /dev/null; hdfs snapshotDiff /user/hadoop/results before_results after_append Difference between snapshot before_results and snapshot after_append under directory /user/hadoop/results: M ./2026 + ./2026/sem1.csv - ./2026/sem1.csv $ hdfs dfs -rm -r -skipTrash /user/hadoop/results/.snapshot/before_results rm: Modification on a read-only snapshot is disallowed $ hdfs dfs -rm -r -skipTrash /user/hadoop/results rm: The directory /user/hadoop/results cannot be deleted since /user/hadoop/results is snapshottable and already has snapshots $ hdfs lsSnapshottableDir drwxr-xr-x 0 hadoop supergroup 0 2026-10-21 16:22 2 65536 /user/hadoop/results === QUOTAS $ hdfs dfs -mkdir -p /user/hadoop/quota_lab/names /user/hadoop/quota_lab/space && hdfs dfsadmin -setQuota 3 /user/hadoop/quota_lab/names && hdfs dfsadmin -setSpaceQuota 10m /user/hadoop/quota_lab/space $ for i in 1 2 3; do echo x | hdfs dfs -put - /user/hadoop/quota_lab/names/f$i.txt && echo put f$i ok; done 2>&1 | grep -E '^put' put f1 ok put f2 ok put: The NameSpace quota (directories and files) of directory /user/hadoop/quota_lab/names is exceeded: quota=3 file count=4 $ echo x | hdfs dfs -put - /user/hadoop/quota_lab/space/tiny.txt 2>&1 | grep -E '^put' put: The DiskSpace quota of /user/hadoop/quota_lab/space is exceeded: quota = 10485760 B = 10 MB but diskspace consumed = 402653184 B = 384 MB $ hdfs dfsadmin -setSpaceQuota 1g /user/hadoop/quota_lab/space && hdfs dfs -put /tmp/canteen_orders.csv /user/hadoop/quota_lab/space/ && echo put ok put ok $ hdfs dfs -count -q -h -v /user/hadoop/quota_lab/names /user/hadoop/quota_lab/space QUOTA REM_QUOTA SPACE_QUOTA REM_SPACE_QUOTA DIR_COUNT FILE_COUNT CONTENT_SIZE PATHNAME 3 0 none inf 1 2 4 /user/hadoop/quota_lab/names none inf 1 G 1010.6 M 1 1 4.5 M /user/hadoop/quota_lab/space === TRASH $ hdfs getconf -confKey fs.trash.interval 0 $ hdfs dfs -D fs.trash.interval=1440 -rm /user/hadoop/quota_lab/names/f1.txt 2026-10-21 16:22:46 INFO TrashPolicyDefault:196 - Moved: 'hdfs://namenode/user/hadoop/quota_lab/names/f1.txt' to trash at: hdfs://namenode/user/hadoop/.Trash/Current/user/hadoop/quota_lab/names/f1.txt $ hdfs dfs -ls -R /user/hadoop/.Trash | grep f1.txt -rw-r--r-- 3 hadoop supergroup 2 2026-10-21 16:22 /user/hadoop/.Trash/Current/user/hadoop/quota_lab/names/f1.txt $ hdfs dfs -mv /user/hadoop/.Trash/Current/user/hadoop/quota_lab/names/f1.txt /user/hadoop/quota_lab/names/ && hdfs dfs -ls /user/hadoop/quota_lab/names Found 2 items -rw-r--r-- 3 hadoop supergroup 2 2026-10-21 16:22 /user/hadoop/quota_lab/names/f1.txt -rw-r--r-- 3 hadoop supergroup 2 2026-10-21 16:22 /user/hadoop/quota_lab/names/f2.txt $ hdfs dfs -D fs.trash.interval=1440 -rm /user/hadoop/quota_lab/names/f2.txt 2026-10-21 16:22:54 INFO TrashPolicyDefault:196 - Moved: 'hdfs://namenode/user/hadoop/quota_lab/names/f2.txt' to trash at: hdfs://namenode/user/hadoop/.Trash/Current/user/hadoop/quota_lab/names/f2.txt $ hdfs dfs -D fs.trash.interval=1440 -expunge -immediate 2>&1 | grep -oE '(Created|Deleted) trash checkpoint: .*'; hdfs dfs -ls /user/hadoop/.Trash Created trash checkpoint: /user/hadoop/.Trash/261021162255 Deleted trash checkpoint: /user/hadoop/.Trash/261021162255

Real output. Note the quota lines: 2 files fit in a name quota of 3, and a 2-byte file breaks a 10 MB space quota because 384 MB are reserved for the new block.

8 Line by line

Checking a space quota while writing

Follow the NameNode's quota check as a client writes a small file into a folder with a 10 MB space quota.

Worked examples: real problems, solved and traced in memory

Three protection calculations: the space snapshots really cost, a sensible quota, and a snapshot schedule.

Example 1BeginnerQuota · sizing

What space quota does a team need?

Problem statement

A team expects 20 TB of data with replication 3 and wants 25% headroom. What space quota should be set?

Input
20 TB · ×3 · +25%
Expected output
setSpaceQuota 75t

Approach

  1. Raw = data × replication.
  2. Add 25% headroom.
  3. Space quotas count raw bytes.

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 2IntermediateSnapshots · cost

How much disk do a week of snapshots hold?

Problem statement

A 50 TB folder changes 2% of its data per day (rewritten or deleted). Daily snapshots are kept for 7 days. Roughly how much extra raw space (replication 3) do the snapshots hold?

Input
50 TB · 2%/day · 7 days · ×3
Expected output
about 7 TB of old data, 21 TB raw

Approach

  1. Each day 1 TB of old data is kept by snapshots.
  2. For 7 days: 7 TB.
  3. Times replication.

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 3AdvancedOperations · schedule

Which snapshots to keep?

Problem statement

Policy: keep daily snapshots for 7 days and Sunday snapshots for 4 weeks. Given 30 days of snapshots named by day number (day 30 = today, day 30 is a Sunday), list which to keep.

Input
days 1–30, Sundays every 7 days back from 30
Expected output
keep: [9, 16, 23, 24, 25, 26, 27, 28, 29, 30]
delete: 20 snapshots

Approach

  1. Keep the last 7 days.
  2. Keep Sundays within 28 days.
  3. Delete the rest.

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 7.4 in one screen

  • Snapshot: read-only point-in-time view; -allowSnapshot then -createSnapshot; under dir/.snapshot/name; instant (copy-on-write).
  • Restore = copy out of .snapshot; snapshotDiff shows + − M R; snapshots can't be edited; a folder with snapshots can't be deleted.
  • Snapshots pin deleted blocks: delete old snapshots to free space. Not a backup: copy off-cluster (DistCp).
  • Name quota counts files + folders including the folder itself (quota 3 → 2 files).
  • Space quota counts raw bytes with replicas; a new block reserves 128 MB × 3 = 384 MB.
  • Trash: fs.trash.interval (default 0 = off); -rm moves to .Trash/Current; -expunge checkpoints and purges; -skipTrash bypasses.
  • Check usage: hdfs dfs -count -q -h -v.

Interview and viva questions

What are HDFS snapshots?

Read-only, point-in-time copies of a directory tree. An administrator enables them per directory with hdfs dfsadmin -allowSnapshot; users create them with hdfs dfs -createSnapshot. Creation copies no data; the NameNode records later changes so the old view remains available under the .snapshot path. They are used to recover from accidental deletes or overwrites and as a consistent source for backups.

What is the difference between a name quota and a space quota?

A name quota limits the number of files and directories in a tree (including the directory itself). A space quota limits the raw bytes consumed, counting all replicas. They are set independently with hdfs dfsadmin -setQuota and -setSpaceQuota.

Why does a small file fail a space quota that seems large enough?

Because when a block is allocated, HDFS charges a full block size times the replication factor against the quota until the block is completed. With 128 MB blocks and replication 3, a quota below 384 MB cannot accept any new file.

How does the HDFS trash work?

If fs.trash.interval is greater than zero, deleting with the shell moves files to /user/<name>/.Trash/Current. Periodically (or on -expunge) Current is renamed to a timestamped checkpoint, and checkpoints older than the interval are deleted permanently. Files can be restored by moving them out of the trash. -skipTrash and most API deletes bypass it.

Are snapshots a backup?

No. They live in the same cluster and depend on the same NameNode and DataNodes. They protect against logical mistakes, not against losing the cluster. For disaster recovery, copy data (or snapshot differences) to another cluster or to cloud storage with DistCp.

Practice problems

Protection exercises using the real messages and numbers from the lab.

P1Easy

Snapshot path

Build the path of sem1.csv inside the snapshot before_results of /user/hadoop/results.

Input
folder, snapshot, file
Expected output
/user/hadoop/results/.snapshot/before_results/2026/sem1.csv
Show solution and explanation
d, s, f = "/user/hadoop/results", "before_results", "2026/sem1.csv"
print(f"{d}/.snapshot/{s}/{f}")
/user/hadoop/results/.snapshot/before_results/2026/sem1.csv

How it works: /user/hadoop/results/.snapshot/before_results/2026/sem1.csv, as listed in the lab.

P2Easy

Quota used

The space quota is 1 G and the remaining quota is 1010.6 M. How much is used, and how much data is that with replication 3?

Input
1024 M − 1010.6 M
Expected output
used 13.4 M raw -> 4.5 M of data
Show solution and explanation
used = 1024 - 1010.6
print(f"used {used:.1f} M raw -> {used / 3:.1f} M of data")
used 13.4 M raw -> 4.5 M of data

How it works: 13.4 M raw = 4.5 M of data × 3: the canteen_orders.csv file.

P3Easy

Reserved bytes

Compute the reservation that the 2-byte file triggered.

Input
128 MB × 3
Expected output
402653184 bytes
Show solution and explanation
print(128 * 1024 * 1024 * 3, "bytes")
402653184 bytes

How it works: 402,653,184 bytes, exactly the number in the error message.

P4Medium

Parse snapshotDiff

Count created, deleted and modified entries in the real snapshotDiff output.

Input
3 lines
Expected output
Counter({'M': 1, '+': 1, '-': 1})
Show solution and explanation
from collections import Counter
out = """M	./2026
+	./2026/sem1.csv
-	./2026/sem1.csv"""
print(Counter(line.split()[0] for line in out.splitlines()))
Counter({'M': 1, '+': 1, '-': 1})

How it works: One of each: the folder was modified, and the restored file appears as deleted (old inode) plus created (new inode).

P5Medium

Which quota fails first?

A folder has name quota 1,000 and space quota 30 GB. A job writes 600 files of 20 MB each (replication 3). Which limit is hit?

Input
600 × 20 MB
Expected output
names: 601 of 1000 | raw: 35.2 GB of 30 GB
Show solution and explanation
files, size_mb, rep = 600, 20, 3
names_needed = files + 1
raw_gb = files * size_mb * rep / 1024
print("names:", names_needed, "of 1000 | raw:", round(raw_gb, 1), "GB of 30 GB")
names: 601 of 1000 | raw: 35.2 GB of 30 GB

How it works: Space: 35.2 GB > 30 GB, while names (601) are fine. Big files hit space quotas; tiny files hit name quotas.

P6Medium

Trash age

A trash checkpoint is named 261021162255. With fs.trash.interval = 1440, when will it be deleted?

Input
yyMMddHHmmss + 1440 min
Expected output
created 2026-10-21 16:22:55 -> deleted after 2026-10-22 16:22:55
Show solution and explanation
from datetime import datetime, timedelta
t = datetime.strptime("261021162255", "%y%m%d%H%M%S")
print("created", t, "-> deleted after", t + timedelta(minutes=1440))
created 2026-10-21 16:22:55 -> deleted after 2026-10-22 16:22:55

How it works: One day later, at the next expunge run after that time.

P7Business problem

Cost of a runaway job

Without quotas, a runaway job filled the cluster and 25 teams lost a 6-hour working day (₹1.2 lakh per team per day). With quotas only its own team would have been affected. What did the missing quota cost?

Input
24 other teams × ₹1.2 lakh × 6/8 day
Expected output
Rs 21.6 lakh
Show solution and explanation
print(f"Rs {24 * 1.2 * 6 / 8:.1f} lakh")
Rs 21.6 lakh

How it works: About ₹21.6 lakh in lost work (illustrative), for one missing admin command.

P8Advanced

Blocks freed after deleting a snapshot

Live files refer to blocks {A, C}; snapshot s1 refers to {A, B}; snapshot s2 refers to {B, C, D}. Which blocks are freed if s1 is deleted? If s2 is also deleted?

Input
live {A,C}, s1 {A,B}, s2 {B,C,D}
Expected output
delete s1 frees: []
then s2 frees  : ['B', 'D']
Show solution and explanation
live, s1, s2 = {"A", "C"}, {"A", "B"}, {"B", "C", "D"}
before = live | s1 | s2
print("delete s1 frees:", sorted(before - (live | s2)))
print("then s2 frees  :", sorted((live | s2) - live))
delete s1 frees: [] then s2 frees : ['B', 'D']

How it works: Deleting s1 frees nothing (A is live, B is in s2). Deleting s2 then frees B and D. Space returns only when no snapshot or live file refers to a block.

Real-world scenario questions (asked in company interviews)

Data protection questions come up in every Hadoop administration and data platform interview.

Operations · recoveryFresher

“A user deleted a production folder. Can you get it back?”

The classic incident question.

The interviewer is checking: trash, snapshots, backups, in order.

Show a strong answer
  • Check the user's .Trash/Current (and checkpoints); -mv it back.
  • If trash was off or bypassed, copy it back from the latest snapshot under .snapshot.
  • Otherwise restore from the DR cluster or reprocess from raw data. Then add snapshots and trash to prevent a repeat.
Quotas · troubleshootingExperienced

“DSQuotaExceeded, but the folder only has 2 GB of a 3 GB quota”

A team's job fails while writing many files in parallel.

The interviewer is checking: block reservation and raw bytes.

Show a strong answer
  • Space quotas count raw bytes: 2 GB of data at replication 3 may already be 6 GB raw.
  • Every block being written reserves block size × replication (384 MB with defaults); 20 parallel writers reserve 7.5 GB at once.
  • Raise the quota to cover raw size plus in-flight blocks, or reduce parallel writers.
Capacity · snapshotsExperienced

Deleting 100 TB didn't free any space

An admin deleted old partitions, but the cluster's used space stayed the same.

The interviewer is checking: snapshots (and trash) holding blocks.

Show a strong answer
  • Check hdfs lsSnapshottableDir and snapshots on parent folders: they still reference the deleted blocks.
  • Also check the trash: deleted data may sit in .Trash until the interval passes.
  • Delete the obsolete snapshots / expunge trash; space is freed as DataNodes delete the blocks.
Design · policyExperienced

Design a data protection policy for a shared cluster

40 teams, one production cluster, one DR cluster.

The interviewer is checking: layered protection.

Show a strong answer
  • Trash on (e.g. 3 days) cluster-wide; restrict -skipTrash to service accounts.
  • Snapshots on critical folders: daily for 7 days, weekly for 4 weeks, with automatic cleanup.
  • Name and space quotas on every team folder, with alerts at 80%.
  • Nightly DistCp (snapshot diffs) to the DR cluster for critical data.