Why you are doing this at all
How does a database keep a committed write safe through a power cut? The usual answer is that it writes the data to disk before it says yes. It doesn't. A database stores tables and indexes in fixed-size pages, 8 KB each in Postgres. When Postgres tells you an UPDATE committed, the page holding your row has usually changed only in memory, and it can stay that way for minutes. The disk has only a record of about a hundred bytes at the end of a log, saying what changed.
That log is the write-ahead log, or WAL. The rule it's named for is short. A record of every change goes into the log, and the log is flushed before the changed page may reach the disk. Flushed means forced from memory onto the disk. If the machine dies, the database reads the log back and makes the same changes again.
The log is the copy of your data that has to be right; the tables and indexes are a copy the log can rebuild.
Most of what's hard about durability follows from that sentence. A commit costs one flush of the log, and nothing else has to reach the disk before the client hears yes. A checkpoint decides where a rebuild starts, which bounds both the restart time and the size of the log. A page that a crash leaves half-written can't be patched from a change record. A whole copy has to survive somewhere a crash can't tear, and in Postgres that place is the log. And a replica needs nothing but the log.
Why not write the pages at commit? A transfer that debits one account, credits another and adds a ledger row changes at least three pages in three places on disk. Writing them at commit means three random writes, and the client waits for all of them. A crash after the first two leaves one account debited and the other untouched, with no record of what was meant.
The log turns those three writes into one append to the end of one file. It also gives the commit a single point. The engine appends a commit record, a record that marks the transaction committed. After a crash, a transaction with a commit record in the log happened, and one without didn't.
When the log is your decision
Every database you'd pick already has a log. It becomes your decision in three places.
- What "committed" means. Most engines can acknowledge a write before the flush, and the setting decides how much a crash takes back.
- How much log you make and keep. The log's volume sets disk space, replica bandwidth and restart time, and checkpoints control it.
- A component that must not lose a write. A key-value store, a queue or a ledger in a design question needs a log, and the interviewer will ask what happens on a crash.
Some data doesn't need one at all. If losing it costs nothing anyone would notice, the flush is a cost with no return. A rate limiter's counters reset in the next window anyway, which is why the rate limiter keeps them in memory with persistence off. Choosing a database works through that decision.
How a write-ahead log works
Log first, pages later
The rule has two halves. ARIES, short for Algorithm for Recovery and Isolation Exploiting Semantics, is a recovery method that C. Mohan and colleagues at IBM published in 1992, and it states both. First, the log records that describe a change must be on disk before the changed page may replace the old copy on disk. Second, a transaction isn't committed until the log has been flushed up to its commit record.
Each half lets the engine skip a write it would otherwise wait for. The log can undo a change, so the engine may write a page that holds uncommitted changes, for example to free memory. ARIES calls that a steal policy. Without it, the paper notes, a busy page might always hold someone's uncommitted change and never be written. The log can also redo a change, so no page has to be written at commit, which ARIES calls no-force.
Every log record gets a log sequence number, or LSN. In Postgres the LSN is the record's byte position in the log, so subtracting two LSNs gives the bytes of log between them. That's how replication lag is measured. Every data page stores the LSN of the last record that changed it. The engine keeps the rule with that number: before it writes a page, it makes sure the log has been flushed past the page's LSN.
A record says what to change in a form the engine can replay. ARIES allows the bytes before and after a change, or an operation such as "add 5 to field 3 of record 15". A Postgres record names a block in a data file and the change to it. Only a server with the same data files can use that, which matters when a replica reads the log.
What a commit costs: fsync
When a program writes to a file, the operating system copies the bytes into its page cache, memory it writes to disk later. If the program crashes, nothing is lost, because the operating system still holds the bytes. If the machine crashes or loses power, they're gone. fsync is the call that pushes a file's cached bytes to the drive and waits until the drive says they're stored. A durable commit is a write to the log and then an fsync, and the client waits for both.
How long the fsync takes depends almost entirely on the drive. Percona measured it in 2018 on spinning disks and solid-state drives (SSDs), writing and flushing one file 1,000 times on each. The chart shows ten of them.
The gap comes from each drive's own cache. Every SSD has a volatile write cache. A drive with power-loss protection carries capacitors that hold enough charge to write that cache to flash if the power fails. So it can confirm a flush as soon as the data is in its cache. A drive without it has to write the data to flash first.
A spinning disk has to wait for the platter to bring the right sector under the head. Percona's disks spun at 5,400 or 7,200 revolutions per minute (RPM), and the faster ones flushed faster.
Other pages in this course use 0.3 ms for a flush on a data-centre NVMe drive, between Percona's two protected NVMe drives.
Group commit
A drive that takes 3.8 ms per flush manages about 263 flushes a second. If every commit needed a flush of its own, that would be the database's commit rate. It isn't, because one flush covers everything in the log up to the point where it was called.
So while one flush is running, commits from other sessions append their records and wait. When the flush finishes, the next one carries all of them. This is group commit. The Postgres documentation says one fsync of the WAL can commit many transactions. With the default settings, a group is every session that reached its commit while the previous flush was running.
How far does that go? Take 10,000 commits a second and the two NVMe drives from the chart.
The question is whether a slow flush caps the commit
rate, or only slows each commit down. Many sessions
commit at once. Flush times are Percona's.
Consumer NVMe, 3.8 ms a flush
one flush per commit 1 / 3.8 ms ≈ 263/s
commits arriving during
one flush 10,000 × 3.8 ms ≈ 38
flushes needed 10,000 / 38 ≈ 263/s
each commit waits 3.8 to 7.6 ms
average, 1.5 flushes 1.5 × 3.8 ms ≈ 5.7 ms
sessions committing
at once 10,000 × 5.7 ms ≈ 57
Enterprise NVMe, 0.14 ms a flush
one flush per commit measured ≈ 7,380/s
commits per flush 10,000 × 0.14 ms ≈ 1.4
each commit waits 0.14 to 0.28 ms
average, 1.5 flushes 1.5 × 0.14 ms ≈ 0.21 ms
sessions committing
at once 10,000 × 0.21 ms ≈ 2
─────────────────────────────────────────────────────────
Both drives reach 10,000 commits a second. The slow
one needs about 57 sessions committing at once, and
each commit waits about 27 times as long.A slow flush costs latency, not throughput, as long as enough sessions are committing at once. This is the batching trade from latency numbers that matter. Because only the log has to be right, a commit costs one flush of it, and one flush serves everyone waiting.
How often to flush
Most engines let you acknowledge before the flush. The record goes into the log buffer in memory, the client hears yes, and a background process flushes a moment later. A crash in between takes back the last few commits.
The question is how many acknowledged commits a
machine crash can lose with each engine's
flush-later setting.
Postgres, synchronous_commit = off
flushed within 3 × wal_writer_delay
3 × 200 ms = 600 ms
commits lost, at most 0.6 s × 10,000/s = 6,000
MySQL InnoDB, innodb_flush_log_at_trx_commit = 0 or 2
flushed about once a second
commits lost, up to 1 s × 10,000/s ≈ 10,000
Redis, AOF on (off by default), everysec
flushed once a second
commits lost, up to 1 s × 10,000/s ≈ 10,000
─────────────────────────────────────────────────────────
Thousands of commits that a client was told had
succeeded. That's acceptable for page views and
not for payments.All three lose only the end of the log. The log is complete and in order up to some point, so recovery produces the database as it was a moment before the crash. Postgres's documentation says the result is the same as if the lost transactions had been aborted cleanly. That's lost data, not corrupted data.
Turning the flush off altogether is a different thing. Postgres's fsync = off lets pages reach the disk before the records that describe them, which breaks the rule the log is named for. Its documentation warns that a power failure can then cause unrecoverable corruption, and advises it only if you can recreate the whole database from somewhere else. SQLite's synchronous = OFF carries the same warning.
The choice can be made per transaction. Replication and leader election covers Postgres's synchronous_commit levels, including those that wait for a standby, and why a payment and a page view get different ones.
Checkpoints, and what they bound
Left alone, the log grows forever and a restart replays it from the beginning. The Raft paper names both problems: as the log grows, it occupies more space and takes more time to replay. A checkpoint fixes both.
A checkpoint writes every dirty page, a page changed in memory but not yet written, to the data files. Then it writes a checkpoint record into the log. Every change logged before the checkpoint started is now in the data files. Recovery starts at that point, the redo point, and the log before it can be deleted or reused. Transactions keep running during a checkpoint, and Postgres spreads a checkpoint's page writes over 90 percent of the interval, so they don't arrive as one burst.
Because the writes are spread out, the last finished checkpoint can be almost two intervals old. Say checkpoints start every T minutes. One starts at time 0 and finishes at 0.9T. The next starts at T and finishes at 1.9T. A crash just before 1.9T recovers from the redo point at time 0, so it replays up to 1.9 intervals of log.
So the interval bounds two things: how much log you keep, and how much a restart replays. The cost runs the other way. A page changed 1,000 times between checkpoints is written to its data file once, so shorter intervals mean more page writes. And the full-page images covered below make every checkpoint add to the log.
Engines trigger a checkpoint on time, on log size, or on whichever comes first, and the engines table below gives each one's trigger. A size limit sets an interval too: divide the limit by how fast you write log. Search engines that write index files in batches keep a log for the same reason, such as Elasticsearch's translog, and inverted indexes covers those files.
The checkpoint isn't the only thing holding on to the log. A standby that's behind, a failing archive or a stopped change data capture reader all need log the checkpoint has passed. The engine keeps it for them. Postgres keeps every byte a replication slot's reader hasn't confirmed, with no limit by default.
Crash recovery: redo, and the idea of ARIES
On restart, the engine finds the last checkpoint and reads the log forward from its redo point.
Redo has to handle pages that were written after the checkpoint and pages that weren't, and the page LSN says which is which. For each record, redo reads the page and compares the two numbers. If the page's LSN is lower than the record's, the page is missing this change, so redo applies it and sets the page's LSN to the record's. If not, the change is already on the page and redo skips it. Running redo twice gives the same pages as running it once. A crash during recovery is therefore harmless, because the next restart runs redo again.
ARIES adds the part that deals with transactions that hadn't finished. A restart makes three passes over the log.
- Analysis reads forward from the last checkpoint to the end of the log. It works out which pages may be dirty and which transactions were still running at the crash. Those transactions are the losers.
- Redo reads forward from the oldest change any dirty page might be missing, and reapplies every logged change, the losers' included. ARIES calls this repeating history. Afterwards the pages are exactly as they were at the moment of the crash.
- Undo rolls back the losers, newest change first. Each undo is logged too, as a compensation log record, so a crash during undo never undoes the same change twice.
Because redo restores the moment of the crash, undo becomes an ordinary rollback on pages in a known state. And redo doesn't need to know which transactions will turn out to be losers.
The passes cost different kinds of downtime. InnoDB accepts connections as soon as redo is done, and rolls back unfinished transactions in a background thread. Its documentation says that rollback can take three or four times as long as the transaction had been running. A batch job that held one transaction open for 20 minutes before a crash can keep its rows locked for an hour or more after the restart. Commit long jobs in chunks they can redo.
Torn pages: full-page writes and doublewrite
Redo assumes the page it reads is a whole page, old or new. A crash can leave it neither. The drive writes an 8 KB Postgres page as 16 sectors of 512 bytes, and a power cut part way through leaves some sectors new and some old. That's a torn page.
A log record can't repair it. "Insert this row at offset 3,120" makes sense only on a page whose other bytes are intact. Recovery has to be able to rebuild a page from nothing, so a whole copy of the page has to exist somewhere a crash can't have torn.
Engines keep that copy in different places.
- Postgres writes the whole page into the WAL the first time the page changes after each checkpoint. Redo starts by restoring that full-page image, then applies the later records. Later changes to the page before the next checkpoint log only the change.
- InnoDB writes each page it flushes to a doublewrite file first, then to its place in the data file. After a crash it finds a good copy in one of the two. Its documentation notes that the I/O doesn't double, because the doublewrite batch goes out as one large sequential write with one
fsync. - SQLite in WAL mode logs whole pages every time. Each WAL frame is one page, and the database file is written only at a checkpoint, from those complete copies.
An engine can skip the copy only where a page can't be torn. Postgres's documentation allows turning page images off on a file system that prevents partial writes, such as ZFS. A log-structured merge (LSM) tree never overwrites a data file once it's written, so its data files can't be torn this way.
The Postgres copy is expensive when changes are spread thin. LSM trees vs B-trees prices a random 100-byte insert into a large index at about 5.7 KB of page image on top of the change record. The image is paid once per page per checkpoint interval, so the interval decides how often you pay it, and the second worked example sizes that.
The log as the source for replication
If the log can rebuild the database after a crash, it can build a second copy somewhere else. A Postgres standby is a server that never leaves recovery: it receives the primary's WAL and keeps replaying it. The documentation says a standby fed record by record is typically under a second behind, if it can keep up with the load. Recovery runs in one process, the startup process, so a standby can receive the WAL on time and still fall behind applying it.
The record format sets the limits. Postgres's WAL names blocks in data files, so a standby is a byte-for-byte copy. It copies the whole server, not chosen tables, and needs the same hardware architecture and the same major version. For per-table changes, Postgres with wal_level = logical logs extra detail and decodes the WAL into row changes, which is logical replication. Feeding other systems from that decoded stream is change data capture.
MySQL took the other route. InnoDB's redo log stays inside the server. Replicas read the binary log, a second log of row changes written beside it.
The two logs have to agree on every commit, or a replica receives a transaction that InnoDB rolled back. MySQL keeps them in step with an internal two-phase commit: InnoDB prepares the transaction, the server writes and syncs the binary log, and then InnoDB commits. Each commit needs both logs flushed, batched by one group commit.
Raft builds the same idea into the protocol. Quorums, Raft and Paxos describes the leader's log, which a majority must hold before an entry commits. The Raft paper requires each server to write its log to stable storage before answering. Its snapshots do a checkpoint's job: each one replaces the log up to a point, so the log stops growing and a restart replays less.
The log also gives you a backup that a replica can't. A replica replays your DROP TABLE within a second. A physical backup, a copy of the data files, plus every WAL file archived since, lets you restore the copy and replay up to the moment before the mistake. Postgres calls this point-in-time recovery.
How a WAL differs from an event log
Kafka is also an append-only log that readers consume in order, and message queues vs event streams covers it from the consumer's side. Both are logs, so they get mixed up, but they differ on each of these.
| a database's WAL | a Kafka topic | |
|---|---|---|
| who reads it | recovery, replicas of the same engine, and decoders such as change data capture | any consumer, each at its own offset |
| what a record is | a change to a page, in the engine's own format | an event your application defined |
| how long it's kept | until a checkpoint has passed it and no reader needs it, then recycled or archived | until its retention period ends |
| what makes a write durable | an fsync before the commit is acknowledged | copies on the in-sync replicas, with no fsync per write |
Kafka's design documentation says data is written to the log on the file system without necessarily being flushed, so it sits in the operating system's page cache. Kafka promises that a committed message isn't lost as long as one in-sync replica stays alive. It also says that requiring an fsync on every write could cut performance by two to three orders of magnitude. The risk it accepts is every in-sync replica losing power at once.
The difference comes from what each log is for. A WAL is kept until a checkpoint and every reader have passed it, and then it's recycled or archived. A Kafka topic is the data itself, kept for its readers, and nothing can rebuild it.
Which engines do what
| engine | the log | synced before commit returns, by default | what triggers a checkpoint | replicas read |
|---|---|---|---|---|
| Postgres | WAL, in 16 MB segment files | yes | 5 minutes, or the log nearing max_wal_size, 1 GB | the WAL itself |
| MySQL InnoDB | redo log of a set capacity, 100 MB by default | yes | the redo log filling | the binary log, a second log |
| SQLite, WAL mode | a WAL of whole pages | with FULL, not with NORMAL | 1,000 pages of WAL | no built-in replicas |
| RocksDB | one WAL for all memtables | no | a full memtable (write_buffer_size, 64 MB), with max_total_wal_size as the backstop | no built-in replicas |
| Kafka | the topic is the log | no | a recovery point every 60 s; retention deletes old segments | followers copy the leader's log |
The method
1. Say what a commit must survive. A process crash, a power cut, the loss of the machine or the loss of a zone. A process crash needs only the record written to the operating system. Postgres's synchronous_commit = off and InnoDB's setting 0 can skip that too, so they can lose commits to a process crash. A power cut needs the flush. The last two need a copy on another machine.
2. Price one flush on the drive you'll run. Ask whether it has power-loss protection. On Percona's NVMe drives that's 0.14 ms against 3.8 ms.
3. Count the sessions committing at once. Sessions share flushes, so the commit rate is the group size divided by the flush time.
4. Decide which writes may skip the flush. Choose per transaction where the engine allows it, and write down the loss: up to 600 ms of commits for Postgres's asynchronous commit.
5. Set the checkpoint from the restart you can afford. A restart replays up to about two intervals of log. Check that the log size limit doesn't trigger checkpoints more often than you meant, and price the page images.
6. List every reader of the log. Standbys, the archive and change data capture readers can each stop the log from being trimmed. Cap what each may hold, and alert before the cap.
Worked examples, start to finish
Each of these three breaks a different obvious answer.
An import that commits one row at a time
A nightly job loads 1,000,000 rows into Postgres. It runs as one session and commits after every row. It takes over an hour. The obvious fixes are a faster drive or turning off fsync for the load.
The question is where the hour goes, and which fix
removes it. One session, so every commit waits for
its own flush. The drive is the consumer NVMe drive
from the chart, 3.8 ms a flush.
One row per transaction
flushes 1,000,000
waiting on flushes 1,000,000 × 3.8 ms = 3,800 s
≈ 63 min
1,000 rows per transaction
flushes 1,000,000 / 1,000 = 1,000
waiting on flushes 1,000 × 3.8 ms = 3.8 s
The enterprise drive, one row per transaction
waiting on flushes 1,000,000 × 0.14 ms = 140 s
─────────────────────────────────────────────────────────
Batching cuts the waiting by 1,000 times on the drive
you already have. The better drive cuts it by 27.Group commit doesn't help here. It shares a flush among commits that are waiting at the same moment, and one session never has two. Turning fsync off would risk the whole database, as the flush section explains.
The decision is to commit in batches of 1,000 rows, and to write the last loaded id in the same transaction as each batch. Flush waiting per row drops from 3.8 ms to 3.8 µs. A crash loses at most the batch in progress, and the restarted job resumes after the last committed batch instead of loading it twice.
If the job can't batch, set synchronous_commit = off for this one session. A crash then loses at most the last 600 ms of the load and nothing else in the database.
A checkpoint interval chosen for fast restarts
A Postgres primary takes 20,000 updates a second on a 20 GB table, and each update changes one row on a page chosen at random. The team wants quick restarts after a crash, so it shortens the checkpoint interval to 1 minute. The log volume jumps, and so does the bandwidth to every standby and the size of the archive.
The page images cause it. The first change to a page after each checkpoint logs an image of the whole page, up to 8 KB, so a shorter interval means more first changes. How many depends on how many updates each page gets per interval, the same ratio LSM trees vs B-trees uses to price a B-tree insert.
The question is how the interval changes the log, and
the replay after a crash. Each update logs ~100 B. The
first change to a page after a checkpoint also logs
the page, 8 KB: a full heap page logs nearly all of
it, and a part-full index leaf logs less, because the
empty middle is left out.
An interval of T seconds has 20,000 × T updates over
P pages. A page misses one random update with chance
1 − 1/P, so it misses them all with chance about
e^(−20,000 × T / P). It's touched otherwise.
A 20 GB table, P = 2.6M pages
1 min 5 min 30 min
updates 1.2M 6M 36M
pages touched 0.96M 2.4M 2.6M
updates logging a page 80% 39% 7%
log per update 6.7 KB 3.3 KB 0.7 KB
log per second 134 MB/s 66 MB/s 14 MB/s
log per day 11.5 TB 5.7 TB 1.2 TB
pages written back,
touched × 8 KB / T 131 MB/s 64 MB/s 12 MB/s
replay, up to 1.9 T 15 GB 38 GB 48 GB
A 200 GB table, P = 26M pages
updates logging a page 98% 89% 54%
log per second 162 MB/s 148 MB/s 91 MB/s
replay, up to 1.9 T 18 GB 85 GB 312 GB
─────────────────────────────────────────────────────
On the 20 GB table, 30 minutes cuts the log to a
tenth and only triples the replay. On the 200 GB
table each interval still touches most pages once,
so the log falls by less than half and the replay
grows 17 times.Every column assumes the log size limit is high enough for the clock to decide. Postgres starts a checkpoint once the log since the last one reaches max_wal_size divided by 1.9, about 540 MB at the 1 GB default. At 134 MB a second that's a checkpoint every 4 seconds, whatever the timeout says.
So how often should this database checkpoint, when a restart replays up to two intervals of log?
Checkpoint every minute, so restarts are quick
Less log to replay means a faster restart, and the setting is one line.
The worksheet breaks it. At 1 minute, 80 percent of updates carry a page image, and the log runs at 134 MB a second, 11.5 TB a day that every standby receives and the archive keeps. The checkpoints also write the changed pages back, 131 MB a second against 12 at 30 minutes. And it saves little replay: 15 GB against 48 GB.
A long interval, with the log size limit raised to match
Set the interval from the restart you can afford. At 30 minutes the log falls to 14 MB a second, because almost every page already has its image and later changes log only about 100 bytes. A restart replays at most 48 GB.
Raise max_wal_size to match, about 48 GB here, because that's how much log the server now keeps on disk. WAL compression shrinks the page images further, for some CPU.
This is what most teams run. The cost is the restart: up to 48 GB of replay, plus a read of every page it touches. If that restart is your RTO, the recovery time objective that says how long users notice a failure, the next tier asks whether it has to be.
Recover by failing over, and set the interval for the log
Question the premise that the crashed server's restart is the recovery. A hot standby has been replaying this WAL all along, typically under a second behind if it keeps up, so promoting it waits for little replay. Watch its replay lag, not only what it has received, because one process does the replay. Replication and leader election budgets a failover at about 33 seconds, most of it clients reconnecting.
With the restart off the critical path, choose the interval for the log's cost. At 30 minutes the log is a tenth of the 1-minute figure, and so are the bandwidth to every standby and the archive's growth.
What you give up: you need a standby you trust to take over. An asynchronous standby loses the commits it hadn't received, and the old primary has to be stopped from writing once the standby is promoted. On the 200 GB table, a longer interval buys less, because each interval still touches most pages: 91 MB a second at 30 minutes against 162 at 1 minute.
A key-value store that must not lose a write
The question is to design a key-value store. It takes 20,000 puts a second of values up to 1 KB, and once a put is acknowledged it must survive a crash. The first instinct is to store each value in its place in a data file and make that write durable.
The question is what each design pays per put, and which failures an acknowledged put survives. 20,000 puts a second of 1 KB. The course's figures: 0.3 ms a flush on a data-centre drive, and a 1.5 ms round trip between zones. Write the value in place pages changed value + index 2 × 4 KB random disk writes 20,000 × 8 KB = 160 MB/s wait, 2 flushes 2 × 0.3 ms = 0.6 ms survives a crash, unless a page tears Append to a log, group commit disk writes, in order 20,000 × 1 KB = 20 MB/s puts per flush 20,000 × 0.3 ms ≈ 6 wait 0.3 to 0.6 ms survives a crash or a power cut Replicate the log to 3 zones, ack at 2 wait 1.5 + 0.3 ms ≈ 1.8 ms leader sends 2 × 20 MB/s = 40 MB/s survives losing any one machine or zone ───────────────────────────────────────────────────────── The log cuts the disk writes to an eighth and makes them sequential. Replicating it waits three to six times as long and survives losing the machine.
Write each value in place, and flush it
It keeps one copy of everything, with no log to manage, and a get is one read.
The worksheet prices it at 160 MB a second of random writes for 20 MB a second of data. Correctness breaks it first. A put changes two pages, and a crash between them leaves the index and the value disagreeing. Worse, a power cut while a 4 KB page is being written tears it, and the torn page loses other keys' values that were acknowledged long ago.
Append every put to a log, then apply it in memory
Each put appends a record of key, value and checksum to the log. Group commit flushes it, the in-memory index is updated, and the client hears yes. The data files are written in the background, as an LSM tree like RocksDB does, or as periodic snapshots of the whole state. A restart loads the latest snapshot and replays the log after it.
This is the standard answer. Writes are sequential, 20 MB a second, and a put waits 0.3 to 0.6 ms. Snapshots bound the replay the way checkpoints do. The cost is that everything rests on one machine's disk. If that disk fails, every put since the last backup is gone, and while the machine is down the key-value store is down.
Make the replicated log the durable copy
Question the premise that durable means flushed on this machine. Send each log record to three nodes in three zones, and acknowledge once two of them have it on disk. This is a Raft log. The wait becomes about 1.8 ms, three to six times the senior tier's, and an acknowledged put now survives losing any one machine or zone.
Each node's data files are now a copy its log can rebuild, and the log exists on three machines. A node that loses its disk gets a snapshot and the log after it from the leader.
Amazon's Aurora takes this furthest: the database writes only log records over the network, and the storage nodes build the pages. In its paper's benchmark, that sustained 35 times as many transactions as mirrored MySQL, with 7.7 times fewer I/Os per transaction on the database node.
What you give up: three machines for one machine's data, a consensus protocol, and one leader whose log sets the write ceiling. You also need terms on the log, so a deposed leader's late writes are refused. Some systems go further and drop the per-write flush, as Kafka does, which leaves the risk that every replica loses power at once.
Where it goes wrong
These are ordered by how often they come up.
1. Calling Kafka a write-ahead log
Kafka doesn't flush each write. Its durability comes from in-sync replicas, so if it's the only copy of your data, the replicas need separate power and zones. In the other direction, a database's WAL is an internal format kept until a checkpoint and every reader have passed it. Reading it as an event stream is what change data capture does, with a decoder in between.
2. Forgetting what holds the log
A stopped change data capture reader, a failing archive or a standby that's down for maintenance keeps every byte of log written since. At 14 MB a second that's 1.2 TB a day. Cap what each reader may hold, and alert well before the cap.
3. Checkpointing often for quick restarts
Every checkpoint restarts the page images. On the 20 GB table in the second example, 1-minute checkpoints make the log ten times bigger than 30-minute ones, for a replay only a third as long. A log size limit set too low does the same, whatever the timeout says.
4. Trusting a flush you haven't measured
Percona's drives ranged from 0.04 ms to 66 ms per flush, and a drive without power-loss protection that reports a fast flush is probably not flushing. Measure the drive you'll run before you size commits on it.
5. Retrying a failed fsync
In 2018, Craig Ringer reported on the Postgres developers' mailing list that Postgres retried a failed fsync and trusted a later success. On Linux, a failed write-back can mark the pages clean and drop the data, so the retry succeeds with nothing left to write. Since the February 2019 releases, such as 11.2, Postgres panics on a failed flush and recovers from the WAL, unless data_sync_retry is turned on.
That fix doesn't make the problem go away. Rebello and colleagues tested Postgres 12.0 in 2020 and still found commits reported as failed that had been kept, and existing keys lost on ext4 in full data-journaling mode. Crash and replay is the best rule known, not a guarantee.
If you memorise nothing else
| fact | why it matters |
|---|---|
| A commit waits for the log flush, not the page | the page reaches the data file minutes later |
| A flush costs 0.14 ms with power-loss protection, 3.8 ms on a consumer NVMe drive without it, ~20 ms on a 7,200 RPM disk | the drive sets commit latency |
| Group commit lets one flush carry every waiting commit | throughput comes from concurrency, latency from the drive |
| One session gets one commit per flush | batch rows per transaction |
| Flush-later settings lose up to the last second of commits | 600 ms in Postgres, about 1 s in InnoDB and Redis |
| Turning the flush off can corrupt data, not only lose it | pages reach disk before their log records |
| RocksDB doesn't sync its WAL by default | process crash safe, power cut not |
| A Postgres restart replays up to ~1.9 checkpoint intervals | the checkpoint bounds replay and log size |
| A log size limit sets a checkpoint interval | divide it by the log write rate |
| The first change to a page after a checkpoint logs the whole page | short intervals multiply the log |
| Redo compares page LSN with record LSN | replay is safe to repeat |
| ARIES: analysis, redo everything, undo the losers | undo is logged too, so it never repeats |
| The slowest reader holds the log | slots, archives and old readers fill disks |
| Postgres ships its WAL; MySQL ships a second log | physical copies need the same major version |
| Kafka doesn't flush each write | its durability is in-sync replicas |
What is expected at each level
Mid-level
Know the rule: the log is written and flushed before the changed pages, and a commit waits only for the log. Know that recovery replays the log from the last checkpoint, and that checkpoints exist so the replay and the log stay bounded. Know what fsync does.
You aren't expected to size group commit or page images unprompted. Suppose you're asked what happens if the server loses power right after a commit. A good mid-level answer is "the change is in the log on disk, so the restart replays it into the pages".
Senior
You lead this part, and three things must come up without prompting.
The price of a durable commit, and how it's shared. One flush, priced on the drive in the design, shared by group commit. Say what a single session can do and what many can.
What "committed" means here. Which writes wait for the flush, which may skip it, and how much a crash can take back, in commits or milliseconds.
What bounds a restart. The checkpoint interval, the replay it implies in bytes, and the log readers that can stop the log being trimmed.
Two things are disqualifying: turning off fsync to fix throughput, and a design that says "we write to disk" without saying when the client hears yes.
Staff+
Producing a correct design is still the bar. A staff answer decides where durability lives, with numbers.
Move durability to the replicated log when losing a machine is in scope. Price it at a round trip plus a flush, and say what a node does when its disk dies.
Choose the checkpoint interval for the log, not the restart, when a standby can take over, and size the page images that decide the log's volume.
Separate the two logs. A WAL is the engine's private record, kept until a checkpoint and every reader have passed it. An event log is data kept for readers, and Kafka makes it durable differently.
Treat the log's readers as part of its capacity. Every slot, archive and decoder has a cap and an alert.
And say what you would not build. Each of these can cost a team a quarter.
One is a custom write-ahead log in an application that already sits on a database. Another is faster disks for an import that commits one row at a time. A third is synchronous_commit = off for the whole cluster, when only the page views could afford it.
Another is ever shorter checkpoints for recovery time, when a standby has already replayed the log. And the last is Kafka as the only copy of payments, with nobody pricing every in-sync replica losing power at once.
Sources
Every engine behaviour and measured number here comes from the sources below, and the arithmetic is worked out on the page from them.
- ARIES, Mohan et al., ACM TODS 1992. The WAL rule, steal and no-force, page LSNs, checkpoints and the three restart passes.
- The PostgreSQL documentation on the WAL, torn pages, checkpoints and group commit, asynchronous commit, WAL internals, WAL settings, data_sync_retry, log shipping, replication options and slot limits. Also its hot standby page on the startup process, and the 11.2 release notes for the fsync panic. Its source file xlog.c gives the checkpoint trigger.
- The MySQL documentation on the InnoDB redo log, the doublewrite buffer, flush settings, crash recovery and the binary log.
- SQLite on WAL mode, the WAL format and synchronous. The RocksDB wiki on the WAL, its performance and memtable flushes. Redis persistence, the Elasticsearch translog, and Kafka's design on page-cache writes and in-sync replicas, with its broker settings for the recovery point.
- Fsync Performance on Storage Devices, Yves Trudeau, Percona, 2018. Flush times across drives, and why only drives with capacitors can flush fast and keep the data. Intel's 750 Series specification, April 2015, lists its power-loss data protection.
- On failed flushes: PostgreSQL's fsync() surprise, LWN, 2018; the PostgreSQL wiki's Fsync Errors; and Can Applications Recover from fsync Failures?, Rebello et al., USENIX ATC 2020, which tested Postgres 12.0 after the fix.
- Amazon Aurora, Verbitski et al., SIGMOD 2017: only redo records cross the network, and the 35 times and 7.7 times results. The Raft paper, Ongaro and Ousterhout, 2014: stable storage before replying, and snapshots.