Key takeaways
- ✓When a store says OK, the write can be in the program's own memory, the operating system's memory, the drive's cache or on the disk. OK promises only what the code did before saying it. A write is durable once it would survive a crash.
- ✓A killed program loses only its own memory; a power cut also loses the operating system's memory and can leave half a record. Our two stores, killed 260 times, lost no acknowledged write, even the 60 kills with no flush, because each write reached the operating system before OK.
- ✓A power cut was simulated by cutting a copy of the file at a random byte, 200 times. Recovery reads records from the start and stops at the first incomplete one: every complete record was kept every time. The length check caught all 200; the checksum guards against bytes that are wrong rather than missing.
- ✓A flush is expensive. 5,000 small writes on the Mac: 544,415 a second with no flush, 44,644 with fsync on each (which on a Mac stops at the drive's cache), 212 with F_FULLFSYNC, which makes the drive store it. About 2,600× slower than no flush.
- ✓Postgres flushes before every commit's OK by default: 2,698 commits a second with one client, 8,332 with 16, every one still flushed. Part of the 3.1× is clients overlapping their trips; part is group commit, one flush covering the commits that piled up during the last.
- ✓synchronous_commit = off says OK before the flush: 1.9× the commits with 16 clients, nothing with one. Killed five times, Postgres lost 0 of 37,803 acknowledged inserts with it on, and 11,163 of 168,613 (6.6%) with it off, some in every kill.
- ✓Choose per transaction: turn it off for writes you can lose a fraction of a second of (page views, metrics, logs), keep it on for orders, payments and anything you told a customer is saved.
Most code treats a database's OK as "saved". This chapter checks what OK really promises. The short version: OK means whatever the code did before saying it. Postgres was force-stopped in the middle of a stream of writes five times with one setting and five times with another; with the first, every write it had said OK to was still there, and with the second, 11,163 were gone. Same database, one setting.
The examples come from Lab 04 (Storage Engines and Indexes) of the system design labs: the first three exercises of 01_kvstore.py (two small stores built from scratch, killed, cut and timed) and 04_durability.py (Postgres, timed and then killed). The same lab's indexes (03_indexes.py) are Chapter 6. The rest of the lab, B-trees against log-structured stores and how many bytes each writes (01_kvstore.py Exercise 4 and 02_engines.py), and connection pooling (05_pooling_n1.py), isn't covered in this series. Everything ran on one laptop (an Apple M4 Max, its own SSD), with Postgres 18.6 in Docker Desktop. Other work kept the laptop busy: its load average, the number of processes wanting a core, was 8 when the store tests finished and 21 when the Postgres run finished.
The two stores live in the lab's kvstore/ folder and save keys and values in files. Store A (LogStore in the code) appends every write to the end of one file, a log, and keeps an in-memory index of where each key's latest value is. Store B (LSMStore) first appends every write to a write-ahead log, a file whose only job is to hold changes until they're stored properly, then keeps them in memory and writes sorted files later. For this chapter they behave the same way: each write is one record appended to a log file.
Where is the write when the database says OK?
Think of a filing office. A clerk takes your form. While it's in the clerk's hand, it's in the program's own memory. Then the clerk drops it in the out-tray, the operating system's memory: fast. The clerk says "got it": that's the store's OK, called an acknowledgement. Only later does someone walk the form to the fireproof cabinet, the disk: a slow walk. Making that walk now, and waiting until the form is in the cabinet, is a flush; the system call that asks for it is fsync. On some machines the walk stops at a tray by the cabinet's door, the drive's own cache, and a power cut can still empty that tray.
Who says OK, and when
Then
A write moves left to right. Each step is a different place; the OK can be said after any of them. What happens after the OK (the operating system writing it to disk a little later) doesn't help a write that was lost first.
write(), then Python's flush() hands it to the operating system, then OK.
Recorded: 60 kills of stores A and B, 783,423 writes acknowledged, 0 lost.
A write is durable if it would survive a crash. Which crash matters, because the two kinds empty different places.
Two kinds of crash
| Crash | Like | What's lost | What protects an acknowledged write |
|---|---|---|---|
| The program is killed | the clerk faints | the program's own memory | saying OK only after the write has left the program |
| A power cut | the building goes dark | the program's memory, the operating system's memory and the drive's cache; a write can stop halfway | a flush that reaches the disk before OK, and a way to recognize half a record |
A program crash can't touch the out-tray. A flush is what protects you from power cuts.
Our stores, killed 260 times
Here is how store A saves one record (kvstore/log_store.py):
def _append(self, rec: bytes):
self.f.write(rec) # into our own buffer: the clerk's hand
self.f.flush() # Python's flush(): hands it to the operating system (the out-tray)
if self.sync:
durable_sync(self.f.fileno(), self.full_sync) # fsync: asks for the walk to the cabinet
Python's flush() has the same name as the flush above but only reaches the out-tray. durable_sync is the lab's wrapper for the real one: plain fsync, or on macOS optionally F_FULLFSYNC (more on that below). The store's put() returns after this, and a separate writer program prints each key as soon as put() returns: that's the acknowledgement.
The test starts the writer, lets it write for a random 20–300 ms, and kills it with SIGKILL, the signal a program can't catch or clean up after. Then it reopens the store and looks for every key that was acknowledged. Stores A and B were each killed 100 times with fsync on every write, then 30 more times with no fsync at all:
| Store | fsync | Kills | Acknowledged writes | Acknowledged but lost | Written, not yet acknowledged |
|---|---|---|---|---|---|
| A | on | 100 | 626,686 | 0 | 83 |
| B | on | 100 | 78,612 | 0 | 100 |
| A | off | 30 | 731,852 | 0 | 13 |
| B | off | 30 | 51,571 | 0 | 30 |
Nothing acknowledged was lost, even with no flush: each write was in the out-tray before the store said OK, and killing the program never touches the out-tray. No kill left half a record either, because each record goes to the operating system in one write() call, which a program kill can't split.
The last column is the other side of the same coin. In most kills (226 of 260) the write that was under way had reached the file, but the kill came before its acknowledgement reached the writer. That's allowed, but it means a client that never got an answer can't know whether its write happened: it has to retry, and the write has to be safe to apply twice. That's Chapter 10.
A power cut, mid-write
A power cut is worse: it can stop a write halfway and leave half a record at the end of the file. You can't cut a laptop's power hundreds of times, so the lab simulates it: copy a store's file and cut the copy at a random byte, 100 times in store A's log (2,000 records, 131,560 bytes) and 100 times in store B's write-ahead log (150 records, 9,160 bytes). Then open the store and check that it kept every record that was complete before the cut, and nothing else.
Every record has the same layout (kvstore/records.py): a 12-byte header (a checksum, then the key's length and the value's length, 4 bytes each), then the key and the value. A checksum is a number computed from the rest of the record; here it's CRC32, a common 32-bit checksum. On opening, the store reads records from the start and stops at the first one that can't be trusted, and cuts the file there:
- fewer than 12 bytes left: not even a header, stop;
- the lengths say the record runs past the end of the file: stop;
- the checksum doesn't match the bytes: stop.
All 200 recoveries kept exactly the complete records, and dropped only the half one. Move the cut yourself on the first six records of store A's log, built with the lab's own format:
Record 4 says it is 56 bytes long, but only 32 are left: it runs past the end of the file. Stop.
The lab: 100 random cuts in each store
Store A (its log, 131,560 bytes): 100 cuts, 0 wrong recoveries. Store B (its write-ahead log, 9,160 bytes): 100 cuts, 0 wrong recoveries. What stopped each scan: ran past the end 154, a header shorter than 12 bytes 41, a cut exactly on a boundary 5, a bad checksum 0.
The breakdown by check isn't saved by the lab; it was recomputed by re-running Exercise 2 with the lab's own code and seed, which reproduced the saved results. A cut only shortens the file, so the length checks catch every one; the checksum is tested by the lab's unit test that corrupts one byte.
Which check did the work? The lab doesn't save that, so the cuts were rerun with the lab's code and seed: the record ran past the end 154 times, the header was incomplete 41 times, and 5 cuts fell exactly between two records, so nothing had to be dropped. The checksum never fired. A cut only shortens the file, so the length checks catch every one. The checksum is for a different failure: bytes that are all there but wrong, like garbage in the middle of a file, or a file that grew before its last bytes arrived. The lab's unit test for that corrupts one byte, and the reader stops right there.
The price of the walk
So why not flush every write? Here's the price, on the Mac: 5,000 writes of 50 bytes into store A, three ways.
| Durability | Writes a second | µs per write | Reaches |
|---|---|---|---|
| no flush | 544,415 | 1.8 | the out-tray (operating system's memory) |
fsync() on each write |
44,644 | 22 | the drive's cache |
F_FULLFSYNC on each write |
212 | 4,706 | the disk itself |
On macOS, fsync() hands the data to the drive but doesn't make the drive empty its own cache, so a power cut can still lose it. F_FULLFSYNC is macOS's stronger flush, which does make the drive store it. With that on each write: 212 writes a second, almost 5 ms each, about 2,600 times slower than leaving the write in the out-tray. That's why databases avoid one flush per write.
Writes a second, log scale: each step is ten times more.
F_FULLFSYNC makes the drive write its cache to flash: the walk all the way into the cabinet, on every write.
Postgres: one walk, many commits
In Postgres, the OK is a commit: the end of a transaction, one group of writes saved together. Before it answers a commit, Postgres writes the change to its own write-ahead log and, by default, flushes that log. It runs in Docker's Linux virtual machine (VM), where the flush is a different one: fdatasync, measured in Lab 01 with Postgres's pg_test_fsync tool at 83 µs. It most likely stops at a cache, like plain fsync on the Mac. (The 212 a second above and Postgres's thousands below are different flushes on different layers; they can't be compared directly.)
04_durability.py measures commits a second with one insert per commit, for 8 seconds each:
| Clients | Commits a second | Per commit, per client |
|---|---|---|
| 1 | 2,698 | 0.37 ms |
| 16 | 8,332 | 1.92 ms |
Sixteen clients got 3.1× the commits of one, and every one was still flushed before its OK. Part of that is 16 clients overlapping their trips to the database. Part is group commit: while one flush is under way, more commits pile up, and the next flush carries them all. The lab didn't count flushes per commit, so it can't say how big each part is.
OK before the walk: synchronous_commit = off
Postgres has a setting to skip the wait: synchronous_commit. Normally it's on: write the log, flush it, then OK. Turned off, Postgres says OK first. A background process, the WAL writer, flushes the log a moment later: usually within 200 ms (the default wal_writer_delay); Postgres's documentation puts the worst case at three times that. Until then, the write is still in Postgres's own memory: in the clerk's hand.
| Clients | on | off | off ÷ on |
|---|---|---|---|
| 1 | 2,698 | 2,502 | 0.93× |
| 16 | 8,332 | 15,820 | 1.9× |
With 16 clients it almost doubled the commits a second. With one client it made no difference: at 371 µs per commit, most of the time is the trip to the database and back, and the 83 µs flush is a small part. On a disk whose flush takes milliseconds, both the cost of on and the gain from off would be bigger.
Kill the database
So what does skipping the wait cost? The lab runs a stream of inserts from 8 clients, each recording every insert Postgres acknowledged. After a random 1 to 2.5 seconds it force-stops the database (docker kill -s SIGKILL db, a program kill: the VM and its operating system keep running), restarts it, and looks for every acknowledged row. Five kills with each setting:
| synchronous_commit | Kills | Acknowledged | Acknowledged but lost | Lost per kill |
|---|---|---|---|---|
| on | 5 | 37,803 | 0 | 0, 0, 0, 0, 0 |
| off | 5 | 168,613 | 11,163 | 3,500, 138, 1,650, 3,237, 2,638 |
OK came before the flush. Every kill lost the inserts still in Postgres's own memory, waiting for the background writer.
Each run lasted a random 1–2.5 s and its length wasn't saved, so the bars differ in height and the losses can't be turned into milliseconds of writes. The bars share one scale: the five runs acknowledged 37,803 inserts in all with the setting on, 168,613 with it off.
With it off, every kill lost writes Postgres had said OK to, from 138 up to 3,500: 6.6% of everything acknowledged. But a program kill can't touch the out-tray, so why? Because with this setting off, Postgres says OK while the write is still in its own hand. Even the mild crash loses it. A power cut would also empty the out-tray.
What the setting doesn't do is damage the database. The lost commits are simply missing, as if they had never happened; the data that's left is consistent. That's the difference from turning flushing off for the whole server (Postgres's fsync = off), which can corrupt it.
Choose per write
You don't have to choose for the whole database. The setting can be changed for one transaction:
BEGIN;
SET LOCAL synchronous_commit = off; -- only for this transaction
INSERT INTO page_views (page, at) VALUES ('/pricing', now());
COMMIT; -- OK before the flush
Every other transaction keeps the default and waits for its flush. Page views, metrics, logs: losing the last fraction of a second is fine. Orders and payments: keep it on. Anything you told a customer is saved.
Caveats
- The power cuts are simulated. Cutting a copy of the file only shortens it; a real power cut can also leave a file whose length grew but whose last bytes never arrived, which is what the checksum is for. The lab never cut the laptop's power.
- The store kills used plain fsync. On the Mac that stops at the drive's cache, which a program kill doesn't touch. Nothing in the lab tests what a power cut does to that cache.
- Postgres's flush ran inside Docker's VM. At 83 µs it most likely stops at a cache too. On a server whose disk really flushes,
onwould be slower andoffwould gain more. - One run per cell, on a busy laptop. Each commit rate is one 8-second run. Each kill ran a random 1–2.5 s and the lengths weren't saved, so the losses can't be turned into milliseconds of writes; the lab's notes estimate the 3,500 at about 200 ms, which these results can't check.
- 3.1× with 16 clients isn't all group commit. Overlapping round trips explain part of it; the lab didn't measure how much.
The checklist
- Know what OK means in your stack. When it's said, is the write in the program's memory, the operating system's, a drive cache, or on the disk?
- Say OK only after the write leaves the program. Then a program crash loses nothing, even without a flush.
- Flush before OK if a power cut must not lose the write, and check that the flush reaches the disk (on macOS,
F_FULLFSYNC, notfsync). - Recover by reading from the start and stopping at the first record that's short or fails its checksum; cut the file there.
- Don't flush once per write if you can share it. Group commit and batching several writes per transaction spread one flush over many.
- Skip the wait (
synchronous_commit = off) per transaction, only where losing a moment of writes is fine. - Test it by crashing it. Kill the program mid-write and count acknowledged writes that are gone; that number is what OK means.
Practice: did it survive?
Write the lab's durability arithmetic: which crash empties which place, the store's record format and its recovery scan, the cost of a flush, and how many acknowledged writes a crash lost. The tests use the recorded runs: records byte-for-byte as the lab's store writes them, cuts that keep exactly the complete records, a corrupted byte caught by the checksum, 1.8 against 4,706 µs a write, 3.1× and 1.9× for Postgres, and 11,163 of 168,613 lost.
Quiz
1.A store writes each record to the operating system and then says OK, with no fsync. The program is killed outright (SIGKILL, which it can't catch). What happens to the writes it acknowledged?
2.On a Mac, fsync() on each write ran at 44,644 writes a second and F_FULLFSYNC, macOS's stronger flush, at 212. Why the difference?
3.A store's file is cut at a random byte, leaving half a record at the end. What should recovery do?
4.With synchronous_commit off, one client's commits went from 2,698 to 2,502 a second. Why no gain?
5.Postgres was killed (the program, not the power) with synchronous_commit off, and lost acknowledged inserts every time. How, if a program kill can't touch the operating system's memory?
6.One database holds page-view counts and customer payments. Where would you turn synchronous_commit off?
Check your understanding
Try each question before opening its answer.
What does a database's OK promise?
Only what the code did before saying it. The write can be in the program's own memory, the operating system's memory, the drive's cache or on the disk. Postgres with synchronous_commit on flushes its log before OK; with it off, it says OK while the write is still in its own memory.
Why did the lab's stores lose nothing when killed, even with no flush at all?
Each write went to the operating system (Python's flush()) before the store said OK. A program kill empties only the program's own memory, so the operating system still had every acknowledged write: 0 lost in 260 kills, 60 of them with no fsync. A power cut would have emptied the operating system's memory too.
How does a store recover from half a record at the end of its file?
It reads records from the start and stops at the first one that's incomplete (fewer than 12 bytes left, or its lengths run past the end) or fails its checksum, and cuts the file there. In 200 random cuts the lab's stores kept exactly the complete records every time. The length checks caught all 200; the checksum catches bytes that are present but wrong.
Why do databases avoid one flush per write?
A flush that reaches the disk is very slow. On the Mac, 5,000 small writes ran at 544,415 a second with no flush and 212 a second with F_FULLFSYNC on each, about 2,600× slower. Databases share one flush among many commits (group commit) or batch writes into one transaction.
Turning synchronous_commit off did nothing for one client but almost doubled 16. Why?
It can save at most the flush. One client spends most of each 371 µs commit on the trip to the database and back; the flush inside Docker's VM was about 83 µs. With 16 clients, commits waiting for flushes were holding throughput back: 8,332 a second on, 15,820 off.
Postgres lost acknowledged writes in a program kill with synchronous_commit off. Wouldn't the operating system have them?
Not yet. With the setting off, Postgres says OK before the write leaves its own memory; a background writer flushes it a moment later (usually within 200 ms). Five kills lost 11,163 of 168,613 acknowledged inserts, some in every kill. With the setting on: 0 of 37,803.
Where would you use synchronous_commit = off?
Per transaction (SET LOCAL synchronous_commit = off), for writes you can lose the last fraction of a second of: page views, metrics, logs. Not for orders, payments or anything you told a customer was saved. A crash with it off loses recent commits but doesn't corrupt the database.
Next up: Chapter 8, race conditions and lost updates: so far one writer changed each row. The next chapter has two writers change the same row at once, and every transfer says OK while the balances drift.