Hadoop Core Commands & Data Movement
Lesson opener
In one line: Load, organise, secure, validate and recover files on HDFS with a small set of commands, a disciplined landing-then-publish pattern and a runbook that proves every copy is complete before anyone queries it.
Why it matters: Most HDFS incidents are not exotic cluster failures. They are partial uploads, files in the wrong folder, permissions that are too open or too tight, thousands of tiny files and copies nobody verified. Because HDFS stores replicated blocks rather than rows in a database, a successful command does not prove a complete, correct dataset; validation is your job.
Before this lesson: Big Data & Hadoop: Distributed Foundations explained NameNode, DataNodes, blocks and replication. What Data Engineers Do and Python Advanced supply the pipeline and scripting vocabulary. This lesson stays framework-neutral: the commands are the legacy and on-premises view, and a managed lakehouse on Databricks & Spark hides most of them behind object storage.
Northline Financial Services (illustrative) must load seven years of historical payment files, delivered as monthly CSV extracts, into an HDFS cluster that another team operates. A previous attempt left half-copied months, mixed permissions and a January total that did not match the finance control figure. The data engineer must produce a runbook that others can follow: ingest, validate, recover and, later, migrate.
What you will be able to do
- Explain how an HDFS file becomes blocks, replicas and a place in the namespace.
- Use the core
hdfs dfscommands to create directories, upload, download, inspect, copy, move and delete data. - Set ownership, permissions and replication deliberately.
- Describe data locality and design a directory layout that supports partition-aware reads.
- Recognise and avoid the small-file problem.
- Validate a copy with file counts, sizes, row counts and checksums, and recover from failed transfers and node loss.
- Plan a migration between clusters or to object storage.
Deliverable: an HDFS ingestion, validation and recovery runbook for a named dataset: layout, commands (marked environment-dependent), validation checks with pass criteria, failure scenarios with recovery steps, owners, escalation and rollback.
Prerequisites
| Prerequisite | Why it matters |
|---|---|
| Big Data & Hadoop: Distributed Foundations | NameNode, DataNode, block and replication concepts used throughout. |
| What Data Engineers Do | Landing, staging and published zones; batch loads. |
| Python Advanced | The validation scripts use functions, generators and the standard library. |
| Identity, Access & Least Privilege | Service accounts and least privilege applied to HDFS permissions. |
| Data Quality Checks | Row counts, control totals and completeness checks. |
Plain English
Files, blocks and replicas. When you write a file to HDFS the client splits it into blocks (128 MB by default in Hadoop 3.x; the last block is only as large as the remaining data). The NameNode chooses DataNodes for each block and the client streams data through a pipeline of those nodes. The NameNode stores only metadata; the data never flows through it. With the default placement policy and replication of three, the first replica goes on the writer's node (if it is a DataNode), the second on a node in a different rack and the third on another node in that second rack, so a single node or rack failure does not remove every copy. Block size and replication can be set per file and per cluster; defaults and policies are environment-dependent.
Directories and layout. HDFS has a hierarchical namespace like a file system. Good layouts group data by zone and by the keys that queries filter on, for example /data/<domain>/<zone>/<dataset>/year=2019/month=01/. Engines such as Hive and Spark recognise key=value directory names as partitions and skip folders a query does not need (see Hive & Distributed SQL). Keep names predictable and lower-case, avoid spaces and encode the load date or batch id.
Permissions. HDFS uses POSIX-like owner, group and mode bits with optional access control lists (when enabled by the administrator). The HDFS superuser is the account that runs the NameNode process. Ingestion should run as a dedicated service account with write access only to landing and staging zones; analysts read published zones through groups. Strong authentication in real clusters typically uses Kerberos. Do not use chmod 777 to make an error go away.
Core commands. hdfs dfs (equivalent to hadoop fs for HDFS) offers -ls, -mkdir, -put, -get, -cat, -tail, -cp, -mv, -rm, -du, -count, -stat, -chmod, -chown, -setrep, -checksum and -test. hdfs fsck reports file, block and replica health. hdfs dfsadmin -report summarises capacity and DataNodes. hadoop distcp copies large datasets in parallel using MapReduce. Every command and flag shown in this course is environment-dependent: confirm names and behaviour for your Hadoop version and distribution in the FileSystemShell and HDFS command guides.
Data locality. The scheduler tries to run a task on a node (or at least a rack) that already holds the task's block. Locality works best with large, splittable files in columnar formats. Plain gzip text is not splittable, so one task must read the whole file; bzip2 is splittable but slow; Parquet and ORC are splittable at row-group or stripe level.
The small-file problem. Each file, directory and block is an object in NameNode memory, and each small file typically becomes its own task. Millions of tiny files exhaust NameNode memory and make jobs slow even when disks are mostly empty. Prefer fewer files near block size or larger (hundreds of megabytes is a common target; confirm for your workload), batch by time window, compact after landing and use formats or table features that support compaction.
Failure and recovery. A lost DataNode is repaired automatically by re-replication, so watch for under-replicated and missing blocks rather than reacting to the single node. Missing blocks mean all replicas are gone. Accidental deletion is a different failure: replication copies deletions too. Protect against it with the trash feature (enabled by fs.trash.interval, off by default in stock Hadoop), snapshots on important directories and a copy elsewhere. During startup the NameNode may be in safe mode while it collects block reports; do not force it out of safe mode without understanding why it is waiting.
Validating copies. Compare, in this order: file count, byte size per file, row counts (for text formats), a control total from the source system and a content checksum. hdfs dfs -checksum returns an HDFS composite checksum that depends on block size and bytes-per-checksum settings, so it is comparable only between HDFS paths with the same settings. To compare a source file with its HDFS copy, compute a hash on the streamed content (for example by piping hdfs dfs -cat into a hashing tool) or use distcp for cluster-to-cluster copies, which verifies checksums by default.
Migration. Moving between clusters or to cloud object storage is done in waves, with distcp (using -update to copy only differences and -p to preserve attributes) or provider tools, followed by the same validation and a period where both copies exist. Connectors and credentials for object stores are environment-dependent and must come from a secrets store, never from a command line.
Safe guidance. Practise on a test cluster or a local pseudo-distributed install with synthetic files. Never run delete or -skipTrash commands against production paths without an approved change and a verified copy.
Teacher walkthrough
Plan the historical payment load. All volumes are illustrative.
- Business objective. Make 84 monthly payment extracts (seven years) queryable for audit and fraud analytics, with every month reconciled to a finance control total.
- Scale assumptions. About 1.5 GB per month before compression, so roughly 126 GB of source files; replication of three means about 380 GB of cluster capacity. The scale is modest; the lesson is about correctness, not size.
- Data sources. CSV extracts from the payments system delivered to an SFTP drop and a manifest file listing name, rows, bytes and SHA-256 for each file.
- Volume and velocity. One-off historical backfill, then one new file a month. Backfill runs in the quiet window with a bandwidth limit agreed with the network team.
- Storage. Landing zone
/data/nfs/landing/payments/, staging_incoming/, validated zone/data/nfs/raw/payments/year=YYYY/month=MM/. Files are later converted to columnar format (see Warehouses, Lakes & Lakehouse). - Processing. Copy to
_incoming, validate, then move (-mv, a metadata operation within one HDFS namespace) into the partition folder so consumers never see partial data. - Model workload. A fraud-features job reads the raw partitions after validation; it reads only published partitions, never
_incoming. - Security. The
svc_ingestaccount writes landing and raw; analysts have read-only group access; permissions set explicitly (for example mode 750); no credentials in scripts; audit logging enabled by the platform team. - Monitoring. Per-month validation result, under-replicated and missing block counts, files per directory, average file size, capacity trend and job duration.
- Failure handling. Interrupted uploads are re-run from
_incomingafter cleaning partial files; node failures are left to re-replication unless blocks go missing; wrong or duplicate files are quarantined, not overwritten. - Cost. Drivers: cluster capacity times replication, operator time, network transfer and the cost of re-running failed months. No prices are given; take current figures from your platform owners.
- Validation. A month is "done" only when file count, byte size, row count, control total and checksum all match the manifest and the replication check is clean.
Worked example
The first half of the script simulates how a 1000 MB file becomes blocks with a simplified rack-aware placement, how a node failure creates under-replicated blocks and how re-replication restores them, and why file count matters for the NameNode. The second half builds a manifest for three synthetic payment files, simulates a bad copy (one truncated file, one missing file) and shows the comparison catching both and passing after repair. Placement is a simplified teaching model of the default policy, not the real implementation. It uses only the standard library and synthetic data.
import hashlib
import shutil
import tempfile
from pathlib import Path
BLOCK_MB = 128
NODES = {"n1": "rackA", "n2": "rackA", "n3": "rackB", "n4": "rackB", "n5": "rackC", "n6": "rackC"}
def split_into_blocks(size_mb, block_mb=BLOCK_MB):
full, rest = divmod(size_mb, block_mb)
return [block_mb] * full + ([rest] if rest else [])
def place(block_id, writer, replication=3):
"""Simplified default policy: writer node, a node on another rack, a second node on that rack."""
second_pool = sorted(n for n, r in NODES.items() if r != NODES[writer])
second = second_pool[block_id % len(second_pool)]
third = sorted(n for n, r in NODES.items() if r == NODES[second] and n != second)[0]
return [writer, second, third][:replication]
FILE_MB = 1000
blocks = split_into_blocks(FILE_MB)
print("blocks for a 1000 MB file:", blocks)
placement = {i: place(i, "n1") for i in range(len(blocks))}
for i, nodes in placement.items():
print(f"block {i}: {nodes} racks={sorted({NODES[n] for n in nodes})}")
dead = "n3"
alive = [n for n in NODES if n != dead]
under = [i for i, nodes in placement.items() if dead in nodes]
print(f"{dead} fails: under-replicated blocks = {under}")
for i in under:
placement[i] = [n for n in placement[i] if n != dead]
target = sorted(n for n in alive if n not in placement[i])[0]
placement[i].append(target)
assert all(len(set(nodes)) == 3 and dead not in nodes for nodes in placement.values())
assert all(len({NODES[n] for n in nodes}) >= 2 for nodes in placement.values())
print("after re-replication every block has 3 distinct live copies on 2+ racks")
def namespace_objects(total_tb, file_mb):
files = int(total_tb * 1000 * 1000 / file_mb)
blocks_per_file = max(1, -(-file_mb // BLOCK_MB))
return files + files * blocks_per_file
print("1 TB as 256 MB files, namespace objects:", f"{namespace_objects(1, 256):,}")
print("1 TB as 1 MB files, namespace objects: ", f"{namespace_objects(1, 1):,}")
def sha256_of(path):
digest = hashlib.sha256()
with open(path, "rb") as handle:
for chunk in iter(lambda: handle.read(1 << 16), b""):
digest.update(chunk)
return digest.hexdigest()
def manifest(folder):
result = {}
for path in sorted(Path(folder).glob("*.csv")):
rows = sum(1 for _ in open(path, encoding="utf-8")) - 1
result[path.name] = {"rows": rows, "bytes": path.stat().st_size, "sha256": sha256_of(path)}
return result
def compare(src, dst):
problems = []
for name, meta in src.items():
if name not in dst:
problems.append(f"MISSING {name}")
elif dst[name] != meta:
problems.append(f"MISMATCH {name}")
problems += [f"UNEXPECTED {name}" for name in dst if name not in src]
return problems or ["all files match"]
with tempfile.TemporaryDirectory() as tmp:
src, dst = Path(tmp, "source"), Path(tmp, "landed")
src.mkdir()
dst.mkdir()
for month in ("2019_01", "2019_02", "2019_03"):
lines = ["payment_id,account_token,amount,currency"]
lines += [f"P{month}-{n:04d},tok_{n % 7:02d},{10 + n % 50}.00,INR" for n in range(1, 101)]
(src / f"payments_{month}.csv").write_text("\n".join(lines) + "\n", encoding="utf-8")
expected = manifest(src)
print({k: v["rows"] for k, v in expected.items()})
for path in src.glob("*.csv"):
shutil.copy2(path, dst / path.name)
(dst / "payments_2019_02.csv").write_bytes((src / "payments_2019_02.csv").read_bytes()[:-120])
(dst / "payments_2019_03.csv").unlink()
print(compare(expected, manifest(dst)))
for name in ("payments_2019_02.csv", "payments_2019_03.csv"):
shutil.copy2(src / name, dst / name)
print(compare(expected, manifest(dst)))Expected result: a 1000 MB file becomes seven 128 MB blocks and one 104 MB block, each with three replicas on at least two racks. When n3 fails, blocks 0, 1, 4 and 5 are under-replicated and are restored to three live copies. One terabyte stored as 256 MB files is about 11.7 thousand namespace objects, while the same terabyte as 1 MB files is 2 million. The manifest shows 100 rows per file; the first comparison reports MISMATCH payments_2019_02.csv (truncated) and MISSING payments_2019_03.csv, and after recopying the result is all files match.
The runbook commands below are environment-dependent: they assume a Hadoop 3.x CLI, an HDFS namespace layout, a service account and host names that are illustrative. They are not run by the course test harness; try them on a test cluster first.
# ENVIRONMENT-DEPENDENT: Hadoop 3.x CLI assumed; paths and accounts are illustrative.
hdfs dfs -mkdir -p /data/nfs/landing/payments/_incoming
hdfs dfs -mkdir -p /data/nfs/raw/payments/year=2019/month=01
hdfs dfs -put /staging/payments/payments_2019_01.csv /data/nfs/landing/payments/_incoming/
hdfs dfs -ls -h /data/nfs/landing/payments/_incoming
hdfs dfs -stat "%n %b bytes, replication %r, block size %o" /data/nfs/landing/payments/_incoming/payments_2019_01.csv
hdfs dfs -cat /data/nfs/landing/payments/_incoming/payments_2019_01.csv | sha256sum # compare with the manifest
hdfs dfs -mv /data/nfs/landing/payments/_incoming/payments_2019_01.csv /data/nfs/raw/payments/year=2019/month=01/
hdfs dfs -chmod -R 750 /data/nfs/raw/payments
hdfs dfs -count -q -h /data/nfs/raw/payments
hdfs fsck /data/nfs/raw/payments -files -blocks -locationsA second workplace case
Northline Consumer Goods (illustrative) runs an on-premises HDFS cluster holding a 40 TB retail sales archive and plans to move it to cloud object storage as part of a data centre exit. This differs from the payment backfill: the data is large and live, thousands of directories change daily, consumers cannot be stopped and the target is not HDFS. The runbook is a migration in waves. Each wave copies one domain with distcp -update (environment-dependent, with the object-store connector and credentials supplied by the platform team), compares file counts, byte totals and a sample of checksums, runs consumer queries against both copies and records a signed-off result. Source data stays read-only after the last delta sync until a defined retention date, so rollback is a configuration change back to the original paths. The team also compacts small files before the move because per-file overhead is higher on object stores than on HDFS (confirm the behaviour of your store). Cutover happens per domain, never as one event.
Failure example
Symptom: The January 2019 total from the raw payments table is 38% above the finance control total, although the upload job reported success.
Diagnosis: The first upload was interrupted by a network drop and left a partial file. The loader script retried by uploading the file again under a new name (payments_2019_01_retry.csv) into the same partition folder without removing the partial one. The table reads every file in the folder, so rows from both files were counted. The loader checked the exit code of the last command but never compared file lists, sizes or row counts with the manifest.
Correction: Stop consumers of that partition, list the folder, identify the extra and partial files by comparing against the manifest and move them to a quarantine folder (rather than deleting them immediately). Re-upload the correct file to _incoming, validate it and only then move it into the partition folder. Re-run the downstream job for the affected month.
Validation: The partition folder contains exactly the manifest's file with matching bytes, rows and checksum, fsck reports healthy blocks, the January total equals the finance control total and the downstream outputs are regenerated.
Prevention: Use the landing-then-publish pattern, deterministic file names so retries overwrite the same name in _incoming, validation against a manifest before the publish step, a success marker written only after validation and an alert when a partition folder contains an unexpected file.
Guided practice
Scenario: Write the runbook steps for loading the 2020 payment files (twelve CSVs and a manifest). One upload fails halfway in the middle of the run, and a DataNode is lost the next morning.
Hints:
- Where do files land first, and where are they published?
- What do you compare before moving a file into its partition folder?
- How do you restart safely after a failed upload?
- What do you check after a DataNode loss, and when do you escalate?
Complete solution:
- Layout: land in
/data/nfs/landing/payments/_incoming/; publish to/data/nfs/raw/payments/year=2020/month=MM/. - Load: for each file run
hdfs dfs -putto_incoming(environment-dependent), one file at a time, logging the command and exit code. - Validate before publish: compare file name, byte size, row count and SHA-256 against the manifest; check the replication factor with
hdfs dfs -stat "%r"; any mismatch keeps the file in_incoming. - Publish:
hdfs dfs -mvinto the month folder, then set mode 750 and ownersvc_ingestwith groupfinance_data; write a_VALIDATEDmarker listing the checks. - Failed upload: list
_incoming, remove only the partial file for that month (it is not yet published), re-run the same-putwith the same name and validate again. Never publish a file that has not passed validation. - DataNode loss: run
hdfs dfsadmin -reportandhdfs fsck /data/nfs/raw/payments; under-replicated blocks that fall in number over time mean re-replication is working; missing or corrupt blocks mean escalate to the platform team immediately and restore from the source SFTP files or the second copy. - Close-out: record per-month results, final file counts, final byte totals and the finance control comparison; archive the manifest.
Independent practice
Produce an HDFS ingestion, validation and recovery runbook for a dataset you know, or for Northline's seven-year payment history, and test its validation logic on synthetic files.
Acceptance criteria
- Defines a directory layout with landing, staging, published and quarantine areas and partition-style folders for the main filter keys.
- Lists the commands for create, upload, inspect, publish, permission, replication and delete steps, each marked environment-dependent with the assumed Hadoop version.
- Specifies owners and permissions using a service account and groups, with no world-writable paths and no credentials in scripts.
- Defines validation checks (file count, bytes, rows, control total, checksum, replication health) with explicit pass criteria and an example manifest format.
- Covers at least four failure scenarios (partial upload, duplicate file, DataNode loss, accidental delete) with detection, recovery and validation for each.
- Addresses small files (target size, compaction, files-per-directory alert) and data locality or splittability of the chosen format.
- Includes a migration or rollback plan, escalation contacts by role and a stop condition for publishing.
Common mistakes
- Trusting an exit code as proof of a complete copy.
- Uploading directly into the published folder so consumers see partial data.
- Retrying with a new file name instead of an idempotent name.
- Setting
chmod 777to fix a permission error. - Treating replication as a backup, then deleting data with
-skipTrash. - Landing millions of tiny files, or large gzip text files that cannot be split.
- Comparing an HDFS composite checksum with a local file hash as if they were the same algorithm.
- Copying between clusters without validating sizes and checksums afterwards.
- Putting credentials for object stores in command lines or shell history.
- Forcing the NameNode out of safe mode to "get going" without finding out why it is waiting.
Quick check
- What does the NameNode store, and does file data pass through it during an upload?
- Why is it safer to upload to
_incomingand then move the file? - Why is replication not a backup?
- Name two checks you would run before declaring a copied month valid.
- What makes the small-file problem hurt both the NameNode and job performance?
Answers:
- Metadata: namespace, permissions and the file-to-block map. File data flows directly between the client and DataNodes, not through the NameNode.
- Consumers read only published folders, so partial or invalid files are never visible; the move within one HDFS namespace is a quick metadata operation.
- Replication copies deletions and corruptions as well as good data and protects only against hardware loss; backups, snapshots, trash and an external copy protect against deletion and logical errors.
- Any two of: file count and byte size against the manifest, row count, control total against the source system, content checksum, replication or
fsckhealth. - Every file and block is an object in NameNode memory, and each small file usually creates its own task, so memory and scheduling overhead grow while useful work per task shrinks.
Quiz alignment
The quiz (QUIZ_DAI2) covers blocks and replication, directory layout, core hdfs dfs commands, permissions, data locality and splittable formats, the small-file problem, copy validation, failure recovery and migration, using the payment backfill, duplicate-file and retail archive cases.
Lesson summary
HDFS splits files into replicated blocks tracked by the NameNode. Use a landing, validate, publish pattern with idempotent names, set ownership and permissions explicitly, keep files large and partition-friendly and prove each copy with counts, sizes, row totals and checksums before it is visible. Replication handles node loss but not deletion or logical error, so add trash, snapshots and an external copy. Migrate in waves with distcp or provider tools, validate each wave and keep a rollback. Treat every command as environment-dependent and test it on non-production first.
Bridge to the next lesson
With files landed and validated, the next lesson, Warehouses, Lakes & Lakehouse, asks where such data should live in a wider architecture: how OLTP differs from OLAP, how bronze, silver and gold layers organise data and how formats, metadata and governance serve both analytics and AI workloads.
Sources
- Apache Hadoop, File System Shell: https://hadoop.apache.org/docs/stable/hadoop-project-dist/hadoop-common/FileSystemShell.html
- Apache Hadoop, HDFS Commands Guide: https://hadoop.apache.org/docs/stable/hadoop-project-dist/hadoop-hdfs/HDFSCommands.html
- Apache Hadoop, HDFS Architecture (replica placement, safe mode, data organisation): https://hadoop.apache.org/docs/stable/hadoop-project-dist/hadoop-hdfs/HdfsDesign.html
- Apache Hadoop, HDFS Permissions Guide: https://hadoop.apache.org/docs/stable/hadoop-project-dist/hadoop-hdfs/HdfsPermissionsGuide.html
- Apache Hadoop, HDFS Snapshots: https://hadoop.apache.org/docs/stable/hadoop-project-dist/hadoop-hdfs/HdfsSnapshots.html
- Apache Hadoop, DistCp Guide: https://hadoop.apache.org/docs/stable/hadoop-distcp/DistCp.html
- Apache Hadoop, Hadoop: Rack Awareness: https://hadoop.apache.org/docs/stable/hadoop-project-dist/hadoop-common/RackAwareness.html
- Apache Hadoop, Hadoop in Secure Mode: https://hadoop.apache.org/docs/stable/hadoop-project-dist/hadoop-common/SecureMode.html
- Python 3 standard library,
hashlib: https://docs.python.org/3/library/hashlib.html (example tested with Python 3.11+, standard library only)
Northline Consumer Goods and Northline Financial Services, their paths, accounts, volumes and files are illustrative and synthetic. Hadoop commands, defaults (block size, replication, trash interval) and policies are environment-dependent; confirm them against the documentation for your version and distribution before use.