File Systems & Durable Storage
- Explain inodes, directories, links and journaling well enough to debug "disk full" and crash-consistency problems
- Trace a
write()from your Go code to stable media and say exactly when data survives a crash - Justify why databases
fsyncthe WAL, and choose durability settings for a ledger vs a clickstream - Compare SSD and HDD behaviour, RAID levels, and IOPS vs throughput vs latency when sizing storage
- Choose block, file or object storage for a given banking or e-commerce workload
TL;DR
- A file is an inode (metadata + block map); a directory is a table of name → inode number. Names are not part of the file, which is why hard links and "deleted but still open" files exist.
write()returns once data is in the page cache, not on disk. Background write-back flushes dirty pages seconds later. A power loss or kernel crash before that loses the data.fsync(fd)is the durability point: it flushes the file's data and metadata and asks the device to flush its volatile cache.fdatasyncskips non-essential metadata. A newly created or renamed file also needs anfsyncof its parent directory.- Databases fsync the write-ahead log on commit so an acknowledged transaction survives a crash; group commit amortises one fsync over many transactions. Turning it off trades durability for latency.
O_DIRECTbypasses the page cache but does not by itself guarantee durability.- Storage is described by IOPS, throughput and latency — throughput = IOPS × I/O size; required concurrency = IOPS × latency (Little's law). SSDs give ~100× the random IOPS of HDDs.
- Block storage (EBS, SAN) for databases, file storage (NFS, EFS) for shared POSIX access, object storage (S3) for immutable blobs at scale.
Why it matters
A bank's ledger service acknowledges a transfer, the node loses power, and on restart the transfer is gone — but the customer already saw "success" and the SMS was sent. Whether that can happen is decided by a handful of OS-level settings: whether the database fsyncs its WAL on commit, whether the volume's write cache is power-loss protected, whether commits are replicated synchronously. Regulators and auditors care about this as an RPO question; architects are expected to answer it precisely.
E-commerce has the opposite pressure: during a flash sale, an order service on a cloud volume capped at 3,000 IOPS suddenly sees 10 ms write latency because every order commit is an fsync. Knowing how fsync, group commit, IOPS limits and queue depth interact lets you size storage and choose synchronous_commit settings per table type instead of guessing.
Core concepts
Inodes, directories and links
- The inode holds type, permissions, owner, size, timestamps (
atime,mtime,ctime), link count and the block map (ext4 and XFS use extents: start block + length). It does not hold the name. - Hard link: another directory entry pointing to the same inode (same filesystem only). The file's data is freed when the link count is 0 and no process has it open.
- Symbolic link: a separate inode containing a path; can cross filesystems and can dangle.
- Deleted but open:
rmof a 40 GiB log that a process still writes to frees nothing.dfsays full,dusays empty. Find it withlsof +L1; fix by restarting the process or truncating via/proc/PID/fd/N. - Inode exhaustion: millions of tiny files (session files, image thumbnails) can exhaust inodes while bytes remain. Check
df -i. - Rename is atomic within one filesystem: readers see either the old or the new file. This is the basis of safe config and snapshot updates.
VFS and file systems
The kernel's VFS layer gives one API (open, read, write, fsync) over many filesystems:
| Filesystem | Notes |
|---|---|
| ext4 | Default on many distros; journaling; extents; mature and predictable |
| XFS | Strong with large files and parallel I/O; common for databases and Kafka |
| btrfs, ZFS | Copy-on-write, checksums, snapshots, compression; different performance profile for random overwrites |
| overlayfs | Union filesystem used for container images (see Linux Containers) |
| NFS, EFS | Network file systems: POSIX-ish semantics over the network, different caching and locking behaviour |
Mount options matter: relatime (default) avoids an atime write on most reads; noatime removes it entirely.
Journaling and crash consistency
Appending a block to a file updates several structures: the data block, the inode (size, extent map) and the free-space bitmap. A crash between those writes leaves the filesystem inconsistent — the classic fix was a full fsck scan, which takes hours on large disks.
Journaling writes the intended changes to a log (the journal) first, then applies them in place; after a crash the filesystem replays or discards journal transactions — a write-ahead log for metadata. ext4 modes:
| Mode | What is journaled | Trade-off |
|---|---|---|
data=ordered (default) | Metadata; data blocks are written before the metadata commit that references them | Good balance: no stale data exposed after a crash |
data=writeback | Metadata only, no ordering | Faster; a file can contain garbage after a crash |
data=journal | Data and metadata | Safest; everything written twice |
Journaling protects filesystem consistency, not your application's data. It does not make an un-fsynced write() durable. Copy-on-write filesystems (ZFS, btrfs) achieve consistency differently: they never overwrite live blocks and switch a root pointer atomically.
Page cache and write-back
Default write-back knobs (vary by distro; check sysctl vm):
vm.dirty_expire_centisecs = 3000— dirty data older than ~30 s is written back.vm.dirty_writeback_centisecs = 500— flusher threads wake every ~5 s.vm.dirty_background_ratio = 10— background write-back starts when dirty pages exceed ~10% of available memory.vm.dirty_ratio = 20— above ~20%, writers are throttled insidewrite(). A process that writes faster than the disk seeswrite()itself become slow.
On a 256 GiB database host, 20% is ~50 GiB of dirty data — a later fsync or checkpoint may then take a very long time. Large-memory hosts often lower these ratios, or set dirty_background_bytes / dirty_bytes explicitly.
fsync, fdatasync and what "durable" means
| Call / flag | Guarantees on return |
|---|---|
write() | Data in the page cache. Visible to other readers; not durable |
fsync(fd) | File data and metadata on stable storage, including a device cache flush |
fdatasync(fd) | Data plus metadata needed to read it back (e.g. file size); skips mtime updates — often one fewer write |
O_SYNC / O_DSYNC | Each write() behaves as if followed by fsync / fdatasync |
sync_file_range | Starts write-back of a range; no durability guarantee (no metadata, no cache flush) |
fsync(dirfd) | The directory entry (a new file or a rename) is durable |
Rules that bite in production:
- New files need a directory fsync. Creating
segment-0042.log, writing and fsyncing it is not enough; after a crash the name might not exist. fsync the directory too. - fsync errors are sticky problems. In 2018 PostgreSQL developers found ("fsyncgate") that after a failed fsync, Linux could mark the dirty pages clean and drop them, so retrying fsync returned success while the data was lost. PostgreSQL now treats an fsync failure as a PANIC and recovers from the WAL. Lesson for your code: a failed
Sync()means the data may be gone — do not retry and carry on. - Device caches: fsync issues a flush to the device. Enterprise SSDs with power-loss protection (capacitors) can acknowledge flushes quickly; consumer drives without it must really write to NAND. Some devices have historically acknowledged flushes they didn't honour — one reason to replicate rather than trust a single disk.
- macOS:
fsyncdoes not force the drive cache;F_FULLFSYNCdoes. Go'sFile.SyncusesF_FULLFSYNCon macOS, so fsync benchmarks on a Mac are not comparable to Linux.
The durability ladder — choose the rung your business needs:
| When your API says "success", data is… | Survives | Typical cost |
|---|---|---|
| In process memory | Nothing | ~0 |
In the page cache (write only) | Process crash | Microseconds |
| fsynced on local disk | Power loss, kernel crash | ~0.05–10 ms per fsync (device-dependent, rough) |
| Synchronously replicated to another node | Machine loss | + one network round trip |
| Synchronously replicated across zones | AZ loss | + cross-AZ round trip (~1–2 ms, rough) |
Why databases fsync the WAL
The write-ahead logging rule: before a change to a data page is written in place, the log record describing it must be durable; before a commit is acknowledged, the commit record must be durable. Data pages can then be written lazily (checkpoints), and crash recovery replays the log.
- Group commit is why databases sustain thousands of commits per second on disks that do a few hundred fsyncs per second: many transactions share one flush.
- Sequential WAL writes are cheap even on HDDs; random data-page writes are deferred and batched.
- Common durability settings:
| System | Setting | Durable on ack? |
|---|---|---|
| PostgreSQL | synchronous_commit = on (default) | Yes, local WAL flushed (plus sync standby if configured) |
| PostgreSQL | synchronous_commit = off | No — recent commits (roughly up to 3× wal_writer_delay) can be lost on crash, but no corruption |
| MySQL InnoDB | innodb_flush_log_at_trx_commit = 1 and sync_binlog = 1 | Yes |
| MySQL InnoDB | innodb_flush_log_at_trx_commit = 2 | Survives mysqld crash, not OS crash (about 1 s window) |
| Redis | appendfsync always / everysec / no | Always: yes; everysec: up to ~1 s loss |
| Kafka | Defaults rely on page cache + replication (acks=all, min.insync.replicas) | Durable against single-node loss via replicas, not per-message fsync |
| etcd | fsyncs WAL on every Raft commit | Yes; docs recommend p99 WAL fsync below 10 ms |
Never set PostgreSQL fsync = off in production: unlike synchronous_commit = off, it risks corruption, not just losing recent commits. Details in PostgreSQL Deep Dive and Storage Engines.
O_DIRECT
O_DIRECT transfers data between your buffer and the device, bypassing the page cache.
- Why: the database already has a buffer pool; caching the same page twice wastes RAM ("double buffering") and the kernel's eviction policy competes with the DB's. InnoDB (
innodb_flush_method = O_DIRECT), ScyllaDB and many storage engines use it. - Requirements: buffers, offsets and sizes aligned to the logical block size (typically 512 B or 4 KiB). Go needs aligned allocations (e.g.
github.com/ncw/directio-style helpers). - Not durability: metadata (file size, extents) and device caches still need
fsync/fdatasyncorO_DSYNC. - PostgreSQL traditionally relies on the page cache (and is adding direct I/O support in recent versions); Kafka deliberately relies on the page cache.
SSD vs HDD
| Characteristic (rough, varies by model) | HDD (7.2k rpm) | SATA SSD | NVMe SSD |
|---|---|---|---|
| Random 4 KiB read latency | ~5–10 ms (seek + rotation) | ~0.1 ms | ~0.02–0.1 ms |
| Random IOPS | ~100–200 | tens of thousands | hundreds of thousands to 1M+ |
| Sequential throughput | ~100–250 MB/s | ~500 MB/s | several GB/s |
| Parallelism | One actuator | Several channels | Many channels, up to 64K queues |
| Wear | Mechanical | Limited P/E cycles | Limited P/E cycles |
SSD internals that show up as production behaviour:
- Erase-before-write: NAND is written in pages but erased in much larger blocks. The flash translation layer (FTL) remaps writes and garbage-collects in the background → write amplification and occasional latency spikes under sustained random writes, worse when the drive is nearly full.
- TRIM/discard tells the SSD which blocks are free, improving GC; over-provisioning (spare capacity) does the same.
- Endurance is rated in drive writes per day (DWPD) or TBW; write-heavy logs and WALs wear consumer SSDs quickly.
%utiliniostatis misleading for SSDs/NVMe: 100% util only means "at least one I/O in flight", not saturation.
RAID
| Level | Min disks | Usable capacity | Survives | Write penalty (I/Os per random write) | Notes |
|---|---|---|---|---|---|
| RAID 0 | 2 | N disks | Nothing | 1 | Striping for speed only |
| RAID 1 | 2 | 1 disk | N−1 failures | 2 | Mirroring; fast reads |
| RAID 5 | 3 | N−1 | 1 failure | 4 (read data, read parity, write both) | Long rebuilds on large disks; second failure or read error during rebuild = data loss |
| RAID 6 | 4 | N−2 | 2 failures | 6 | Safer for large HDD arrays |
| RAID 10 | 4 | N/2 | 1 per mirror pair | 2 | Default choice for databases |
RAID is availability, not backup: it faithfully replicates DROP TABLE, ransomware and application bugs. Hardware controllers with battery- or flash-backed write cache can make fsync cheap — verify the cache is protected, or it is lying to you. In the cloud, the provider's volume replication replaces RAID; you still need backups and cross-region copies (see High Availability & Disaster Recovery).
IOPS, throughput and latency
- Throughput = IOPS × I/O size. 3,000 IOPS × 16 KiB = ~47 MiB/s; 3,000 IOPS × 1 MiB = ~2.9 GiB/s (a volume throughput cap would hit first).
- Little's law: outstanding I/Os = IOPS × latency. To get 20,000 IOPS from a device with 0.5 ms latency you need ~10 I/Os in flight. A single-threaded fsync loop at 1 ms latency is capped at ~1,000 IOPS no matter what the volume is rated for.
- Cloud volumes have provisioned IOPS and throughput caps (e.g. AWS gp3 starts at a baseline of 3,000 IOPS and 125 MiB/s, provisionable higher), plus instance-level EBS bandwidth limits. Network-attached volumes add ~0.5–1 ms+ latency (rough) compared with local NVMe.
- Measure with
fioandiostat -xz 1; look atr_await/w_await(latency),aqu-sz(queue depth),r/s+w/s(IOPS).
Block vs file vs object storage
| Block | File | Object | |
|---|---|---|---|
| Interface | Raw device (SCSI/NVMe); you put a filesystem on it | POSIX files over the network (NFS, SMB) | HTTP API: PUT/GET/DELETE whole objects by key |
| Examples | EBS, Persistent Disk, SAN (iSCSI, FC) | EFS, Filestore, NetApp, on-prem NAS | S3, GCS, Azure Blob, MinIO, Ceph RGW |
| Latency | Lowest (sub-ms to ~1 ms) | ~ms, metadata-heavy ops slower | Tens of ms per request (rough) |
| Sharing | One host at a time (mostly) | Many hosts concurrently | Unlimited clients |
| Mutability | In-place updates | In-place updates, locks | Immutable objects (replace whole object) |
| Scale | Per-volume limits | Moderate | Effectively unlimited, cheap per GB, tiering |
| Banking / e-commerce use | Ledger and order databases, Kafka logs | Legacy batch file exchange (settlement files, core banking drops), shared CMS assets | Statements, KYC documents, receipts, product images, backups, data lake; WORM retention with object lock |
S3 has offered strong read-after-write consistency for all operations since December 2020. Object storage design internals are covered in S3-like Object Storage.
Trade-offs
| Option | Strengths | Weaknesses | Choose when |
|---|---|---|---|
| fsync per commit (local) | Acknowledged = durable on this node | Latency bound by device flush; throughput needs group commit | Ledgers, payments, anything with RPO = 0 on a node |
| Group commit / batched fsync | Near per-commit durability with high throughput | Adds small batching delay | High-TPS OLTP; WAL-based queues |
Async commit (synchronous_commit = off, everysec) | Low latency | Loses the last ~ms–1 s of acked writes on crash | Clickstream, carts, sessions, metrics |
Replication-based durability (Kafka acks=all) | Survives node loss without per-write fsync | Correlated failures (whole-AZ power loss) can lose data | High-throughput event streams with multi-AZ replicas |
| Synchronous replication + fsync | Survives node and AZ loss | Highest latency; availability depends on replicas | Core banking, settlement, regulatory RPO = 0 |
| Page cache (buffered I/O) | Simple, kernel-managed caching | Double buffering for DBs; write-back stalls | Most applications, Kafka, PostgreSQL |
O_DIRECT + own buffer pool | Predictable memory and I/O control | Alignment, complexity, still needs fsync | Storage engines with their own cache |
In practice
Durably and atomically replacing a file (configuration, checkpoint, snapshot index):
package fsutil
import (
"os"
"path/filepath"
)
// WriteFileAtomic writes data to path so that after a crash the file holds
// either the old or the new contents, never a partial write.
func WriteFileAtomic(path string, data []byte, perm os.FileMode) error {
dir := filepath.Dir(path)
tmp, err := os.CreateTemp(dir, ".tmp-*")
if err != nil {
return err
}
tmpName := tmp.Name()
defer os.Remove(tmpName) // no-op after a successful rename
if _, err := tmp.Write(data); err != nil {
tmp.Close()
return err
}
if err := tmp.Chmod(perm); err != nil {
tmp.Close()
return err
}
if err := tmp.Sync(); err != nil { // fsync file data and metadata
tmp.Close()
return err
}
if err := tmp.Close(); err != nil {
return err
}
if err := os.Rename(tmpName, path); err != nil { // atomic within one filesystem
return err
}
d, err := os.Open(dir)
if err != nil {
return err
}
defer d.Close()
return d.Sync() // make the rename itself durable
}
Measuring what your volume can really do:
# fsync latency the way a WAL sees it (etcd's docs suggest a similar test)
fio --name=wal --directory=/var/lib/test --rw=write --ioengine=sync \
--fdatasync=1 --bs=4k --size=256m
# Random read IOPS at queue depth 32, bypassing the page cache
fio --name=randread --filename=/var/lib/test/file --rw=randread --bs=4k \
--iodepth=32 --ioengine=libaio --direct=1 --size=4g --runtime=60 --time_based
# Live view: latency (r_await, w_await), queue (aqu-sz), IOPS, util
iostat -xz 1
Approximate fsync latencies to sanity-check results: local NVMe with power-loss protection ≈ tens of microseconds; consumer NVMe without PLP ≈ hundreds of microseconds to a few ms; network block volumes ≈ 1 ms or more; HDD ≈ several ms to tens of ms.
Placement rules of thumb:
- Put the database WAL on the lowest-latency volume you have; data files can tolerate more latency.
- Keep application logs off the database volume — log bursts compete for IOPS and dirty-page budget.
- Do not put a database on a container's overlay filesystem; use a volume.
- For Kafka, prefer multiple disks (JBOD or XFS on fast volumes) and leave RAM for the page cache.
Common pitfalls
- Assuming
write()is durable. "We write the transaction to a local file then ack." Symptom: lost records after a node crash or power event; no error logged anywhere. - Forgetting the directory fsync after creating or renaming files. Symptom: after a crash a segment file is missing or the old snapshot reappears.
- Retrying after fsync fails. The second fsync may succeed while data is already lost. Treat it as fatal for that file and recover from a replica or log.
dffull butdusmall. A deleted log still held open. Symptom: disk-full alerts thatrmdoesn't fix;lsof +L1shows the culprit.- Running out of inodes. Symptom: "No space left on device" with free bytes;
df -iat 100%. - Trusting
%utilon SSD/NVMe. Symptom: "disk is 100% busy" while latency is fine; checkawaitandaqu-sz. - Huge dirty-page ratios on big-RAM hosts. Symptom: periodic multi-second stalls when write-back or a checkpoint flushes tens of GiB.
- Cloud volume caps. IOPS or throughput limits at the volume or instance level. Symptom: latency jumps sharply at a round number of IOPS; burst-credit volumes slow down hours into a sale.
- Treating RAID or replicas as backups. Symptom: a bad migration or ransomware is replicated everywhere instantly.
Interview angle
- "How do you guarantee a payment is not lost once acknowledged?" — WAL + fsync on commit (or synchronous replication), group commit for throughput, the durability ladder, and idempotent retries for the gap between commit and response.
- "Why can't we just turn off fsync for speed?" — explain what is lost (recent commits vs corruption), and offer alternatives: async commit per transaction type, faster volumes, batching.
- "Size storage for 5,000 orders/s." — convert to commits, WAL bytes and fsyncs, apply group commit, check IOPS/throughput caps and latency, plan headroom and separate WAL volume.
- "Block vs file vs object storage for KYC documents?" — object storage with encryption, versioning and object lock for retention; metadata in a database.
- Red flags: "the journal makes my writes durable"; "RAID is our backup"; not knowing that
write()returns before data reaches disk; quoting IOPS without I/O size and latency.
Self-check
1. What does a directory store, and why does deleting a file sometimes not free space?
A directory maps names to inode numbers. Deleting a file removes one name and decrements the link count; the inode and data blocks are freed only when the link count is zero and no process holds an open descriptor. A running process still writing to a deleted log keeps the space allocated until it closes the file or exits.
2. Exactly which steps make a newly created WAL segment durable?
Write the data, fsync (or fdatasync) the file so its data and size reach stable storage, then fsync the parent directory so the new directory entry is durable. If the segment was created via rename, the directory fsync must come after the rename.
3. Why do databases fsync the WAL on commit instead of the data files?
The WAL is append-only and sequential, so one flush covers the commit record (and many concurrent transactions via group commit). Data pages are scattered random writes; deferring them to checkpoints batches them. After a crash, replaying the durable WAL reconstructs any changes not yet in data files, so durability needs only the log flushed at commit.
4. Does O_DIRECT guarantee data is on stable storage when write returns? Explain.
No. It bypasses the page cache, but the data may still be in the device's volatile write cache, and metadata changes (file size, block allocation) are not necessarily persisted. You still need fsync/fdatasync or O_DSYNC to guarantee durability.
5. A volume is rated 16,000 IOPS but your single-threaded fsync loop achieves only 900 ops/s. Why?
Little's law: with one outstanding I/O, throughput = 1 / latency. At ~1.1 ms per fsync (typical for network block storage), you get ~900 ops/s. The rated IOPS needs many concurrent I/Os. Group commit, batching or more parallel writers increase achieved throughput; lower-latency storage raises the single-stream ceiling.
6. Scenario: an e-commerce company stores carts, orders and clickstream events. Choose durability settings for each.
Orders: synchronous commit with fsync and synchronous replication to another zone — acknowledged orders must not be lost. Carts: async commit (or Redis with everysec) is acceptable — losing a second of cart edits on a crash is tolerable. Clickstream: Kafka with replication (acks=all is optional depending on loss tolerance), no per-message fsync, and batching for throughput. Document the RPO for each.
7. Why is RAID 10 usually preferred over RAID 5 for databases?
RAID 5 has a write penalty of 4 I/Os per small random write (read data and parity, write both), hurting OLTP write latency, and rebuilds of large disks are long and risky. RAID 10 has a write penalty of 2, better random-write performance and faster rebuilds, at the cost of 50% capacity.
Exercise
Measure the cost of durability on your own hardware.
- Write a Go program that appends 4 KiB records to a file in a loop for 10 seconds in four modes: (a)
Writeonly, (b)Write+Syncevery record, (c)Write+unix.Fdatasyncevery record, (d) group commit: 8 goroutines submit records to a channel and one writer goroutine fsyncs once per batch (up to 64 records or 2 ms), replying to each submitter after the flush. - Report records/s and p50/p99 latency per record for each mode. Run it on your laptop and on a cloud VM with a network block volume (and local NVMe if available).
- Run the
fioWAL test above on the same volumes and compare with your Go numbers. - Crash test (in a disposable VM): run mode (a) and hard-reset the VM (not a graceful shutdown); count records on restart. Repeat with mode (b).
- Bonus: use
WriteFileAtomicto update a JSON checkpoint 1,000 times while killing the process randomly; verify the file is always valid JSON.
Done looks like: a table of mode × device with throughput and latency, the crash-test counts, and a paragraph recommending durability settings for a ledger vs a clickstream writer.
Further reading
- Operating Systems: Three Easy Pieces — Persistence part: hard disks, RAID, file system implementation, FSCK and journaling, flash-based SSDs: https://pages.cs.wisc.edu/~remzi/OSTEP/
- Pillai et al., "All File Systems Are Not Created Equal: On the Complexity of Crafting Crash-Consistent Applications" (OSDI 2014)
- Martin Kleppmann, Designing Data-Intensive Applications — Chapter 3 (storage engines) and Chapter 7 (durability)
man 2 fsync: https://man7.org/linux/man-pages/man2/fsync.2.html- PostgreSQL documentation, "Reliability and the Write-Ahead Log": https://www.postgresql.org/docs/current/wal.html
- Brendan Gregg, Systems Performance (2nd ed.) — File Systems and Disks chapters
Related
- Storage Engines: B-Tree vs LSM — how WAL, pages and compaction build on these primitives
- PostgreSQL Deep Dive — WAL, checkpoints,
synchronous_commit - Replication — durability beyond a single disk
- High Availability & Disaster Recovery — RPO/RTO and backups
- S3-like Object Storage — designing object storage
- Double-Entry Ledger Design — what must never be lost
- Memory Management — the page cache from the memory side
Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).