Summary#
A distributed file system (DFS) makes thousands of ordinary servers look like one giant file system. You get directories, file names, open, read and append. The bytes of each file are split into large chunks (or blocks), spread across many machines and replicated (or erasure-coded), so a disk, a server or a whole rack can fail without losing data.
The classic design comes from the Google File System (GFS) ("The Google File System", Ghemawat, Gobioff and Leung, SOSP 2003). Its open-source clone, the Hadoop Distributed File System (HDFS), became the storage layer of the whole Hadoop and Spark ecosystem. Both split the problem into two roles:
- One metadata server (the GFS master or HDFS NameNode). It holds the namespace (the directory tree), the file-to-chunk mapping and chunk locations, all in memory.
- Many data servers (GFS chunkservers or HDFS DataNodes). They store chunks as local files on their disks. Clients talk to them directly for data, so the metadata server never touches file contents.
This page explains:
- why this split works, and the design assumptions behind it: huge files, appends, streaming reads, commodity hardware that fails constantly;
- how GFS works: 64 MB chunks, leases that pick a primary replica to order mutations, the separation of data flow from control flow, the record append operation, and its relaxed consistency model;
- how HDFS works: the NameNode and DataNodes, rack-aware replica placement, the write pipeline, and how the single NameNode was made highly available (QJM, ZKFC, Observer NameNodes) and scaled out (federation, router-based federation);
- the small-files problem, and why 100 million tiny files can break a cluster that easily stores petabytes of big files;
- erasure coding in HDFS 3: Reed-Solomon RS(6,3) cuts storage overhead from 3× to 1.5×, and costs you in reconstruction;
- the successors: Google Colossus (distributed metadata in Bigtable), Ceph (no central metadata server, using CRUSH), Facebook Tectonic, plus Lustre, Ozone, JuiceFS, 3FS and others;
- DFS vs object storage vs block storage: which to use when, and why most new data lakes live on S3-style object stores (Object Storage and Blob Storage).
In interviews you rarely design a DFS from scratch, though "design GFS" and "design HDFS" do come up for infrastructure roles. You do constantly use one, or its modern replacement, object storage. Knowing its internals explains why big data systems behave the way they do: why files are immutable, why Spark wants 128 MB+ files, why rename is cheap on HDFS and expensive on S3, and why "move compute to data" was once the rule.
Why It Exists#
In the early 2000s Google had to store and process the whole crawled web: hundreds of terabytes, growing fast, on thousands of cheap commodity servers. Commercial storage (big NAS or SAN arrays) was too expensive and didn't scale to that size. Single-machine file systems obviously couldn't hold it.
So Google built a file system around their actual workload, which looked nothing like a desktop file system's. The GFS paper lists the assumptions explicitly:
- Component failures are the norm, not the exception. With thousands of machines and tens of thousands of disks, something is always broken: disks, memory, connectors, power supplies, operating systems and application bugs. Monitoring, error detection, fault tolerance and automatic recovery must be built in.
- Files are huge. Multi-gigabyte files are common, and each holds many application objects such as web documents. Managing billions of kilobyte-sized files is not the goal. Block size and I/O patterns are designed for big files.
- Most files are mutated by appending, not overwriting. Random writes within a file are practically nonexistent. Once written, files are only read, often sequentially. Examples are crawl outputs, logs, intermediate MapReduce results and archival data.
- Reads are mostly large streaming reads (hundreds of KB to MBs, sequentially), plus some small random reads.
- Many clients append to the same file concurrently, as in producer–consumer queues or many-way merges. Atomic append with minimal synchronisation is essential.
- High sustained bandwidth matters more than low latency. Batch jobs care about throughput.
These assumptions justify several choices:
- Huge blocks reduce metadata and client–master interaction.
- A single master is simple, and is made viable by keeping it out of the data path.
- Relaxed consistency with an atomic append keeps concurrent appends fast.
- Replication across racks survives failures.
- A custom API rather than POSIX avoids paying for semantics nobody needs.
Then came MapReduce ("MapReduce: Simplified Data Processing on Large Clusters", Dean and Ghemawat, OSDI 2004), which ran computation on the machines that stored the data. Input splits were aligned with chunks, so most map tasks read from local disk instead of the network. The pair of a DFS plus a data-local compute framework became the template for Hadoop (HDFS plus MapReduce, started in 2006 at Yahoo), and then for an industry.
Why not just use object storage? Today you often should. But a DFS gives things that early object stores didn't:
- Hierarchical namespace with cheap, atomic directory renames. Job output committers relied on renaming a temporary directory into place.
- Append to existing files.
- Data locality: compute scheduled on the nodes that hold the blocks.
- Strong consistency of metadata operations. S3 only became strongly consistent for reads after writes in December 2020.
- Low-latency access within the cluster, without HTTP overhead per request.
How It Works#
The core idea: separate metadata from data#
Every DFS in the GFS family has the same skeleton:
- The client asks the metadata server where data lives, caches the answer, and then streams bytes directly to and from the data servers. The metadata server handles small, fast requests (a few hundred bytes each), not gigabytes of data. That's why a single machine can coordinate thousands of servers.
- The data servers store chunks as ordinary files on local disks (ext4, XFS) and report which chunks they hold.
- The metadata server tracks everything else, and directs background work: re-replicating chunks that lost a copy, rebalancing disks, garbage collection.
GFS architecture#
Chunks. Files are divided into fixed-size 64 MB chunks. Each chunk has a globally unique, immutable 64-bit chunk handle, assigned by the master at creation. Each chunk is stored as a Linux file on a chunkserver and replicated on 3 chunkservers by default; users can choose other replication levels per file or namespace region.
Why 64 MB, when local file systems used 4 KB blocks?
- Fewer master interactions. A client reading a 1 GB file sequentially asks the master about 16 chunks, not 250,000 blocks. Caching chunk locations for a multi-terabyte working set fits easily in the client.
- Persistent TCP connections. A client doing many operations on one large chunk keeps one connection to the chunkserver.
- Small metadata. The master stores less than 64 bytes of metadata per 64 MB chunk. So 1 PB of data is about 16 million chunks, which is about 1 GB of master RAM, plus a little more for replica locations.
- Downside: hot spots. A small file is one chunk. If hundreds of clients read the same small file (the paper's example is an executable launched by a batch job on many machines), its 3 chunkservers get overloaded. GFS fixed this case with a higher replication factor for such files, and by staggering start times.
Lazy space allocation avoids the obvious waste: a chunk replica is a plain Linux file that grows only as data is written. A 1 KB file uses 1 KB on disk, not 64 MB.
Master metadata comes in three kinds, all kept in memory:
- The namespace: the tree of files and directories, stored as a lookup table from full pathname to metadata, with prefix compression.
- The mapping from files to chunks: an ordered list of chunk handles per file.
- The locations of each chunk's replicas.
The first two are made durable by logging every change to an operation log on the master's disk, replicated to remote machines. A change is acknowledged to the client only after its log record is flushed both locally and remotely. To bound recovery time, the master checkpoints its state when the log grows: a compact B-tree-like image that can be memory-mapped. Recovery loads the latest checkpoint and replays only the log since then.
Chunk locations are not persisted. The master asks every chunkserver at startup, and keeps current through regular HeartBeat messages. This is a deliberate simplification. The chunkserver has the final word about what's on its own disks (disks die, chunkservers get renamed or restarted), so trying to keep a persistent, consistent copy on the master would be pointless.
Reads. To read byte offset 200,000,000 of /crawl/2003/part-17:
- The client converts the offset to a chunk index: 200,000,000 / 67,108,864 gives chunk index 2.
- It asks the master for (file name, chunk index). The master replies with the chunk handle and replica locations, and typically also returns information for the next few chunks, which saves round trips.
- The client caches this, keyed by file name and chunk index, until the entry expires or the file is reopened.
- It sends the read (chunk handle, byte range) to the closest replica, which is often on the same rack. Further reads of the chunk need no master interaction.
Failure detection and repair.
- Chunkservers send HeartBeats; if a server is silent too long, the master treats its replicas as lost.
- Re-replication is prioritised by need. A chunk with one remaining replica goes before one with two, and chunks blocking client progress go first.
- Rebalancing moves replicas to even out disk usage and load.
- Placement spreads replicas across racks, so that a rack switch or power failure doesn't take all copies. Reads can use the bandwidth of several racks, at the cost of cross-rack write traffic.
Leases and mutation order#
A mutation is a write or an append to a chunk, and it must be applied to all replicas in the same order. GFS avoids having the master order every mutation by granting a lease:
- The master gives one replica a chunk lease, making it the primary. The lease has an initial timeout of 60 seconds, and extensions are piggybacked on HeartBeats while mutations continue.
- The primary picks a serial order for all mutations to the chunk. All replicas apply mutations in that order.
- If the master loses contact with the primary, it waits for the lease to expire before granting a new one, so two primaries can never exist at once. This is a time-based form of fencing, which relies on bounded clock drift (Time, Clocks and Ordering).
Separating data flow from control flow. The write protocol pushes the data first, along a chain of chunkservers. It sends the control (the "commit" with serial numbers) only after every replica has the data.
Why push data along a chain rather than from the client to all three in parallel?
- Each machine's full outbound bandwidth is used for one transfer, instead of being split three ways.
- Each machine forwards to the closest machine that hasn't received the data yet, using network topology (distances estimated from IP addresses). This avoids slow inter-switch links.
- Pipelining. A chunkserver starts forwarding as soon as it receives the first bytes, over full-duplex links.
The paper gives the ideal time to push B bytes to R replicas as B/T + R·L, where T is network throughput and L is the latency per hop. With 100 Mbps links and L well under 1 ms, 1 MB takes about 80 ms, almost independent of the replica count.
If a secondary fails, the write returns an error. The modified region is now inconsistent: some replicas applied it and others didn't. The client retries. Correctness comes from the application, through the record-append semantics below.
Record append: at-least-once atomic appends#
Many GFS files were queues with many concurrent producers, or the outputs of many-way merges. With ordinary writes, every producer would need a distributed lock to agree on offsets. GFS instead provides record append: the client gives only the data, and GFS appends it atomically, at least once, at an offset GFS chooses, and returns that offset.
How it works:
- The client pushes data to all replicas of the last chunk of the file, then sends the append request to the primary.
- The primary checks whether the record fits in the current chunk.
- If it doesn't fit, the primary pads the chunk to 64 MB, tells the secondaries to pad too, and replies "retry on the next chunk".
- If it fits, the primary appends at its current end offset, and tells the secondaries to write at exactly that offset.
- Record size is limited to one quarter of the chunk size (16 MB), so the worst-case padding waste stays bounded.
- If the append fails on any replica, the client retries. Replicas may now hold duplicate records (the retry succeeded on replicas where the first attempt had already landed), or partial records, padding or garbage in the failed region.
GFS guarantees only that the data is written at least once as an atomic unit at the same offset on all replicas, if the operation reports success. Replicas are not bytewise identical.
Applications cope by making records self-validating and identifiable:
- each record includes a checksum, so readers skip padding and fragments;
- each record includes a unique id, so readers drop duplicates when they matter.
The design pushes a little complexity to the application in exchange for lock-free concurrent appends at full bandwidth. Kafka's log segments and modern idempotent producers inherit this way of thinking (Delivery Guarantees: At-Most, At-Least and Exactly-Once).
The GFS consistency model#
GFS defines the state of a file region after a mutation in two terms:
- Consistent: all clients see the same data, whichever replica they read.
- Defined: consistent, and clients see the mutation's whole contents.
| Operation | Serial success | Concurrent successes | Failure |
|---|---|---|---|
| Write | Defined | Consistent but undefined: data from several writes mingled in fragments | Inconsistent |
| Record append | Defined, possibly interspersed with inconsistent padding or duplicates | Same as serial: each record defined, with padding or duplicates between | Inconsistent |
Metadata (namespace changes) is atomic and strongly consistent. The master handles it, with locking and the operation log. Only file data has relaxed semantics.
Practical consequences that shaped GFS applications:
- Prefer appends to overwrites. Writers create files, append, then atomically rename the file to a permanent name when it's complete, or write checkpoints that readers use to know how far data is valid.
- Readers only process up to the last checkpoint and validate each record's checksum.
- Stale replicas are detected with chunk version numbers. The master bumps a chunk's version whenever it grants a new lease. A replica that missed mutations while its server was down has an old version, and the master removes it in garbage collection and never returns it to clients. Clients compare version numbers when caching, too.
Other GFS mechanisms worth knowing#
- Snapshots. Copying a file or directory tree is nearly instant, using copy-on-write. The master revokes outstanding leases on the affected chunks, logs the snapshot, and duplicates only the metadata. The first later write to a shared chunk makes the chunkservers copy it locally (no network transfer) before the write proceeds.
- Namespace locking. There's no per-directory data structure listing files. Each operation takes read locks on every ancestor path and a read or write lock on the leaf. Creating
/home/user/footakes read locks on/homeand/home/userand a write lock on/home/user/foo. A concurrent snapshot of/home/user, which needs a write lock on it, is serialised against the create. Many creates in one directory run in parallel. - Lazy garbage collection. Deleting a file just renames it to a hidden name with a timestamp. A background scan removes hidden files older than 3 days (configurable), so accidental deletes can be undone. Orphaned chunks (those no file references) are found when chunkservers report their chunks in HeartBeats, and the master replies with the handles that can be deleted. This is simpler and more robust than eager distributed deletion, because messages can be lost and servers can be down.
- Data integrity. Each chunkserver checksums its own data independently, using a 32-bit checksum per 64 KB block, and verifies it on every read before returning data. A mismatch returns an error, and the master re-replicates from a good copy. Replicas can't be compared with each other, because they aren't bytewise identical. Idle chunks are scanned in the background to catch rot in rarely read data.
- Master replication. The operation log and checkpoints are replicated. If the master machine dies, monitoring outside GFS starts a new master process elsewhere, and clients use a DNS alias for the master. Shadow masters serve read-only metadata, slightly behind the primary, while it's down.
Scale in the paper. The paper reports that its largest cluster provided hundreds of terabytes across over a thousand disks on over a thousand machines, accessed concurrently by hundreds of clients. Master memory and CPU weren't the bottleneck at that size. They became one later, as described under Colossus below.
HDFS: NameNode and DataNodes#
HDFS began in 2006 as part of Apache Hadoop. Doug Cutting and Mike Cafarella built Nutch and Hadoop following the GFS and MapReduce papers, and Yahoo invested heavily in it. "The Hadoop Distributed File System" (Shvachko, Kuang, Radia and Chansler, IEEE MSST 2010) reports on managing 25 petabytes of data at Yahoo, on clusters of thousands of nodes. The architecture maps almost one-to-one onto GFS:
| GFS | HDFS | Notes |
|---|---|---|
| Master | NameNode | Namespace and block map in RAM |
| Chunkserver | DataNode | Blocks stored as local files, plus a .meta checksum file |
| Chunk, 64 MB | Block, 128 MB by default since Hadoop 2 (64 MB in Hadoop 1) | Configurable per file |
| Operation log and checkpoint | EditLog and FsImage | Checkpointing merges edits into a new image |
| Record append, multi-writer | Single writer per file; append added later; hflush and hsync | Simpler semantics |
| Chunk version number | Generation stamp per block | Detects stale replicas after pipeline failure |
| Lease to primary replica | Lease to the writing client (one writer per file) | Different meaning of "lease"! |
The NameNode stores:
- The namespace: inodes for files and directories, with permissions, quotas, modification times and replication factors.
- The block map: file → ordered list of block ids, and block → DataNodes holding replicas. Block locations, as in GFS, come from block reports and aren't persisted.
- The persistent state: the FsImage (a checkpoint of the namespace) plus the EditLog (a journal of every change since). On startup the NameNode loads the FsImage, replays the EditLog, then waits in safe mode until enough DataNodes have reported blocks to meet a minimum replica threshold. On a large cluster this used to take tens of minutes, which is one reason high availability matters so much.
The confusingly named Secondary NameNode is not a standby. It periodically downloads the FsImage and EditLog, merges them into a new FsImage, and uploads it back, so the EditLog doesn't grow without bound. In HA setups, the Standby NameNode does this checkpointing instead.
DataNodes:
- store each block replica as two local files: the data, and its checksum metadata (CRC32C per 512-byte chunk by default);
- send a heartbeat every 3 seconds, carrying capacity and usage stats, and receive commands in the replies: replicate this block, delete these, re-register;
- send a full block report periodically (every 6 hours by default) and incremental block reports when blocks are added or removed.
The NameNode declares a DataNode dead after about 10.5 minutes without heartbeats by default. The delay is deliberately long, to avoid a re-replication storm when a whole rack reboots briefly. Then it schedules re-replication of that node's blocks from surviving replicas.
Reads in HDFS:
- The client calls
open(). The NameNode returns the first batch of block locations, sorted by network distance from the client: same node, then same rack, then other racks. - The client reads from the closest DataNode, verifying checksums. On a failure or checksum mismatch it reports the bad replica and moves to the next.
- Short-circuit local reads: when the client runs on the DataNode holding the block, which is the case for data-local MapReduce or Spark tasks, it can read the block file directly from local disk through a passed file descriptor (Unix domain socket), bypassing the DataNode's TCP path.
Replica placement and the write pipeline#
Rack awareness. An administrator configures a topology script that maps each DataNode to a network location such as /dc1/rack17. Inter-rack bandwidth is scarcer than intra-rack bandwidth, and racks fail together (top-of-rack switch, power).
The default placement policy for replication factor 3:
- First replica: on the writer's own node if the writer is a DataNode, otherwise on a random node that isn't too busy or full.
- Second replica: on a node in a different rack.
- Third replica: on a different node in the same rack as the second.
- Any further replicas are spread randomly, with at most 2 replicas per rack when possible.
This survives the loss of a whole rack, which still leaves at least one copy. It keeps write cost low: only one cross-rack transfer (first to second), with the second-to-third hop staying inside a rack. Reads can use two racks' bandwidth.
The write pipeline follows GFS's chained data push, with explicit packet acks:
Key details:
- Packets (64 KB by default) flow down the pipeline. The client keeps a data queue of packets to send and an ack queue of packets sent but not yet acknowledged by all DataNodes in the pipeline.
- Pipeline failure recovery. If a DataNode in the pipeline fails:
- The client closes the pipeline and moves unacknowledged packets back to the front of the data queue.
- The NameNode gives the surviving replicas a new generation stamp. The failed node's partial replica has the old stamp, so it's recognised as stale and deleted when that node comes back.
- The pipeline is rebuilt from the remaining nodes, optionally adding a replacement DataNode, and writing continues.
- The block is under-replicated until the NameNode schedules re-replication in the background.
- Durability semantics.
hflush()guarantees that data written so far has reached the memory of all pipeline DataNodes, so it's visible to new readers.hsync()additionally forces it to disk on each DataNode.close()flushes and then completes the file.- HBase's write-ahead log on HDFS depends on
hflushandhsync.
- Single writer, enforced with leases. The client holding the file's lease is its only writer, and renews it periodically.
- If it stops renewing (the client crashed), another client may take over after the soft limit (1 minute).
- After the hard limit (historically 1 hour, configurable in recent versions), the NameNode itself runs lease recovery. It picks a primary DataNode to synchronise the last block's replicas to a common length, then closes the file.
- The lease is a lock with a timeout, the same idea as a distributed lock (Distributed Locks).
Housekeeping tools:
- the Balancer moves blocks from full to empty DataNodes, under a bandwidth cap, after cluster expansion;
- decommissioning drains a node before removing it, by re-replicating all its blocks elsewhere;
- disk-level balancing (the
diskbalancer) evens out usage across a DataNode's own disks; - heterogeneous storage policies (HOT, WARM, COLD, ALL_SSD, ONE_SSD) put replicas on SSD, disk or archive storage. Together with the Mover tool, this lets you tier data by age (Data Lifecycle, Tiering and Retention).
NameNode high availability#
In Hadoop 1, the NameNode was a single point of failure. If it crashed, the whole cluster was unavailable until someone restarted it, and loading the FsImage plus waiting for block reports could take an hour on a big cluster. Planned maintenance (upgrades, config changes) meant downtime too. Hadoop 2 introduced HA NameNodes:
Sharing the EditLog. The active NameNode writes each edit to a Quorum Journal Manager (QJM): a group of 2N+1 JournalNodes, usually 3, and an edit is durable when a majority acknowledge it. The standby continuously reads edits from the JournalNodes and applies them, so its in-memory namespace is only moments behind. An older option was a shared NFS directory, which just moved the single point of failure onto the filer.
Fencing the old active. The danger in any failover is split brain: two NameNodes both believing they're active and both writing edits.
- QJM prevents this with epoch numbers. A NameNode becoming active obtains a new, higher epoch from a majority of JournalNodes. JournalNodes then reject writes from any lower epoch, so a paused old active, perhaps stuck in a long GC pause, can't corrupt the log when it wakes up. This is the same idea as Paxos ballot numbers and Raft terms (Consensus: Raft and Paxos).
- Admins can still configure extra fencing methods, such as
sshfenceto kill the old process, or a shell script that cuts its power, as defence in depth.
Hot block locations. DataNodes send heartbeats and block reports to both NameNodes, so the standby already knows where every block lives. Failover needs no safe-mode wait, and usually completes within tens of seconds.
Automatic failover uses a ZooKeeper Failover Controller (ZKFC) process next to each NameNode:
- Health monitoring: it pings its local NameNode, and marks it unhealthy if it stops responding or reports a problem.
- Leader election: the healthy ZKFC whose NameNode is active holds an ephemeral lock znode in ZooKeeper. If its ZooKeeper session expires (the host died or was partitioned) or its NameNode is unhealthy, the lock is released. The other ZKFC acquires it, fences the old active, and transitions its own NameNode to active.
This is a textbook use of a coordination service for leader election (Leader Election and Coordination Services).
Later improvements:
- More than two NameNodes. Hadoop 3 supports multiple standbys, for example one active and two standbys, so the cluster survives two failures.
- Observer NameNodes (Hadoop 3.x) are standbys that serve read requests. Most NameNode traffic is reads:
getBlockLocations,getFileInfo,listStatus. Offloading them to observers relieves the active. To keep read-your-writes consistency, the client tracks the last transaction id it has seen from the active. An observer serves its read only once it has applied edits up to that id, and the client can callmsyncto fetch the latest id. Observers make reads slightly stale but causally consistent (Consistency Models).
NameNode federation#
HA solves availability, not scale. One NameNode still holds the whole namespace in one JVM heap, and serialises mutations under one global namespace lock. Its limits:
- Memory. A common rule of thumb is about 150 bytes of heap per namespace object (each file, directory and block). A cluster with 400 million files and 400 million blocks needs about 120 GB of heap. JVM garbage collection pauses on heaps that size can last seconds.
- Throughput. Metadata operations (create, delete, open, list) top out at tens of thousands to around 100,000+ per second, depending on the mix. A huge batch job that opens a million files can saturate the NameNode for everyone.
- Isolation. One team's runaway job, with millions of creates, affects every other team.
Federation (Hadoop 2) runs several independent NameNodes, each owning a separate namespace volume: for example /user on NN1, /data/warehouse on NN2 and /tmp on NN3.
- Each NameNode manages its own block pool: the set of blocks belonging to its namespace.
- All DataNodes store blocks for all block pools and register with every NameNode. Storage is shared and namespaces are partitioned.
- NameNodes don't coordinate with each other at all, so each can be made HA independently.
How clients see one tree:
- ViewFs is a client-side mount table (
viewfs://cluster/) mapping path prefixes to NameNodes, like Unix mount points. Every client needs the same config, and moving a directory between namespaces means updating all clients. - Router-based federation (RBF), from Hadoop 3, adds a layer of stateless Routers that hold the mount table in a shared State Store and proxy client RPCs to the right NameNode. Clients see a single logical namespace. Admins can rebalance subtrees between NameNodes without touching clients.
Limits of federation:
- No atomic rename across namespaces. Renaming
/user/xto/data/xacross NameNodes becomes a copy plus a delete. - Manual partitioning of the namespace, and imbalance when one subtree grows fast.
- Still bounded per namespace. Each NameNode has the same single-JVM limits.
This is why Google replaced GFS's single master with Colossus's distributed metadata, and why Facebook built Tectonic.
The small-files problem#
HDFS and GFS are optimised for big files. Many small files, much smaller than a block, cause several kinds of damage:
-
NameNode memory. Every file costs roughly the same metadata whether it's 1 KB or 1 GB: about one inode plus one block, so ~300 bytes.
Data layout Objects Approximate NameNode heap 1 PB as 128 MB files (8 million files) About 16 million About 2.4 GB: trivial 1 PB as 1 MB files (1 billion files) About 2 billion About 300 GB: far beyond a practical JVM heap Same bytes, about 125 times more metadata.
-
Block reports and heartbeat load. Each DataNode reports millions of tiny blocks, and NameNode CPU goes into processing reports instead of serving clients.
-
Processing overhead. Classic MapReduce launches one map task per file, or per split, and a task has a startup cost of a second or more. Spark and Hive create one partition per file. Ten thousand 100 KB files become ten thousand tasks that each do milliseconds of work, and the job is dominated by scheduling.
-
I/O efficiency. Each small file means a NameNode RPC, a DataNode connection and a disk seek. Instead of streaming at about 150 MB/s per disk, you do random I/O at about 100 seeks per second on HDDs.
Where small files come from:
- streaming jobs writing a file per micro-batch per partition;
- over-partitioned tables, like
date/hour/country/devicewith tiny partitions; - many reducers each writing small outputs;
- landing raw events one file per event;
- incremental updates in table formats without compaction.
Fixes:
- Compaction jobs periodically merge small files into large ones. Target 128 MB–1 GB per file for columnar formats such as Parquet and ORC.
- Container formats pack many records into one file: SequenceFiles, Avro container files, or Parquet with many row groups.
- Hadoop Archives (HAR) pack files into an archive with an index. The NameNode sees one file, at the cost of slower reads.
- Reduce the number of output writers:
coalesceorrepartitionbefore writing, a reasonable partitioning scheme, and batch windows of minutes rather than seconds for streaming sinks. - CombineFileInputFormat and Spark's
maxPartitionBytescombine many small files into one task, which fixes the processing overhead but not the metadata. - Put tiny objects somewhere else. Use a store built for small values: HBase (rows in big HFiles on HDFS), a key-value store, or object storage, which has no central in-memory namespace. Apache Ozone was built by the HDFS community largely to handle billions of objects, with metadata in RocksDB instead of a JVM heap.
- Table formats with compaction: Apache Iceberg, Delta Lake and Apache Hudi track files in manifests and provide built-in compaction, or "optimize", operations (Data Pipelines, Warehouses and Lakes).
Facebook's photo store shows the same problem outside Hadoop. Haystack ("Finding a Needle in Haystack: Facebook's Photo Storage", Beaver et al., OSDI 2010) replaced a NAS where every photo was a file. Each photo read took several disk I/Os just for directory and inode metadata. Haystack packs millions of photos into large append-only volume files, with an in-memory index from photo id to (volume, offset, size). That gives about one disk I/O per read: the small-files solution at the storage layer.
Erasure coding in HDFS 3#
Three-way replication is simple and fast, but it stores every byte three times: a 200% storage overhead. For petabytes of cold data (old logs, last year's tables, archived raw events), most of that cost buys almost nothing, because the data is rarely read. Erasure coding (EC) gives the same or better durability at a fraction of the overhead.
The idea. Split data into k data units, then compute m parity units with a Reed-Solomon code ("Polynomial Codes over Certain Finite Fields", Reed and Solomon, 1960). You can reconstruct the original from any k of the k+m units. That means:
- it tolerates m simultaneous failures;
- storage overhead is (k+m)/k.
| Scheme | Storage for 1 TB | Overhead | Failures tolerated | Units read to repair one lost unit |
|---|---|---|---|---|
| 3× replication | 3 TB | 200% | 2 | 1, just copy |
| RS(3,2) | 1.67 TB | 67% | 2 | 3 |
| RS(6,3), the HDFS default policy | 1.5 TB | 50% | 3 | 6 |
| RS(10,4), used by Facebook's HDFS-RAID and f4 | 1.4 TB | 40% | 4 | 10 |
| XOR(2,1) | 1.5 TB | 50% | 1 | 2 |
Going from 3× to RS(6,3) on 10 PB of cold data saves 15 PB of raw disk: from 30 PB to 15 PB. At a few cents per GB per month all-in, that's millions of dollars a year. It also tolerates 3 failures instead of 2.
How HDFS 3 implements it (HDFS-7285, released in Hadoop 3.0, 2017):
- Striped layout. EC in HDFS stripes data across DataNodes in small cells (1 MB in the default
RS-6-3-1024kpolicy), rather than encoding whole 128 MB blocks.- Logical data is written round-robin as cell 1 to DataNode 1, cell 2 to DataNode 2, up to cell 6 to DataNode 6. Then 3 parity cells go to DataNodes 7–9, and the pattern repeats.
- The set of 9 internal blocks, one per DataNode, is a block group.
- Striping makes EC work for small and medium files. A 10 MB file still gets full EC protection, which wouldn't be true if you needed six whole 128 MB blocks before encoding.
- Policies per directory.
hdfs ec -setPolicy -path /archive -policy RS-6-3-1024k. New files under that path are erasure-coded. Existing files must be rewritten, by copying them, to convert. - Placement. The 9 internal blocks of a block group must sit on 9 different DataNodes, and ideally across at least 9 racks, or at least 3 racks so that a rack loss doesn't exceed 3 units. Small clusters can't use wide policies.
- Encoding and decoding cost. The client computes parity while writing, which costs CPU. Intel's ISA-L library provides vectorised Reed-Solomon (the native coder), which makes this cheap on modern CPUs.
The costs:
- Repair traffic. Reconstructing one lost 128 MB internal block in RS(6,3) means reading 6 units from 6 DataNodes and computing it. That's 6× the network and disk traffic of re-copying a replica. A failed 12 TB DataNode triggers about 72 TB of reads cluster-wide. The NameNode runs reconstruction as background tasks on DataNodes and throttles it.
- No data locality. A file's bytes are spread over 6 DataNodes in 1 MB cells, so no single node has a full block to read locally, and every read goes over the network. With fast datacenter networks this matters less than in 2006, but it's why EC fits cold data and replication fits hot data.
- Degraded reads. If a DataNode holding a needed cell is down, the client must read k other cells and decode on the fly, which costs higher latency and CPU.
- Limited operations. In early versions, append,
hflushandhsyncwere not supported on EC files, so EC suited write-once archival data. - Small-cluster limits. RS(6,3) needs at least 9 DataNodes, and RS(10,4) needs 14.
Repair-efficient codes. Reed-Solomon's repair cost (read k units to rebuild one) led to locally repairable codes (LRC):
- Azure LRC ("Erasure Coding in Windows Azure Storage", Huang et al., USENIX ATC 2012) groups 12 data fragments into two local groups of 6, each with a local parity, plus 2 global parities. That's an overhead of 16/12 ≈ 1.33×. The common single-failure repair reads only 6 fragments instead of 12.
- Xorbas ("XORing Elephants: Novel Erasure Codes for Big Data", Sathiamoorthy et al., VLDB 2013) added local parities to Facebook's HDFS RS(10,4), and roughly halved repair disk I/O and network traffic.
Facebook f4 ("f4: Facebook's Warm BLOB Storage System", Muralidhar et al., OSDI 2014) moved "warm" photos (older and rarely read) from Haystack, whose effective replication factor was 3.6, to RS(10,4) within a datacenter. Keeping a full RS(10,4) copy in a second datacenter gave an effective factor of 2.8. Storing instead an XOR of blocks from two datacenters in a third brought it down to 2.1. This is a clear illustration of tiering by temperature: hot data replicated for fast reads, warm and cold data erasure-coded for cost (Data Lifecycle, Tiering and Retention).
Durability arithmetic (simplified). Assume independent disk failures at an annual failure rate (AFR) of 2%, and that a failed unit is repaired within 6 hours.
- 3× replication: data is lost only if the other 2 replicas fail within the repair window of the first failure.
- The probability that one specific disk fails within 6 hours is about 0.02 × 6/8760 ≈ 1.4 × 10^-5.
- For both other replicas, that's about (1.4 × 10^-5)² ≈ 2 × 10^-10 per failure event.
- RS(6,3): data is lost if 3 more of the 8 other units fail within the window. That's about C(8,3) × (1.4 × 10^-5)³ ≈ 56 × 2.7 × 10^-15 ≈ 1.5 × 10^-13, about 1,000 times less likely per event than 3× replication, at half the storage.
Real systems also worry about correlated failures: a rack, a power domain, a bad firmware batch. That's why placement across failure domains matters as much as the code. Durability claims like S3's "eleven nines" combine codes, placement, fast repair and integrity scanning (Object Storage and Blob Storage).
Colossus, Ceph and modern successors#
Google Colossus
By the late 2000s, GFS's single master had become the limit for Google:
- Its memory capped the number of files per cell, which hurt applications that wanted many small files.
- Its latency hurt interactive applications like Gmail.
- Its failover took too long.
Sean Quinlan's interview "GFS: Evolution on Fast-forward" (ACM Queue, 2009) describes these pain points. Google's successor, Colossus, has never been described in a full paper. Public talks and a Google Cloud blog post ("A peek behind Colossus, Google's file system", 2021) describe its shape:
- Distributed metadata. The Colossus control plane consists of horizontally scalable curators, which handle metadata operations such as file creation. They store file system metadata in Bigtable rather than in one server's memory. This removes the file-count limit, which had been the root cause of the small-files problem.
- D file servers store the data on disks and flash, and clients read and write to them directly.
- Custodians run background tasks: durability (reconstructing lost data), disk-space balancing, and RAID-style maintenance.
- Reed-Solomon encoding is used widely, and data is placed according to storage tier and temperature (flash for hot, disk for colder).
- The bootstrap is recursive. Colossus metadata lives in Bigtable, and Bigtable stores its own data in Colossus. The smallest metadata, at the root, is stored with Chubby's help (Leader Election and Coordination Services).
Colossus underlies most Google storage products, including Cloud Storage, Bigtable, Spanner and BigQuery.
Ceph
Ceph ("Ceph: A Scalable, High-Performance Distributed File System", Weil, Brandt, Miller, Long and Maltzahn, OSDI 2006) takes a different path. It has no central server that knows where data lives. Placement is computed.
- RADOS (Reliable Autonomic Distributed Object Store) is the core. OSDs (object storage daemons, typically one per disk) store objects, replicate or erasure-code them among themselves, detect failures among peers, and recover data autonomously.
- Monitors (MONs), a small cluster of 3 or 5 running Paxos, maintain the cluster map: which OSDs exist, which are up, and the placement rules. The map is small, and every client and OSD caches it.
- CRUSH ("CRUSH: Controlled, Scalable, Decentralized Placement of Replicated Data", Weil et al., SC 2006) is a deterministic, pseudo-random hash-based placement function.
- Objects hash into placement groups (PGs).
- CRUSH maps each PG to an ordered list of OSDs, following a hierarchy of failure domains: "3 replicas in different racks", or "EC 4+2 across hosts".
- Any client holding the cluster map computes where an object lives. No lookup is needed, so there's no metadata bottleneck for data placement. When OSDs are added, only a proportional fraction of PGs move, much like consistent hashing (Consistent Hashing).
- Three interfaces on top of RADOS:
- RBD: block devices for VMs and Kubernetes volumes.
- RGW: an S3- and Swift-compatible object gateway.
- CephFS: a POSIX file system with a cluster of metadata servers (MDS). They dynamically partition the directory tree (dynamic subtree partitioning), moving hot subtrees between MDS nodes.
- BlueStore (since 2017) stores objects directly on raw block devices, with RocksDB for metadata, rather than on a local file system. "File Systems Unfit as Distributed Storage Backends: Lessons from 10 Years of Ceph Evolution" (Aghayev et al., SOSP 2019) explains why. Building on XFS or ext4 had caused years of pain: double journalling, slow metadata, and mismatched transaction semantics.
Ceph is popular for on-premises private clouds (it's the default storage for OpenStack and is used with Kubernetes through Rook). It's one system offering block, object and file storage.
Facebook Tectonic
Tectonic ("Facebook's Tectonic Filesystem: Efficiency from Exascale", Pan et al., FAST 2021) consolidated Facebook's many separate storage systems into one exabyte-scale, multitenant file system per datacenter: HDFS clusters for the data warehouse, plus Haystack and f4 for blobs.
- Metadata is disaggregated into three layers: a name layer (directories), a file layer (file → blocks) and a block layer (block → disks). Each is hash-partitioned and stored in ZippyDB, Facebook's Paxos-replicated, RocksDB-based key-value store. This avoids any single-node metadata limit.
- Chunk store: storage nodes store chunks. Blocks are replicated or Reed-Solomon encoded per tenant's needs.
- Client-driven, tenant-specific optimisations. The warehouse uses RS-encoded full-block writes for space efficiency. Blob storage uses replicated, quorum-appended writes for low latency.
- Result. Warehouse clusters that used to be many separate HDFS instances (each limited by its NameNode) became one Tectonic cluster per datacenter, with better utilisation and no more manual data placement across clusters.
Other systems worth knowing
| System | Design | Fits when |
|---|---|---|
| Lustre | Separate metadata servers (MDS and MDT) plus object storage servers (OSS and OST); POSIX; striping across OSTs; very high parallel bandwidth | HPC and supercomputers: many nodes reading and writing one huge file in parallel; AI training clusters |
| IBM Storage Scale, formerly GPFS | Shared-disk parallel file system with distributed locking; POSIX | Enterprise HPC, media, analytics needing POSIX at scale |
| GlusterFS | No metadata server; files placed by elastic hashing of names onto bricks | Simple scale-out NAS; small to medium on-prem deployments |
| Apache Ozone | Object store for the Hadoop ecosystem: Ozone Manager for the namespace (RocksDB plus Raft), Storage Container Manager, block containers | Replacing HDFS when you hit file-count limits but want Hadoop compatibility, using S3 and ofs:// interfaces |
| JuiceFS | POSIX file system with metadata in Redis, TiKV, MySQL or PostgreSQL and data chunks in an object store | POSIX semantics over S3 for ML training, shared home directories, legacy apps |
| Alluxio | A caching and virtualisation layer between compute and storage: HDFS, S3, GCS | Speeding up repeated reads of remote object storage for Spark, Presto and ML jobs |
| SeaweedFS | Haystack-inspired volume servers plus a master; optional filer for directories | Billions of small files or blobs on your own hardware |
| 3FS (Fire-Flyer File System, DeepSeek, open-sourced 2025) | Disaggregated design: metadata in FoundationDB, data chunks on SSDs replicated with CRAQ (chain replication), RDMA networking | Very high-throughput AI training and inference data loading across many GPU nodes |
| Cloud managed | Amazon EFS and FSx (NFS, Lustre, Windows, ONTAP), Google Filestore, Azure Files, Azure Data Lake Storage Gen2 (hierarchical namespace on Blob) | You need a shared file system without operating one |
Chain replication ("Chain Replication for Supporting High Throughput and Availability", van Renesse and Schneider, OSDI 2004) appears throughout this family. Writes enter at the head and propagate to the tail, and the tail acknowledges and serves reads, giving strong consistency with pipelined throughput. CRAQ ("Object Storage on CRAQ", Terrace and Freedman, USENIX ATC 2009) lets any replica serve reads for clean objects, scaling reads. It's GFS's chained data push turned into a full replication protocol.
DFS vs object storage vs block storage#
Three storage abstractions dominate. They differ in what you address, what operations you get and who can share it.
| Block storage | Distributed file system | Object storage | |
|---|---|---|---|
| Unit | Fixed-size blocks on a volume, addressed by offset | Files in a hierarchical directory tree | Immutable objects addressed by key in a flat bucket namespace |
| Examples | Amazon EBS, Google Persistent Disk, Azure Managed Disks, iSCSI SAN, Ceph RBD | HDFS, CephFS, Lustre, EFS, GPFS, JuiceFS | Amazon S3, Google Cloud Storage, Azure Blob, MinIO, Ceph RGW |
| Access | Mounted by one host (mostly), formatted with a local file system | Mounted or accessed through a client library by many hosts | HTTP API (PUT, GET, LIST, DELETE) from anywhere |
| Mutations | In-place random writes at any offset | Append; random writes depending on the system: HDFS has none, Lustre and CephFS have full POSIX | Replace the whole object; no partial updates, but multipart upload |
| Rename | N/A | Atomic and cheap (metadata only), including directories | No real rename: copy plus delete, per object, and not atomic for "directories" |
| Listing | N/A | Fast directory listing from the namespace | Prefix LIST, paginated (1,000 keys per page in S3) |
| Latency | Sub-millisecond to a few ms | ms for data and metadata | Tens of ms for first byte, per request |
| Scale | One volume: up to tens of TB | Petabytes to exabytes; metadata server limits apply | Effectively unlimited objects and bytes |
| Cost | Highest per GB; pay for provisioned size | Medium; you run it, or pay a managed premium | Lowest per GB, with cheaper archive tiers; pay per request |
| Best for | Databases, VM boot disks, anything needing a local-disk illusion | Hadoop-era analytics, HPC, shared POSIX workspaces, ML training needing POSIX | Data lakes, backups, media, user uploads, logs, static assets |
The modern default for analytics is object storage, not HDFS:
- Disaggregated compute and storage. In 2006, the network was slow (1 Gbps per node, oversubscribed between racks), so moving computation to the data was essential. Today datacenter networks run 25–100+ Gbps per node with flatter topologies, and reading from remote storage is fast enough. Separating them lets you scale and pay for compute and storage independently: spin up 500 Spark executors for an hour, then release them, while the data stays in S3.
- Durability and operations. S3 provides very high durability and availability without you running NameNodes, JournalNodes and ZooKeeper, or replacing disks.
- Strong consistency. Since December 2020, S3 provides strong read-after-write consistency for PUTs and DELETEs, including LIST. This removed the eventual-consistency hacks (S3Guard) that Hadoop on S3 used to need.
- Cost. Object storage per GB is typically cheaper than replicated block storage under a self-run HDFS, especially with lifecycle tiering.
But object storage lacks file-system semantics, and that bit the Hadoop ecosystem:
- The rename problem. Hadoop's job output committer wrote task output to a temporary directory, then renamed it into place as the atomic commit. On HDFS that's a single metadata operation. On S3 it's a copy plus delete for every object: slow, proportional to data size, and not atomic, since readers could see half-committed output. The solutions were S3A committers (staging and magic committers, which use multipart uploads completed at commit time), and then table formats.
- Table formats (Apache Iceberg, Delta Lake, Apache Hudi) put an atomic metadata layer on top of object storage. A table is a set of immutable data files listed in manifest files, and a commit is one atomic swap of a pointer to the new metadata (through a catalog, or a conditional write). You get snapshot isolation, time travel and schema evolution without needing rename, or even LIST.
- Listing cost and latency. Listing millions of keys is slow, and each request has a cost. Table formats avoid listing by tracking files explicitly.
- POSIX-needing applications (legacy tools, some ML frameworks, shared home directories) need a file system interface. JuiceFS, Alluxio, Mountpoint for Amazon S3, gcsfuse or a managed NFS (EFS, Filestore) fill that gap, with semantics limits you must check.
- Hierarchical namespaces in object stores. Azure Data Lake Storage Gen2, and Google Cloud Storage buckets with hierarchical namespace enabled, add real directories with atomic rename to object storage. They're converging the two worlds.
For an application like Dropbox or an upload service, don't run a DFS. Store file bytes in blob storage and metadata in a database, so storage scales and survives server loss, unlike files kept on the app server's own disk. Better still, let clients upload directly to blob storage using presigned URLs, so bytes never pass through your servers. Use blob storage event notifications to mark uploads complete in the metadata DB, and serve downloads through a CDN. See Pattern: Handling Large Files and Blobs and Design File Storage and Sync (Dropbox / Google Drive).
Interestingly, at its scale Dropbox later moved the bulk of user data from S3 into its own in-house storage system, Magic Pocket (announced in 2016). That's the classic build-versus-buy inflection: at exabyte scale, owning the storage stack can pay off.
When to Use It#
Use a distributed file system, or a managed equivalent, when:
- Many machines must read and write the same large datasets through a file-like interface, and the data is far bigger than one server: hundreds of TB to many PB.
- The workload is throughput-oriented batch processing: large sequential reads and writes, write-once-read-many files. This is MapReduce, Spark, Hive and Presto on an on-prem cluster.
- You need file-system semantics that object stores lack: atomic directory rename, append, cheap listing, hierarchical permissions or quotas. Or POSIX itself (random writes,
mmap, locks) for HPC and legacy applications. - Data locality still matters. On-prem clusters have limited network bandwidth, so co-locating compute with storage saves the network.
- Massively parallel I/O to shared files, as in HPC simulations and large-scale AI training checkpoints, needs a parallel file system like Lustre, GPFS or 3FS.
- You're running a private cloud and need block, object and file storage from one self-managed system, as with Ceph.
Pick something else instead when:
- You're in the cloud building a new data lake. Use object storage (S3, GCS, Azure Blob) plus a table format (Iceberg, Delta, Hudi). There's no NameNode to run, storage is cheaper, and compute is elastic.
- You're storing user uploads, media or backups for an application. Use object storage with presigned URLs and a CDN (Object Storage and Blob Storage).
- You need low-latency random reads and writes of small records. Use a database or key-value store: Bigtable and HBase sit on top of a DFS precisely because the DFS itself is bad at this.
- One server needs a disk. Use block storage (EBS, Persistent Disk).
- The data is billions of tiny files. A classic single-NameNode DFS will choke. Use an object store, Ozone, a KV store, or pack the files into containers.
When NOT to Use It#
- Don't propose HDFS by reflex in a cloud system design interview. "Store raw data in S3" is the modern answer, and HDFS signals a 2012 mindset unless the scenario is explicitly on-prem.
- Don't use a DFS as a database. No transactions across files, no secondary indexes, no efficient small updates.
- Don't run your own DFS for a small team. Operating NameNodes, JournalNodes, ZooKeeper, balancers and disk replacements is a full-time job. Managed services exist.
- Don't treat an NFS-mounted shared file system as infinitely scalable. Metadata-heavy workloads, like millions of small files or
lson huge directories, overwhelm metadata servers there too.
How to Implement It#
You'll rarely build a DFS from scratch, but you may deploy, configure or design one. The steps for a production HDFS cluster, and the reasoning behind them:
-
Size the cluster. Start from usable capacity, the replication factor or EC policy, growth, and headroom.
- Example: 2 PB usable at 3× replication is 6 PB raw. With 25% free-space headroom that's 8 PB raw. At 120 TB per node (12 × 10 TB disks), that's about 70 DataNodes.
- Size NameNode heap at about 1 GB per million blocks plus files, with generous headroom.
-
Plan failure domains. Configure a rack topology script so the placement policy can spread replicas. Use at least 3 racks for 3× replication, and 9+ racks for RS(6,3) with rack-level tolerance.
-
Make the NameNode highly available. Run 2–3 NameNodes, 3 or 5 JournalNodes (QJM) and a ZooKeeper ensemble of 3 or 5, plus ZKFC for automatic failover and fencing. Use Observer NameNodes if read RPCs dominate.
-
Choose block size and replication per dataset. Keep 128–256 MB blocks for big analytic files. Use 3× replication for hot data, and erasure coding (RS-6-3-1024k) for cold directories. Set storage policies (HOT, WARM, COLD) for tiering.
-
Prevent small files at the source: target big output files in jobs, run compaction, and apply namespace quotas per team (file-count and space quotas).
-
Secure it. Use Kerberos for authentication, plus HDFS permissions and ACLs, Apache Ranger for central policies, wire encryption (RPC privacy, TLS for data transfer), and transparent encryption zones with a KMS for data at rest.
-
Federate when one namespace isn't enough. Use router-based federation to present one namespace over several NameNodes, partitioned by team or workload.
-
Monitor:
- NameNode RPC queue time and processing time, GC pauses, heap usage;
- missing, corrupt and under-replicated blocks;
- DataNode disk failures and volume failures;
- capacity per DataNode, balancer progress;
- JournalNode sync latency.
Alert on missing blocks > 0 and on a growing under-replication backlog (Observability: Logs, Metrics and Traces).
-
Practise failure: kill the active NameNode, pull disks, power off a rack, and verify automatic recovery. Test snapshots and DistCp backups to a second cluster or object storage for disaster recovery.
A minimal HA plus erasure-coding configuration sketch:
<!-- hdfs-site.xml (excerpt): HA NameNodes with QJM and ZKFC -->
<property><name>dfs.nameservices</name><value>prod</value></property>
<property><name>dfs.ha.namenodes.prod</name><value>nn1,nn2,nn3</value></property>
<property><name>dfs.namenode.rpc-address.prod.nn1</name><value>nn1.dc1:8020</value></property>
<property><name>dfs.namenode.shared.edits.dir</name>
<value>qjournal://jn1:8485;jn2:8485;jn3:8485/prod</value></property>
<property><name>dfs.ha.automatic-failover.enabled</name><value>true</value></property>
<property><name>ha.zookeeper.quorum</name><value>zk1:2181,zk2:2181,zk3:2181</value></property>
<property><name>dfs.ha.fencing.methods</name><value>sshfence</value></property>
<property><name>dfs.blocksize</name><value>268435456</value></property> <!-- 256 MB -->
<property><name>dfs.replication</name><value>3</value></property># Cold data: switch an archive directory to Reed-Solomon 6+3 (1.5x instead of 3x)
hdfs ec -enablePolicy -policy RS-6-3-1024k
hdfs ec -setPolicy -path /warehouse/archive -policy RS-6-3-1024k
# Existing files keep their layout; rewrite them to convert
hadoop distcp -skipcrccheck /warehouse/archive_old /warehouse/archive
# Tiering: keep the newest data on SSD, older on dense disks
hdfs storagepolicies -setStoragePolicy -path /warehouse/hot -policy ONE_SSD
hdfs mover -p /warehouse/hot
# Health checks
hdfs fsck / -list-corruptfileblocks
hdfs dfsadmin -report | head -20| Technology | Fits when |
|---|---|
| HDFS | On-prem Hadoop or Spark estates; data-local batch processing; append-only analytic files |
| Apache Ozone | HDFS-compatible, but billions of objects; S3 API on-prem |
| Ceph (RADOS, RBD, RGW, CephFS) | Private cloud needing block, object and file from one self-healing cluster; OpenStack and Kubernetes |
| Lustre, or FSx for Lustre | HPC and AI training needing huge parallel POSIX bandwidth to shared files |
| IBM Storage Scale (GPFS) | Enterprise POSIX at scale with mature tooling |
| JuiceFS | POSIX semantics on top of cheap object storage; ML datasets, shared workspaces |
| Alluxio | Caching remote object storage near compute for repeated reads |
| Amazon EFS, Google Filestore, Azure Files | Managed shared NFS or SMB for applications needing a shared mount |
| Amazon S3, GCS, Azure Blob, MinIO | New data lakes, blobs, backups, media: the default unless you need file semantics |
Trade-offs#
| Option | Pros | Cons | Pick when |
|---|---|---|---|
| Single metadata master (GFS, HDFS) | Simple; globally consistent namespace; smart placement decisions | Memory and throughput ceiling; failover complexity; small-files limits | Up to hundreds of millions of files; big-file batch workloads |
| Distributed metadata (Colossus, Tectonic, HopsFS, Ozone) | Scales file counts to billions or more; no single bottleneck | Much more complex; cross-partition renames need transactions | Exabyte, multitenant, many-small-files storage |
| Computed placement (Ceph CRUSH) | No lookup service for data placement; scales clients freely | Rebalancing on topology change; CRUSH tuning is subtle | Self-managed clusters with heterogeneous hardware |
| 3× replication | Fast reads and repairs; data locality; simple | 3× storage cost | Hot data, small clusters, latency-sensitive reads |
| Erasure coding RS(6,3) | 1.5× storage; tolerates 3 failures | Costly repairs; no locality; CPU for encoding; degraded reads | Cold and warm data at scale |
| Relaxed consistency (GFS record append) | Lock-free concurrent appends at full speed | Duplicates and padding; apps must checksum and dedupe | Many producers appending to shared logs |
| Single writer per file (HDFS) | Simple, predictable semantics | No concurrent writers; append is limited | Batch outputs, write-once files |
| DFS on-prem vs object storage in the cloud | DFS: locality, rename, append, low latency | DFS: you operate it; fixed capacity | DFS when on-prem or POSIX is needed; otherwise object storage |
Common Pitfalls#
- Small files. Streaming jobs writing a file every few seconds per partition can create millions of files a day. Enforce compaction and quotas.
- Assuming HDFS is POSIX. There are no random writes, a single writer per file, and
hflushvisibility semantics. Applications thatseekand overwrite will fail. - Under-provisioned NameNode heap, and GC pauses that trigger false failovers. Tune GC, size the heap, and monitor RPC queue latency.
- No fencing. An HA setup without a working fencing method risks split brain. QJM epochs protect the log, but test fencing anyway.
- Ignoring rack topology. Without a topology script, all three replicas may land in one rack, and a switch failure loses data.
- Erasure coding hot data. Every read becomes remote and degraded reads are slow. Use EC for cold data.
- Forgetting repair bandwidth. A dense-node failure (12 × 16 TB = 192 TB) takes many hours to re-replicate, and is longer with EC. During that window durability is reduced. Size the network and cap per-node density.
- Rename-based commits on object storage. Running Hadoop-era jobs against S3 with the old committer is slow and non-atomic. Use S3A committers or table formats.
- Deleting without trash. HDFS has a trash (
fs.trash.interval), and snapshots protect againstrm -raccidents. Enable both for important directories. - Treating checksums as optional. Silent corruption happens at scale. Keep end-to-end checksums and background scrubbing on.
Real-World Examples#
- Google GFS (2003) → Colossus. GFS stored the web crawl and MapReduce data. Colossus, with metadata in Bigtable, now underlies Google storage services such as Cloud Storage, Bigtable, Spanner and BigQuery.
- Yahoo and HDFS. Yahoo ran some of the largest early Hadoop clusters and reported managing 25 PB on HDFS (Shvachko et al., 2010).
- Facebook. It ran huge HDFS warehouse clusters (it was also behind HDFS-RAID erasure coding), Haystack for hot photos (OSDI 2010) and f4 for warm blobs (OSDI 2014). It later consolidated all of these into Tectonic (FAST 2021).
- Microsoft Azure Storage uses LRC erasure coding in its storage stream layer (Huang et al., 2012). Its earlier architecture paper ("Windows Azure Storage", Calder et al., SOSP 2011) describes an append-only stream layer with extents, similar in spirit to GFS.
- Ceph began as Sage Weil's PhD work at UC Santa Cruz (OSDI 2006). It's now widely deployed in OpenStack private clouds and with Kubernetes (Rook), and CERN is a well-known large user.
- Lustre runs on many of the world's top supercomputers. Amazon FSx for Lustre offers it as a managed service, often for ML training.
- DeepSeek open-sourced 3FS in 2025 for AI training and inference data access, built on FoundationDB and CRAQ.
- Dropbox stores file blocks in content-addressed form and built its own exabyte-scale storage system, Magic Pocket (2016), moving off S3 for most data.
Case studies that use this pattern#
- Design an Object Store (Amazon S3): metadata versus data separation, erasure coding and placement, the same building blocks applied to objects.
- Design File Storage and Sync (Dropbox / Google Drive): chunked files, content hashing, blob storage with presigned URLs, metadata DB.
- Design a Video Streaming Platform (YouTube / Netflix): massive blob storage, tiering by popularity, CDN offload.
- Design a Photo Sharing App (Instagram): many small objects; why Haystack-style packing or object stores beat per-file storage.
In the Interview#
Common follow-ups:
- "Why such large chunks?" Fewer metadata entries (master RAM), fewer client–master round trips, and long sequential I/O with persistent connections. The cost is hot spots on small popular files, and internal fragmentation mitigated by lazy allocation.
- "What if the master fails?" The operation log is replicated synchronously before acking, and checkpoints bound replay time. A standby (HDFS HA) or a restarted master takes over. Shadow masters serve stale reads meanwhile. Chunk locations are rebuilt from chunkserver reports.
- "How do you prevent two primaries?" Leases with timeouts: the master waits for the old lease to expire before granting a new one. Version numbers fence stale replicas. In HDFS HA, epochs on the JournalNodes fence the old active.
- "How would you store a billion 10 KB images?" Not as files in HDFS: that's 2 billion NameNode objects. Pack them into large append-only volumes with an index (Haystack), or use object storage.
- "How do you cut storage cost by half?" Erasure-code cold data (RS(6,3) is 1.5× instead of 3×), tier by age with storage policies, and compress with columnar formats.
Deep Dive: Scaling file system metadata beyond one machineShow
The single master is GFS's most elegant simplification and its eventual limit. Every successor answers the same question: how do you partition a hierarchical namespace without losing the semantics that make it a file system?
What makes namespace metadata hard to partition:
- Path resolution walks the tree. Opening
/a/b/c/filemeans checking existence and permissions for/,/a,/a/band/a/b/c. If these live on different partitions, one open costs several round trips. - Rename moves subtrees.
mv /a/b /x/ymust be atomic, and must check that/x/yis not inside/a/b, which would create a cycle. Across partitions this needs a distributed transaction (Distributed Transactions: 2PC, Sagas and Outbox). - Directory listing wants locality.
ls /a/bshould read the children from one place, not scatter across every partition. - Hot spots. A directory receiving 50,000 creates per second (a job's output directory) or a hot root, such as
/user, concentrates load.
Partitioning strategies:
| Strategy | How | Pros | Cons | Used by |
|---|---|---|---|---|
| Static subtree partitioning | Admins assign subtrees to servers, like mount points | Simple; local path resolution in a subtree | Manual; imbalance; no cross-subtree rename | HDFS federation, ViewFs and RBF; NFS automounts |
| Dynamic subtree partitioning | Servers migrate hot subtrees between themselves based on load | Adapts to load; keeps locality | Complex migration; consistency during handoff | CephFS MDS cluster |
| Hash by full path | hash of path picks the server | Uniform spread | Rename of a directory rehashes every descendant; listing scatters | Rarely used alone |
| Hash by parent directory id | All entries of a directory live together: key = parent id plus name | Listing is local; spreads directories | Path resolution still hops per component; huge directories are hot | Tectonic name layer (keyed by directory id); Colossus-style table schemas |
| Store metadata in a scalable database | Inodes and entries are rows in Bigtable, NDB, FoundationDB or a Raft KV | Reuses a proven sharded, transactional store | Latency of DB transactions; schema design matters | Colossus (Bigtable), HopsFS (MySQL NDB Cluster), 3FS (FoundationDB), JuiceFS (TiKV or Redis), Ozone (RocksDB plus Raft) |
HopsFS ("HopsFS: Scaling Hierarchical File System Metadata Using NewSQL Databases", Niazi et al., USENIX FAST 2017) is a clear case study. It replaced the HDFS NameNode's heap with MySQL NDB Cluster tables, with stateless NameNodes running transactions against them. It partitions inode rows by parent id, so listing a directory is one partition scan, and it caches path resolution results to avoid a round trip per component. The paper reports substantially higher metadata throughput and capacity than a single HDFS NameNode, showing the "metadata in a distributed database" approach works.
The cost of each metadata RPC. With metadata in a remote database, a create might take 2–5 ms instead of tens of microseconds in an in-memory NameNode. Systems recover throughput through parallelism (many stateless metadata servers) and batching, not single-operation speed. A Spark job creating 100,000 output files at 3 ms each, with 200 concurrent tasks, finishes its creates in 100,000 × 3 / 200 = 1.5 seconds. That's fine.
Leases, clocks and correctness. GFS's primary leases, HDFS's writer leases and Chubby or ZooKeeper sessions all rely on timeouts. A paused process (a GC pause or VM stall) may still believe it holds a lease after it expired. Two defences recur:
- Wait out the lease plus a clock-drift margin before granting a new holder (GFS's master does this).
- Fencing tokens or epochs that storage nodes check, so a stale holder's writes are rejected no matter what it believes: QJM epochs, generation stamps, chunk version numbers.
The general rule: timeouts give liveness; monotonic fencing numbers give safety (Distributed Locks).
Data servers barely change. The striking pattern across GFS → Colossus, HDFS → Ozone, and Haystack/f4/HDFS → Tectonic is that chunk storage stays simple: dumb servers storing replicated or erasure-coded chunks, plus background repair. Almost all the innovation is in metadata: where it lives, how it's partitioned, and how it's kept consistent.
Deep Dive: Erasure coding internals, repair cost and durability mathShow
Reed-Solomon in one paragraph. Treat the k data units as coefficients of a polynomial of degree k−1 over a finite field, usually GF(2^8), so each byte is a field element. Evaluate the polynomial at k+m distinct points. Any k evaluations determine the polynomial uniquely (Lagrange interpolation), so any k of the k+m units recover the data.
Production implementations use a systematic form, where the first k units are the original data and only m parity units are computed. Concretely, it's a matrix multiply: parity = G × data, with G an m × k Cauchy or Vandermonde-derived matrix. Decoding inverts the k × k submatrix for the surviving units. Codes like this, where any k of n units suffice, are MDS (maximum distance separable). They're optimal in storage for their fault tolerance.
Worked example with XOR, the simplest code with m = 1. Data units D1 = 0b1010 and D2 = 0b0110, so parity P = D1 XOR D2 = 0b1100. If D2 is lost, D2 = D1 XOR P = 0b1010 XOR 0b1100 = 0b0110. Reed-Solomon generalises this to m > 1 using field multiplication, so that any m losses are recoverable.
Encoding cost. Each parity byte needs k multiply-adds in GF(2^8), which are table lookups or SIMD shuffles. ISA-L encodes RS(6,3) at several GB per second per core, so encoding is rarely the bottleneck on modern CPUs. Decoding with failures is similar, plus a small matrix inversion per stripe pattern, which is cached.
The repair problem. For MDS codes, repairing one lost unit classically requires downloading k whole units, which is k times the data being repaired. In a cluster where single-disk failures are the overwhelmingly common event, that dominates network traffic:
-
Regenerating codes ("Network Coding for Distributed Storage Systems", Dimakis et al., IEEE Transactions on Information Theory, 2010) proved that repair bandwidth can be cut far below k units, by having each helper send a function of its data rather than the whole unit. They established a fundamental trade-off curve between storage per node and repair bandwidth.
-
Locally repairable codes take a practical route: add local parities over small groups, so that most repairs read only the group. They give up the MDS property for slightly more overhead.
Code Overhead Repair reads for 1 failure Tolerance RS(12,4) 1.33× 12 Any 4 Azure LRC(12,2,2) 1.33× 6 Any 3, and many 4-failure patterns
Mean time to data loss (MTTDL), the classic Markov model. For 3× replication with N disks, per-disk failure rate λ (per hour) and repair time R (hours), the approximate MTTDL for one specific replica group is:
MTTDL_3x ~ 1 / (3 lambda * 2 lambda R * lambda R) = 1 / (6 lambda^3 R^2)Reading this right to left: a first failure arrives at rate 3λ, the second must strike during repair (probability about 2λR), and the third likewise (about λR).
Plug in an AFR of 2% (λ ≈ 2.3 × 10^-6 per hour) and R = 6 hours:
- λ³ ≈ 1.2 × 10^-17, so 6λ³R² ≈ 2.6 × 10^-15 per hour.
- That gives an MTTDL of about 3.8 × 10^14 hours per group.
- With 10 million chunk groups in a cluster, the cluster-wide MTTDL is about 3.8 × 10^7 hours: about 4,000 years. That's before accounting for correlated failures, which in practice dominate.
Two lessons follow:
- Repair time R appears squared (for 3×) or cubed (for RS with m = 3). Halving repair time through parallel re-replication improves durability 4× to 8×. That's why HDFS and GFS re-replicate from many sources to many targets in parallel: a failed 12 TB disk's blocks are spread over hundreds of nodes, so recovery takes minutes to an hour rather than the 12+ hours of copying one disk to one disk.
- Correlated failures break the independence assumption. Rack power loss, a firmware bug hitting every disk of one model, or a bad software push all take out many units at once. Placement across failure domains (racks, power domains, datacenters) and staged rollouts matter as much as the code.
Parallel repair worked example. A DataNode with 12 × 16 TB disks at 70% full fails, losing about 134 TB of replicas.
- With blocks spread uniformly over 500 other DataNodes, each source sends about 270 GB and each target receives about 270 GB.
- At a throttled 100 MB/s of re-replication bandwidth per node, that takes about 45 minutes.
- Under RS(6,3), each rebuilt block needs 6 reads, so about 800 TB of reads cluster-wide. At the same per-node throttle that's roughly 4–5 hours. The durability window is several times longer, which is one reason EC is reserved for colder data or paired with LRC.
Deep Dive: Designing a GFS-like file system in an interview, with numbersShow
Requirements.
- Functional: create, delete, open, read (offset, length), write and append; directory listing; snapshots.
- Non-functional: store 50 PB of mostly large files (1 GB+); 10,000 concurrent clients; aggregate read throughput of 1 TB/s; survive a disk, node or rack failure without data loss; metadata operations at 50,000/s; prioritise throughput over latency.
Estimation (Back-of-the-Envelope Estimation):
- Raw capacity: 50 PB × 3 replicas = 150 PB. With 20 TB disks at 80% fill that's about 9,400 disks, or about 800 servers with 12 disks each.
- Chunks: at 64 MB, 50 PB / 64 MB ≈ 780 million chunks. At about 64 bytes each, master metadata is about 50 GB of RAM for chunks, plus file metadata. That's feasible on one large server, but uncomfortable. Use 128–256 MB chunks, or design for metadata sharding from day one.
- Throughput: 1 TB/s over 800 servers is 1.25 GB/s per server. Twelve HDDs at about 150 MB/s give about 1.8 GB/s, so this works with sequential I/O, and network interfaces must be at least 25 Gbps.
- Failures: at 2% AFR, 9,400 disks means about 190 disk failures per year, or one every two days. Plus server failures. Automatic re-replication is mandatory, and humans only replace hardware in batches.
- Master load: clients cache chunk locations and use large chunks, so each 1 GB read needs a few master requests. The 50,000 metadata operations per second are within a well-built in-memory master. Shard if the business expects 10× growth.
High-level design:
- A master (Raft-replicated group of 3, or active/standby with a quorum journal) holds the namespace, the file → chunk map and chunk → replica locations. It serves metadata RPCs, grants leases and runs background repair.
- Chunkservers store chunks on local disks with per-block checksums, send heartbeats and chunk reports, and serve data directly.
- A client library caches metadata, streams data in pipelines, retries, and validates checksums.
Key mechanisms to describe:
- reads through location caching and nearest replica;
- writes through leases, a primary assigning order, and a chained data push;
- record append for concurrent producers;
- rack-aware placement;
- chunk version numbers for stale replicas;
- lazy GC;
- copy-on-write snapshots.
Deep-dive topics an interviewer will push on:
- Master as bottleneck: large chunks, client caching and batched location responses. For growth: federation (static subtrees), or metadata in a sharded database (Colossus and Tectonic style).
- Consistency: strongly consistent metadata, and relaxed data semantics for concurrent writes, with at-least-once record append. If the interviewer wants stronger data semantics, propose single-writer files (HDFS) or chain replication with a tail ack (CRAQ-style reads).
- Hot files: a higher replication factor for popular small files, and client-side caching.
- Cost: erasure coding for files older than N days, with a background job converting them (and tiering to dense disks).
- Multi-datacenter: run independent clusters per region with async replication of selected datasets, as Colossus and HDFS deployments do. The alternative is geo-erasure coding (f4-style XOR across datacenters), which trades cross-region repair bandwidth for storage.
What distinguishes a staff-level answer:
- quantifying the failure rate and showing that repair parallelism bounds the vulnerability window;
- separating control plane from data plane explicitly;
- noting that metadata, not bytes, is the scaling frontier;
- explaining when you'd instead build on object storage and spend engineering effort on table formats and caching rather than a new file system.
Key Takeaways#
- A distributed file system separates metadata from data. A metadata service (GFS master, HDFS NameNode) holds the namespace and chunk locations in memory, and data servers stream bytes directly to clients.
- GFS was designed for huge files, appends, streaming reads and constant hardware failure. It uses 64 MB chunks, 3× replication across racks, an operation log plus checkpoints, and HeartBeat-driven repair.
- Leases let one primary replica order all mutations to a chunk. Pipelined, chained data push separates data flow from control. Record append offers lock-free, at-least-once atomic appends, so apps dedupe with ids and checksums.
- HDFS mirrors GFS with NameNode, DataNodes and 128 MB blocks, a rack-aware placement policy (local, remote rack, same remote rack), a packet-acknowledged write pipeline with generation stamps, and single-writer leases.
- NameNode HA uses QJM JournalNodes with epoch fencing, plus ZooKeeper-based ZKFC failover. Observer NameNodes scale reads. Federation and router-based federation split the namespace across NameNodes.
- Small files exhaust NameNode memory (about 150 bytes per object) and kill job efficiency. Compact, pack, use big columnar files, or use stores built for small objects.
- Erasure coding (HDFS 3, RS(6,3)) cuts storage from 3× to 1.5× and tolerates 3 failures, at the cost of expensive repairs, no locality and degraded reads. Use it for cold data, and LRC codes to reduce repair cost.
- Successors distribute metadata: Colossus (Bigtable), Tectonic (ZippyDB), HopsFS and Ozone. Ceph computes placement with CRUSH and has no central lookup.
- Block vs file vs object: block storage for one host's disk, a DFS for shared file semantics and HPC, object storage as the default for data lakes, blobs and backups, with table formats supplying atomic commits.