ealeng

Episode 07 of 55 · Storage

Did the write survive? Crashes, fsync and synchronous_commit

Postgres was force-stopped mid-write five times with one setting and five times with another. With synchronous_commit on, every write it had said OK to was still there; with it off, 11,163 were gone. What a database's OK really promises: where a write can be when OK is said, a program crash against a power cut, how a store recovers from half a record, what a real flush costs (544,415 against 212 writes a second), and when skipping the wait is fine.

Lab 04 · Storage Engines and Indexes14 min read
Video transcript9:29

0:00Cold open

0:01

I killed my database in the middle of writing. Five times with one setting, five times with another.

0:09

With the first, every write it had said OK to was still there.

0:14

With the second, eleven thousand of them were gone. The database had said OK to every one.

0:22

Same database. One setting. Which one are you running?

0:28Intro

0:30

Hands-on system design, part seven.

0:33

Today: when a database says OK, is your write really saved?

0:38Meet Lucía

0:40

I’m Lucía, a platform engineer. When my service saves an order, the database answers OK, and I tell the customer it’s saved.

0:49

But is the order on the disk yet?

0:52

If the machine crashes a moment after that OK, is the order still there?

0:5901 · What you need

1:01

To run it yourself: Python with a few packages, and Docker for a Postgres database we’ll kill on purpose.

1:09

The tests crash a small store we built, and check what it recovers.

1:14

No cloud, and no API keys.

1:1902 · A filing office

1:21

Think of a filing office. A clerk takes your form. It’s in the clerk’s hand: that’s the program’s own memory.

1:29

Then the form goes into the out-tray: the operating system’s memory. That’s fast.

1:36

And the clerk says, got it. That’s the database’s OK. It’s called an acknowledgement.

1:42

Only later does it reach the fireproof cabinet: the disk. That’s a slow walk.

1:49

Making that walk right now, and waiting until the form is in the cabinet, is called a flush. Its system call is named fsync. On some machines it stops at a tray by the cabinet’s door. More on that later.

2:0403 · Two kinds of crash

2:06

Now, two kinds of crash. First, the program is killed: the clerk faints. Whatever was in the hand is lost. But the out-tray and the cabinet are fine.

2:17

Second, a power cut: the building goes dark. The hand and the out-tray are both lost. Only the cabinet survives.

2:26

So a flush protects you from power cuts. A program crash can’t touch the out-tray.

2:3404 · The flush, in code

2:35

To test this, we built a small store. Here’s how it saves one record.

2:41

Write it into the program’s own buffer. That’s the hand.

2:46

Hand it to the operating system. Python calls this flush, but it only reaches the out-tray.

2:53

And only if flushing is switched on: fsync, asking for the walk to the cabinet. Then it says got it.

3:0205 · Killed 260 times

3:04

I built two small stores like this, A and B. I killed the writing program at random moments, a hundred times each, with a flush on every write. Then I looked for every write it had acknowledged. None was lost.

3:18

Then sixty more kills, with no flush at all. What do you think was lost?

3:26

Nothing. Not one acknowledged write.

3:30

Each write was already in the out-tray before the store said got it. Killing the program never touches the out-tray.

3:4006 · A power cut, mid-write

3:41

A power cut is worse. It can stop a write halfway, and leave half a record on the disk.

3:48

I can’t cut my laptop’s power hundreds of times. So I simulated it: copy a store’s file, and cut it at a random byte. A hundred cuts in each of the two stores.

4:00

When the store opens again, it reads records from the start, and stops at the first one that’s incomplete.

4:08

Two hundred cuts in all. Every time, it kept every complete record, and dropped only the half one.

4:1707 · Spotting half a record

4:18

Here’s how it spots half a record.

4:22

Every record starts with a checksum: a number computed from the rest of the record.

4:28

On reading, a record that runs past the end of the file is cut off. That check caught all two hundred cuts.

4:37

The checksum is for a different failure: garbage in the middle. A test corrupts one byte, and the reader stops right there.

4:4608 · The price of the walk

4:48

So why not flush every write? Here’s the price, on this Mac: five thousand small writes, timed three ways.

4:55

Left in the out-tray: five hundred forty-four thousand writes a second. Under two millionths of a second each.

5:04

With fsync on each one: forty-four thousand a second.

5:10

But on a Mac, fsync only reaches a tray at the cabinet’s door: the drive’s own cache. A power cut can still lose it.

5:19

The Mac has a stronger flush that puts the form inside the cabinet. With that on each write: two hundred and twelve a second. Almost five thousandths of a second each.

5:31

That’s about two thousand six hundred times slower. So databases avoid one walk per write.

5:4009 · One walk, many forms

5:41

Now Postgres. In Postgres, the OK is called a commit. By default, it flushes before every commit.

5:49

Postgres runs inside Docker’s Linux machine, and its flush is a different one. Measured on this laptop, it takes about eighty millionths of a second. It most likely stops at a cache, like plain fsync.

6:04

One client, one insert per commit: about two thousand seven hundred commits a second.

6:11

Sixteen clients at once: eight thousand three hundred. Three times as many, and every one still flushed before its OK.

6:21

Part of that is sixteen clients overlapping their trips to the database. Part is group commit: while one walk is under way, more forms pile up, and the next walk carries them all.

6:3510 · OK before the walk

6:36

Postgres has a setting to skip the wait. It’s called synchronous commit. Normally it’s on: write, flush, then OK.

6:45

Turned off, Postgres says OK first. A background writer does the walk a moment later, usually within a fifth of a second: two hundred milliseconds, the default. Until then, the form can still be in Postgres’s own hand.

7:01

With sixteen clients, that almost doubled the commits per second.

7:07

With one client, it made no difference: about two thousand seven hundred on, two thousand five hundred off. Most of its time is the trip to the database and back. The eighty-microsecond flush is a small part.

7:2211 · Kill the database

7:24

So what does skipping the wait cost? A stream of inserts from eight clients. Then I force-stop the database at a random moment, restart it, and look for every row it said OK to.

7:37

Five kills with the setting on. Lost: zero.

7:42

Five kills with it off. What do you think?

7:48

Every kill lost writes it had said OK to. From a hundred and thirty-eight, up to three thousand five hundred. Eleven thousand, one hundred sixty-three in all.

7:59

But a program kill can’t touch the out-tray. So why? Because with this setting off, Postgres says OK while the form is still in its own hand. So even a program kill loses it.

8:12

And this was the mild crash. A power cut would also empty the out-tray.

8:1912 · Choose per write

8:21

You don’t have to choose for the whole database. You can turn it off for one transaction: one group of writes saved together.

8:30

Page views, metrics, logs: losing the last fraction of a second is fine.

8:36

Orders and payments: keep it on. Anything you told a customer is saved.

8:43Back to Lucía

8:45

So, three rules.

8:48

Know what OK means: is your write in the hand, the out-tray, or the cabinet?

8:54

Say OK only after the write leaves your hand. Then a program crash loses nothing. The walk to the cabinet is for power cuts, and it’s expensive.

9:05

And skip the wait only where losing a moment of writes is fine.

9:11

Next time: two writers change the same row at once.

9:16

For today: ask where your write is when the database says OK.Lucía: Where is my write when it says OK?

9:21Summary

9:22

What OK means, two kinds of crash, and where to skip the wait.

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.

Try it · The filing officeWhere the write is when OK is said · recorded where the lab tested it

Who says OK, and when

Then

Step 1
The clerk's hand
the program's own memory
✕ emptied
Step 2
The out-tray
the operating system's memory
OK said here
Step 3
Tray at the cabinet's door
the drive's own cache
kept
Step 4
The cabinet
the disk itself (flash)
kept

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.

This acknowledged write
survives
The program is killed. The clerk faints: whatever is in the hand is gone.

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:

Try it · Cut the fileLab 04 · kvstore/records.py · the first 6 records of store A's log
123456cut · byte 200
kept where the scan stops (cut off) lost with the powereach record: 12-byte header (checksum, key length, value length), then key and value · 56 bytes
Records kept
3 of 6
Bytes cut off
32

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.

Try it · The price of the walkLab 04 · 01_kvstore.py Exercise 3 · 5,000 writes of 50 B
1001,00010,000100,0001,000,000

Writes a second, log scale: each step is ten times more.

Time per write
4,706 µs
Slower than no flush
2,562×

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
Try it · Kill the databaseLab 04 · 04_durability.py Exercise 2 · 8 clients, SIGKILL after 1–2.5 s
29,750kill 1lost 3,50033,546kill 2lost 13822,434kill 3lost 1,65040,034kill 4lost 3,23742,849kill 5lost 2,638
inserts acknowledged before the kill acknowledged, then gone after the restart
Acknowledged
168,613
Acknowledged but lost
11,163
Share lost
6.6%

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, on would be slower and off would 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

  1. 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?
  2. Say OK only after the write leaves the program. Then a program crash loses nothing, even without a flush.
  3. Flush before OK if a power cut must not lose the write, and check that the flush reaches the disk (on macOS, F_FULLFSYNC, not fsync).
  4. Recover by reading from the start and stopping at the first record that's short or fails its checksum; cut the file there.
  5. Don't flush once per write if you can share it. Group commit and batching several writes per transaction spread one flush over many.
  6. Skip the wait (synchronous_commit = off) per transaction, only where losing a moment of writes is fine.
  7. 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.

Try it · Practice in PythonRuns in your browser · ⌘/Ctrl + Enter to run
durability_practice.py78 lines

Quiz

Try it · Check your understanding0 of 6 answered
  1. 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. 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. 3.A store's file is cut at a random byte, leaving half a record at the end. What should recovery do?

  4. 4.With synchronous_commit off, one client's commits went from 2,698 to 2,502 a second. Why no gain?

  5. 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. 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.

Learning something useful?

New labs, articles, and videos on evaluating and testing AI systems come out regularly. Follow along so you don't miss the next one.