skip to content
dkkv0000

Storage Durability from First Principles: fsync (Part 1)

/ 20 min read

Table of Contents
Three-panel xkcd-style comic: a developer brags that write() succeeded, a friend asks if they called fsync(), unplugs the computer, and says 'Congratulations, your database is now an in-memory cache.'

Have you ever wondered what actually happens after your program calls write()? Me too — let’s dig in!

Your program calls write(), gets back “all bytes written”, and tells the user: Saved! Two seconds later, the power cord comes loose. When the machine boots back up, the data is gone — or worse, half-written and out of order.

write() is like handing a sticky note to a coworker and hoping they lock it in the fireproof safe before the building loses power. Every crash-safe storage engine solves durability first. This article explains write(), fsync(), fsync_dir() (fsync on a parent directory), and fsync failure handling from first principles.

1. Why write() is not durable

An ordinary buffered write() can block, even waiting for disk I/O. What its return value tells you is how many bytes were accepted, not whether they will survive a power cut. Follow the bytes through three places they can be buffered:

User SpaceProcess RAMwrite(fd, buf, n)Lost on SIGKILLor power cutVolatile CachesOS Page CacheDirty pages · reordered lazilyDMA flushDrive DRAM CacheTorn 512B / 4K sectors on power cutStill volatile!Non-Volatile DiskFile Inode + Datasavegame.tmp bytesParent Dir Entry"savegame.dat" -> #42fsync()fsync_dir(parent):needed after create, rename, or unlink — otherwisethe filename entry can vanish or revert on reboot even when file bytes survived.
  1. Process memory (std::vector, FILE*): Your application’s own RAM. It forgets everything the second your process trips over a crash.
  2. OS kernel page cache: write() copies bytes into kernel RAM and returns “All good!” Modified pages waiting to reach disk are called dirty pages. They survive a process crash, but power loss wipes them out — and the OS flushes them lazily, in whatever order it feels like.
  3. Drive write-back cache: A drive can acknowledge a write while the bytes are still in its cache. If that cache is volatile and has no power-loss protection, those bytes can disappear.

Without an explicit flush barrier, an application can tell you “Saved!”, lose power two seconds later, and wake up with total amnesia. Consider this innocent-looking C++ program:

Naive write in C++: success does not imply durability
#include <fstream>
int main() {
std::ofstream out("savegame.dat", std::ios::app);
out << "high_score=9999\n"; // Copies into user-space buffer / OS page cache only
out.flush(); // Flushes user-space buffer to OS, NOT to disk
out.close(); // Releases handle; does NOT force a disk flush
// Power loss here can lose "high_score=9999\n" or the entire file.
return 0;
}

Calling out.flush() and out.close() moves bytes out of your process buffer into the OS page cache, but it does not flush dirty pages to permanent media.

2. What fsync() actually does inside the kernel

The POSIX standard (the Unix/Linux OS interface specification) defines fsync() broadly: the operating system must transfer modified data to the storage device, while the transfer mechanism remains implementation-defined.

Real kernels differ in how far they push the data:

Linux (ext4)

On journaled ext4, Linux 6.12’s ext4_sync_file() takes this path for an ordinary file:

  1. file_write_and_wait_range() sends dirty file pages from the OS page cache to the block device. At this point, bytes can still sit in the drive’s volatile DRAM cache.
  2. The filesystem writes the inode metadata (size, timestamps, block pointers) and journal entries (the filesystem’s internal crash log, if journaling is enabled).
  3. If a separate device flush is needed, ext4 calls blkdev_issue_flush(). The journal commit can already supply the required barrier; one fsync() does not imply one additional device flush.

Linux also provides fdatasync(), which flushes file bytes and size metadata but skips non-essential metadata such as access timestamps to save extra disk writes.

Windows and macOS

  • Windows: FlushFileBuffers() flushes both the OS cache and the drive write-back cache.
  • macOS: Plot twist — macOS fsync(2) drops your bytes on the drive controller’s desk, waves politely, and walks away without forcing a hardware cache flush. Durable databases on macOS have to yell fcntl(fd, F_FULLFSYNC, 0) instead.

3. Why fsync(file) alone is not enough

Here is a surprising filesystem trap: you create a new file, write every byte, call fsync(fd), get 0 (success) back — and after a power cut, the entire file is gone.

Why? Because on POSIX filesystems, a file is not one object on disk — it is two separate structures:

  1. The file itself (inode + data blocks): Stores the file’s bytes, size, and permissions under a numeric ID (for example, inode #42). It does not store the filename.
  2. The parent directory: A separate table that maps filenames to inode numbers (for example, "data.log" -> inode #42).

fsync(fd) asks about the file. It does not promise that the name data.log will still point to that file after reboot. The directory update might already have reached disk, but the file sync alone does not tell you. As the Linux fsync(2) man page explains:

Calling fsync() does not necessarily ensure that the entry in the directory containing the file has also reached disk. For that an explicit fsync() on a file descriptor for the directory is also needed.

If power fails after fsync(fd) succeeds but before the parent directory is flushed, Pillai et al. (All File Systems Are Not Created Equal, OSDI ’14) showed three concrete failure modes:

Operation Already synced Not guaranteed durable Possible result after power loss
Create (open + write + fsync(file)) inode #42 and all file bytes Directory entry "data.log" -> #42 File vanishes — the bytes are orphaned on disk with no filename pointing to them
Atomic replace (fsync(tmp) + rename()) New file’s bytes and inode Change of the name index.dat to refer to the new inode Update rolls back — the old index.dat is visible again
Delete (unlink("old.log")) Old file’s bytes Removal of "old.log" from directory table Zombie file — old.log reappears after reboot

The rule is simple:

  • Appending to an existing, already-synced file: fsync(file_fd) is enough (the directory entry is already durable).
  • Creating, renaming, or deleting a file: You must also open the parent directory (open(dir, O_RDONLY | O_DIRECTORY)) and call fsync(dir_fd) so the directory table change reaches disk too.

Crash-safe file replacement pattern

Suppose savegame.dat and its name are already durable. We want readers to see a complete old or new save, and to report “saved” only when the new one can survive a power cut. This Linux example assumes a trusted, stable directory on a local filesystem that supports directory sync, and storage that honors flushes.

Replacing savegame.dat in its own directory
1. Exclusively create a fresh temporary file in the same directory.
2. Write all bytes, sync the file, then close it. Check each result.
3. Rename the temporary file over savegame.dat. Check the result.
4. Open and sync the parent directory. Check for success before reporting "saved".

Trace a power cut at every step:

  • Before rename: The old savegame.dat is untouched. A temporary file may remain. If preparation or rename fails, stop: syncing the directory cannot turn a failed rename into a successful replacement.
  • After rename, before directory sync succeeds: Readers can open the complete new save now. If the directory sync fails, report replacement visible, crash durability unknown. Live rename atomicity alone does not specify which directory state will be recovered after power loss.
  • After directory sync succeeds: Both the new bytes and their name are durable, assuming no subsequent writer replaces them.

On macOS the sample requests F_FULLFSYNC and reports failure if the filesystem does not support the request. On Windows it flushes the temporary file and requests a same-directory replacement with MoveFileExW. Microsoft’s explicit write-through flush guarantee describes a copy-and-delete move. Do not read it as a documented equivalent of the Linux directory-sync guarantee.

Download the C++20 example (durable_write.cpp). Run it in a scratch directory: it replaces savegame.dat.

Production implementations make different choices. Compare the operations they actually check:

4. Case study: how PostgreSQL got fsync() wrong for 20 years (fsyncgate)

Suppose fsync() returns an I/O error (EIO). Every normal human instinct says: “Try calling fsync() again!” On Linux buffered I/O, that instinct causes silent data loss — and for nearly 20 years, even PostgreSQL fell into this trap.

The bug was not a careless typo; it was a collision between how Linux handles failed disk write-backs and how PostgreSQL splits work across multiple OS processes:

  1. Clean does not mean durable after an error: Linux can record a write-back error and leave the page marked clean. It need not evict the page immediately. A read can still return the expected bytes from RAM, while a later sync has no dirty page to write.
  2. PostgreSQL’s multi-process split: Query backends and the background writer call write() on data files through their own file descriptors (fd_1). Minutes later, a separate checkpointer process opens its own file descriptor (fd_2), calls fsync(fd_2), and — if fsync() returns 0 — recycles the old WAL segments.
  3. Two ways a later fsync() could miss the error:
    • Pre-Linux 4.13 (test-and-clear): Linux reported EIO once and immediately cleared the error bit. When PostgreSQL caught EIO and retried the checkpoint later, the second fsync() saw clean pages and cheerfully returned 0.
    • Linux 4.13+ (errseq_t): Write-back errors are tracked for the file with a reporting cursor per open file description. A fresh descriptor can flush pages still dirty from other writers, but it does not provide a reliable history of earlier errors.
  4. When recovery became impossible: The transactions were durable in the WAL at commit time. If the checkpoint was later treated as complete, PostgreSQL could recycle the WAL records it still needed to reconstruct the missing data.
PostgreSQL ProcessesBackend / bgwriterwrite(fd_1, page)Checkpointerfd_2 = open(file)fsync(fd_2) -> 0 (!)Linux OS Page Cache1. Background write-back failsDisk returns EIO2. Page can be marked cleanA retry may not rewrite the page.A new descriptor can miss the error.Result (Before 2018)Checkpointer trusts 0Assumes page is on diskRecycles WALSilent data loss!PostgreSQL 2018 fix (data_sync_retry = off):On a reported data-file sync I/O error, stop (PANIC)before recycling WAL, so crash recovery replays every committed transaction from the last safe checkpoint.

It is like asking a coworker who dropped your folder into the shredder “Did you file that?” and hearing “My desk is spotless, boss!”

PostgreSQL’s default policy, data_sync_retry = off, is to PANIC on a data-file synchronization I/O error rather than complete the checkpoint. That preserves the WAL needed for recovery. It is a database recovery policy, not a rule to terminate every program on every fsync() error.

Other engines skip the kernel page cache drama altogether. TigerBeetle opens its storage file with O_DIRECT, leaving zero room for kernel write-back amnesia.

More real-world fsync() incidents

PostgreSQL is far from the only system burned by fsync() assumptions:

Incident / Study What Went Wrong Root Cause Fix & Exact Citation
ext4 zero-length files (2009) Desktop apps and editors woke up after crashes to 0-byte empty files where configs and saves used to be Apps wrote a temp file and called rename() without calling fsync() first; ext4’s delayed allocation flushed the rename metadata before allocating data blocks Call fsync() before rename() (and Linux 2.6.30 added ext4 workaround heuristics) — Theodore Ts’o’s postmortem (LWN)
SSDs under power fault (2013) Hardware power-fault testing of 15 commercial SSDs from 5 vendors found 13 of 15 failed durability (bit corruption, shorn writes, unserializable writes); one lost 31% (72 GB) after 8 power cuts and another bricked after 136 Consumer SSD firmware and volatile DRAM write caches did not survive abrupt power loss despite host flush commands Use PLP enterprise drives, end-to-end checksums, and replication — Zheng et al., USENIX FAST ’13 (PDF)
OSDI ’14 crash study (2014) Researchers uncovered 60 crash-consistency bugs across 11 real systems (LevelDB, SQLite, LMDB, ZooKeeper, HDFS, Git) on ext4, btrfs, and XFS Missing parent-directory fsync_dir() after file create/rename(), plus assuming writes reach disk in syscall order without flush barriers Explicitly fsync parent directories and test against crash-order models — Pillai et al., OSDI ’14 PDF
etcd missing directory fsync() (2016) Crash testing reproduced silent loss of committed WAL data on recovery (and global data loss if two of three nodes crashed) etcd renamed wal.tmp to wal without calling fsync() on the parent directory; after a crash, recovery saw wal.tmp and unlinked it fsync() the parent directory after every file create or rename() — etcd-io/etcd#6368
5 databases under fsync() errors (2020) Injected write-back failures exposed recovery problems in PostgreSQL, LMDB, LevelDB, SQLite, and Redis A cached read can succeed even when writing the same bytes to storage has failed Check sync errors and do not use a cached read as proof of durability — Rebello et al., USENIX ATC ’20 (PDF)
Kafka lazy fsync & single-node amnesia (2023) Losing unsynced page-cache writes on one broker caused silent global data loss of acknowledged records across a 3-node replicated cluster Non-Byzantine protocols (Raft, Paxos, Kafka ISR) assume fail-stop faults — a rebooted node must retain acknowledged state; without fsync(), a single power-lost node restarts with amnesia and forms a new quorum that drops committed writes Never treat replication as a substitute for fsync() on commit in non-Byzantine protocols — Redpanda proof & Kafka reproduction
CouchDB and recovery after process restart (2025) A restarted process can read unsynced bytes from the surviving OS page cache; a later power cut may erase them On Linux a new descriptor can sync still-dirty data for the same file. Success does not prove that earlier write-back succeeded Distinguish a readable database header from a durable commit. See CouchDB’s commit barriers and Linux file sync and error reporting
ClickHouse bolted-on fsync (2020–2026) Even after fsync support landed in 2020 (#10286), missing flush paths required 6 years of iterative bug fixes across 2021–2026 (#18845, #21642, #34739, #38993, #44781, #104137) ClickHouse was designed around geo-distributed replication and quorum inserts (Yandex production ran with fsync off); retrofitting fsync onto an existing engine leaves subtle durability gaps Design crash-durability barriers into the storage layer from day one rather than bolting them on later — Pranav Mehta (ClickHouse#10286)
NATS JetStream 2.12.1 (2025) Simulated power loss dropped 131,418 of 930,005 acknowledged messages (~30s of writes), and even a single OS crash triggered split-brain JetStream acknowledged publish immediately while calling fsync() only once every 2 minutes by default (sync_interval) Sync before acknowledging Raft/durable commits (or set sync_interval: always) — Jepsen NATS 2.12.1 (§3.4), nats-server#7564, #7567
SpacetimeDB WAL segment creation (2026) Newly created write-log segment files could vanish after a power cut even though the segment itself had been fsync()’d SpacetimeDB called fsync() on the new segment file but omitted fsync() on the parent directory — proving the 2014/2016 fsync_dir() trap still bites modern engines Call fsync() on the parent directory after creating a new segment (shipped in v2.9.0) — Kris Jenkins, SpacetimeDB#5785
macOS fsync(2) & APFS F_FULLFSYNC Committed writes vanish on power loss under plain fsync(2); meanwhile, a 4 KiB F_FULLFSYNC on APFS can stall 760–810 ms behind another process’s writes macOS fsync(2) stops at the drive’s volatile cache; F_FULLFSYNC drains the entire device queue (including other processes’ buffered writes), and Apple’s bundled SQLite quietly downgrades fullfsync=1 to F_BARRIERFSYNC Use F_FULLFSYNC when strict power-loss durability is required and budget for queue-drain latency — Daniel Cosenza, Kit Wickham

The abstraction lesson

Every incident above comes from the same trap: treating POSIX file I/O (write, rename, fsync) as a neat, portable black box. Underneath that thin syscall API sit five independent layers — language runtime, OS page cache, per-fd error tracking, filesystem metadata journal, and drive firmware cache — and every OS, filesystem, and SSD implements the contract slightly differently.

Durable storage engines don’t trust the abstraction blindly:

  • Know your OS flush primitive: Linux fsync() / fdatasync(), macOS F_FULLFSYNC, Windows FlushFileBuffers().
  • Sync directory changes you need to survive a crash. A file sync alone does not guarantee its name is durable.
  • Distinguish interruption from write-back failure. Retry a sync interrupted by EINTR. After EIO, do not acknowledge durability on the strength of a retry or a cached read; recover from a known-good copy or durable log.
  • Test crashes under fault injection: Treat crash recovery as a first-class test suite, not an assumption from a man page.

Open-source storage systems do not all agree on how much to trust a single disk. They fall into four durability philosophies:

1. Strict Local fsyncPostgreSQL · InnoDB · SQLite · DuckDB · LMDB/bboltClient writeWAL / CoWfsync()Local DiskAck to client2. Buffered / Async fsyncRocksDB · WiredTiger · Redis · CassandraClient writePage CacheEarly Acktimer fsyncDisk (1s–10s later)3. Replication-FirstApache Kafka (ISR) · ClickHouse (ReplicatedMergeTree)Client writeNode 1 RAMreplicateNodes 2 & 3 RAMAck (ISR OK)4. O_DIRECT + Quorum Disk fsyncTigerBeetle · FoundationDB (TLog)Client writeBypass OS CacheO_DIRECTQuorum DisksAck to client

1. Strict local fsync (single-node ACID)

Wait for local disk confirmation before acknowledging a write, using group commit so concurrent writers share one flush.

Engine Default Sync & Tunable Option Crash & Torn-Write Strategy
PostgreSQL (8 KiB pages + WAL) A synchronous commit waits for WAL through its commit record to be flushed. Multiple transactions can share that flush; an ordinary commit does not sync a directory. PANIC on data-file sync I/O error by default; full_page_writes protects against torn data pages
MySQL InnoDB (16 KiB pages + redo/binlog) fsync redo + binlog per commit (1,1) with group commit; O_DIRECT data (tunable: 0 or 2) Doublewrite buffer writes pages sequentially and calls fsync before in-place overwrites
SQLite (4 KiB pages, journal/WAL) PRAGMA synchronous = FULL + dir fsync (macOS strict: PRAGMA fullfsync = ON for F_FULLFSYNC) Rolls back uncommitted journal or discards torn trailing WAL frames
DuckDB (columnar blocks + WAL) fsync on WAL commit + periodic checkpoints (tunable: checkpoint_threshold) Dual database headers keep the prior checkpoint valid if a crash hits mid-checkpoint
LMDB / bbolt (Copy-on-Write B+Tree) Two fsync() calls: dirty CoW pages, then alternating meta page 0/1 (tunable: MDB_NOSYNC) Never overwrites live pages; reopening picks the highest valid meta page

2. Configurable fsync (buffered / periodic by default)

Return after writing to RAM or the OS page cache, and sync on a timer unless the caller explicitly requests per-write durability.

Engine Default Sync & Strict Option Crash & Torn-Write Strategy
RocksDB / LevelDB (LSM-tree: WAL + SSTables) Writes to OS page cache (sync = false) (strict: WriteOptions::sync = true + FsyncDir()) Truncates torn WAL tail or fails with corruption under strict recovery
MongoDB WiredTiger (B-Tree + journal) Buffers journal up to 128 KiB + group commit (strict: j: true waits for fdatasync) Replays journal from the last consistent checkpoint after a crash
Redis (in-memory + AOF/RDB) appendfsync everysec on a background thread (strict: appendfsync always) Loses up to ~1 second of writes under everysec; truncates torn AOF tail

3. Replication-first durability (skip hot-path fsync)

Skip per-write local fsync() by default and bet on multi-machine replication instead.

Engine Default Sync & Strict Option Crash & Torn-Write Strategy
Apache Cassandra (LSM-tree + CommitLog) commitlog_sync: periodic every 10s (strict: batch or windowed group) Replays CommitLog on restart; relies on multi-node replication factor
Apache Kafka (partitioned log) No per-message fsync(); OS page cache (tunable: flush.messages / flush.ms, discouraged) Relies on acks = all and in-sync replicas (ISR) across independent brokers
ClickHouse (MergeTree parts) fsync_after_insert = 0, fsync_part_directory = 0 (strict: opt-in = 1) Relies on ReplicatedMergeTree quorum inserts rather than single-disk fsync

4. O_DIRECT + quorum fsync (trust nobody)

Bypass or isolate kernel buffering and require a majority of disks to persist every commit before acknowledging.

Engine Durability Barrier Crash & Torn-Write Strategy
FoundationDB (distributed TLog + storage) Dedicated TLog replicas persist commit batches to disk before ack (multi-region satellites) Storage servers pull asynchronously; recovery reconstructs state from TLog quorum
TigerBeetle (replicated LSM-Forest + WAL) O_DIRECT (io_uring) + quorum WAL fsync across replicas (always strict) Treats local disks as faulty; repairs corrupt sectors transparently from peers

Notice the core engineering tradeoff across all 13 systems:

  • Single-node ACID databases (PostgreSQL, InnoDB, SQLite, DuckDB, LMDB) pay the latency of fsync() on commit and use group commit to amortize that cost across concurrent writers.
  • High-throughput distributed logs and analytics engines (Kafka, Cassandra, ClickHouse) skip per-write fsync() by default and trade single-machine durability for multi-machine replication — a tradeoff Joey Lynch argues for in Wait Before You Sync, provided an ungracefully rebooted node is wiped or replaced from replicas rather than rejoining a quorum with amnesia (otherwise, as Redpanda’s proof shows, a single power cut causes global data loss).
  • Safety-critical replicated engines (TigerBeetle, FoundationDB) combine both: they bypass or isolate kernel buffering and require a quorum of disks to persist every commit.

6. Testing power loss without unplugging hardware

Running around a server room yanking power cords is great cardio, but terrible CI. Crash-safe storage systems place a narrow filesystem interface between the engine and the operating system.

Production builds call the real OS filesystem. Tests run the same engine against a deterministic, fault-injecting filesystem that simulates:

  • Unsynced tail loss: A crash drops bytes written after the last fsync().
  • Reordered flushes: A crash keeps a later write while zeroing an earlier unsynced region.
  • Ambiguous fsync(): Bytes reach durable media, but fsync() still returns EIO.
  • Syscall-boundary crashes: A crash triggers between write(), fsync(), and fsync_dir().

Even with perfect fsync() barriers, storage hardware writes in fixed sectors and can leave partial records on power loss or flip bits over time. Part 2 — Storage Integrity from First Principles: CRC32C (coming soon) explains how checksums detect those failures.

Key terms

Term Plain explanation
Volatile vs. non-volatile memory Volatile memory (RAM, drive DRAM) loses all data when power fails. Non-volatile media (SSD flash, HDD platters) keeps data without power.
OS kernel page cache Memory managed by the operating system to speed up file reads and writes. An ordinary buffered write can return before dirty pages reach storage.
Dirty page A memory page in the OS page cache that holds modified bytes not yet written to the storage device.
Write-back cache A small volatile DRAM buffer inside an SSD or HDD that acknowledges writes early and flushes them to flash or platters later.
Inode The filesystem structure that stores a file’s data block pointers, size, and permissions — separate from its filename.
fsync() vs. fdatasync() fsync() flushes file data and all inode metadata (including timestamps). fdatasync() skips non-essential metadata like timestamps, so it is often faster for append-only logs.
REQ_PREFLUSH A Linux block-layer command flag that tells the storage drive to empty its volatile DRAM cache to permanent media.
F_FULLFSYNC A macOS fcntl() command that forces the drive to flush its hardware write cache, which plain fsync(2) on macOS does not guarantee.
EIO The standard POSIX Input/Output error code returned when a disk read, write, or flush fails.
O_DIRECT A file-open flag that bypasses the OS page cache so reads and writes go directly between process memory and the storage device.
Write-Ahead Log (WAL) An append-only file where a database records changes before applying them to main data files, enabling crash recovery.
Group commit Combining multiple concurrent transactions into a single write() and fsync() call so all writers share one disk flush latency.
Doublewrite buffer InnoDB’s safety area that writes full 16 KiB pages sequentially and calls fsync() before overwriting pages in place, preventing torn pages.
Copy-on-Write (CoW) Writing modified pages to unused disk locations instead of overwriting live pages, then switching a root pointer atomically.
LSM-tree & SSTable A Log-Structured Merge-tree writes new data to memory and a WAL, then flushes sorted, immutable files called SSTables (Sorted String Tables) to disk.
In-Sync Replicas (ISR) & Quorum A group of machines that hold up-to-date copies of a write. A quorum (majority) ensures data survives even if one or more machines lose power.

Series roadmap

  1. Part 1 — Storage Durability from First Principles: fsync (this post): Volatile buffers, Linux ext4 fsync, F_FULLFSYNC, fsync_dir, and fsyncgate.
  2. Part 2 — Storage Integrity from First Principles: CRC32C (coming soon): Torn writes, bit rot, CRC32C math, masking, and internal vs. external checksums.
  3. Part 3 — Building a Crash-Safe Bitcask Engine in C++23 (coming soon): Append-only log, KeyDir, crash recovery, 3-phase compaction, and crash-cut proofs.
  4. Part 4 — Buffering, Caching & Group Commit: Group commit, write buffering, and a sharded read cache.
  5. Part 5 — Eliminating Lock Contention: Sharded KeyDir, asymmetric reader-writer locking, and striped segment reader pools.
  6. Part 6 — CPU, Memory & Zero-Copy I/O: Flat/SIMD hash tables, hardware SSE4.2 CRC32C, and mmap zero-copy reads.

References