Durability & the Write-Ahead Log
What "the write succeeded" actually promises — fsync, group commit, torn writes, and the several layers of hardware that will cheerfully lie to you about all of it.
#The question nobody asks precisely enough
Your database returns OK on a write. What just happened?
The honest range of possibilities:
"OK" might mean any of these:
1. It's in the database's own memory ← survives nothing
2. Handed to the operating system, still in RAM ← survives the process dying
3. Forced all the way onto the drive (fsync) ← survives power loss
4. On the drive AND copied to another machine ← survives losing this machine
5. On the drive on a majority, in 3 buildings ← survives losing a datacenterThe distinction at step 3 is the one people miss: writing data doesn't put it on the disk. It hands it to the operating system, which keeps it in memory and writes it out when convenient. Only an explicit fsync forces it down to the physical drive — and that's the expensive call everything below is about.
Every one of these five is called "durable" by someone. They differ by roughly six orders of magnitude in both safety and cost. Knowing which one your system provides is the entire content of the durability question, and most incidents in this area come from a team believing they had level 4 and actually having level 2.
#Why a log, rather than just writing the data
The naive approach — update the B-tree page in place and be done — fails on the crash case. A single logical update often touches multiple pages: the leaf, maybe a parent after a split, maybe the free-space map (the database's record of which pages have room). Those are separate disk writes. A crash halfway through can leave, say, a parent pointing at a leaf that was never written — the tree is structurally corrupt, and nothing on disk tells you which of the writes landed.
The write-ahead log — WAL — solves this with one rule. Before touching the real data, write down what you're about to do, in a file you only ever append to:
**Write the intent to a sequential log, and fsync it, before modifying the actual data pages.**
This buys three things at once:
- Crash recovery. On restart, replay the log from the last checkpoint. Any change that was acknowledged is in the log; any change in the log but not in the pages gets reapplied.
- Sequential writes instead of random ones. The log is append-only. As the hardware numbers show, sequential writes are dramatically faster than scattered page updates — so the WAL makes commits faster, not slower, despite being extra work.
- A replication stream for free. The log is already an ordered record of every change. Ship it to a follower that replays it and you have physical replication — a byte-for-byte copy of the database on another machine. Decode it into "row X changed from A to B" events and you have CDC.
#fsync, and everything that lies about it
write() does not put data on a disk. It copies bytes into the OS page cache and returns. The kernel flushes them later, whenever it feels like it — typically within 30 seconds. A power loss in that window loses the data, and your application was told the write succeeded.
fsync() is the call that says actually put it on stable media and don't return until you have. It is the single most expensive operation in a database.
Group commit is the standard escape, and the idea is a lift that waits a moment before departing. Rather than forcing a separate disk flush for every transaction, gather everything that commits within a tiny window, write it as one batch, and flush once for the whole group. Each transaction waits marginally longer; the system does a fraction of the expensive operations.
WITHOUT group commit WITH group commit
T1 → fsync (200 µs) T1 ┐
T2 → fsync (200 µs) T2 ├→ one batched write
T3 → fsync (200 µs) T3 ┘ → one fsync (250 µs)
... → ack all three
1,000 txns = 200 ms 1,000 txns in ~20 fsyncs = ~5 ms
Cost: each transaction waits up to one window (~1 ms) longer.
Benefit: throughput scales with batch size, not fsync latency.This is a throughput-for-latency trade, and it's the same shape as batching everywhere else in systems — right down to continuous batching on GPUs in the AI Infrastructure track. Under load, more transactions arrive during each window, so each batch is bigger and each fsync is shared by more commits — the system gets more efficient exactly when it needs to.
#Torn writes and why checksums are mandatory
Filesystems and drives guarantee atomicity for a sector (512 B or 4 KB). Databases use pages of 8–16 KB. A crash mid-write can therefore leave a page with the first 4 KB new and the rest old — a torn page. The page is not corrupt in any way the hardware can detect; it's simply a mixture of two versions.
Three standard defences:
| Approach | Mechanism | Used by |
|---|---|---|
| Full-page writes | After each checkpoint, the first modification to a page writes the whole page to the WAL, so recovery can restore it wholesale | PostgreSQL |
| Doublewrite buffer | Write the page to a scratch area and fsync, then write it in place; recovery prefers the intact copy | MySQL/InnoDB |
| Copy-on-write | Never overwrite a page; write a new one and atomically swap a pointer | ZFS, LMDB, SQLite WAL mode |
All three cost write amplification. Copy-on-write avoids the torn-write problem entirely by construction, which is why it keeps reappearing in modern designs. The price: every update leaves the old copy of the page behind, so data gets scattered across the disk (fragmentation) and something has to find and reclaim the old copies later (garbage collection).
Independently: checksum every page. Storage silently corrupts data — bit rot, misdirected writes where the drive writes correct data to the wrong location, firmware bugs. Without checksums, corruption is discovered when a query returns nonsense, and by then it has been faithfully replicated to every follower and every backup. With checksums, it's caught on read and can be repaired from a replica.
#Checkpoints: keeping recovery bounded
If the log grew forever, recovery would mean replaying everything since the database was created. A checkpoint bounds this: flush all dirty pages to disk, record "everything before log position X is safely applied", and discard (or archive) the log before X.
Recovery time ≈ time to replay the log since the last checkpoint
Frequent checkpoints: fast recovery, but constant background
write I/O, and latency spikes when a
checkpoint storms the disk
Rare checkpoints: minimal steady-state I/O, but recovery
can take many minutes
→ the tuning knob is literally an RTO decisionThis is a direct, quantifiable trade between steady-state performance and recovery time objective (RTO — how long you're allowed to be down after a failure). If your RTO is two minutes, checkpoints must be frequent enough that replaying the log never takes longer than that. It's one of the few places where an availability target maps onto a single config value. Most databases spread checkpoint writes over the interval to avoid the I/O storm.
#Durability across machines
Local fsync protects against power loss. It does nothing about the machine being destroyed, so real durability is replication — and the setting that matters is whether commit waits for a follower.
| Mode | Commit waits for | Loses on primary failure | Cost |
|---|---|---|---|
| Async replication | Local fsync only | Everything not yet shipped | Fastest |
| Semi-sync | One follower's receipt | Data received but not fsynced | +1 network RTT |
| Sync replication | One follower's fsync | Nothing acknowledged | +1 RTT +1 fsync |
| Quorum (majority) | Majority fsync | Nothing acknowledged | +1 RTT, tolerates a slow node |
Quorum is usually the right answer, at the cost of a round trip to another availability zone (AZ — a separate datacenter in the same region). With three copies, a commit needs any two to confirm. If one follower is slow, the other two still form a majority, so commits don't wait for the laggard — unlike sync replication, which is stuck if its one chosen follower is slow. See quorums and replication.
#Exercise
Reasoning to check against: (1) Up to wal_writer_delay (default 200 ms) of committed transactions — the user was told they succeeded, and they're gone. (2) Any messages the leader hadn't yet copied to followers; acks=all with min.insync.replicas=2 is the fix. (3) The Kafka publish succeeds, then power loss wipes the un-fsynced Postgres commit. The consumer reads the event and acts on an order (ships it, emails a receipt) that has no row in the database — a dangling side effect. (4) synchronous_commit = on plus quorum replication, and publish via the outbox pattern inside the same transaction instead of a separate call. Cost: roughly one cross-AZ round trip on the commit path.
#Check yourself
Name the five things "the write succeeded" can mean.Show answer
What is the write-ahead log rule?Show answer
Three things a WAL buys besides crash recovery?Show answer
What is group commit, and what does it trade?Show answer
Name two ways the storage stack has lied about fsync.Show answer
What is a torn page, and the three defences?Show answer
Why is checkpoint frequency an RTO decision?Show answer
Which replication mode loses nothing acknowledged without stalling on one slow node?Show answer
#What to carry forward
- "Durable" has at least five meanings. Know which one you have; assume the weakest until proven otherwise.
- Log first, fsync, then ack. The log is the database; pages are a materialised view.
- fsync is a hardware constant — group commit is how you get throughput without it.
- Torn writes are real; full-page writes, doublewrite, or copy-on-write are the three defences. Checksum everything regardless.
- Checkpoint frequency is an RTO decision expressed as a config value.
- Local fsync survives power loss; only replication survives losing the machine.