A 1.5 GiB file copy finished in 2.6 seconds on a VM whose disk sustains roughly 370 MiB/s. That is not a disk that briefly got faster. dd measured how fast the kernel accepted bytes, not how fast they reached the platter.

That gap is the page cache, and it is one of the most useful lies in Linux. It is also where "the database said committed" turns into "the last 30 seconds of writes are gone" after a power cut.

This is a practical tour of dirty page writeback: what the six vm.dirty_* knobs mean, why the real limit is smaller than the percentage suggests, and how to measure the delay instead of guessing. All live numbers below come from a Debian 13 VM (kernel 6.12.117, ext4 on /dev/vda1, 8,134,240 kB RAM, no swap).

What write() actually promises

write(2) copies bytes into the page cache and returns the number of bytes copied. The man page is unusually blunt about it:

A successful return from write() does not make any guarantee that data has been committed to disk. On some filesystems, including NFS, it does not even guarantee that space has successfully been reserved for the data. In this case, some errors might be delayed until a future write(), fsync(2), or even close(2). The only way to be sure is to call fsync(2) after you are done writing all your data.

-- write(2), NOTES

A page that has been modified in cache but not yet written out is dirty. The kernel owns it from that point: if your process crashes, the data survives and will still be written back. If the machine crashes or loses power before writeback, the data does not.

That distinction matters. "The process died and the file is intact" is page cache working. "The host lost power and the file is truncated" is the same page cache, one layer lower, with no fsync.

The six knobs, and the two pairs

Check your own defaults first:

$ sysctl vm.dirty_ratio vm.dirty_background_ratio \ vm.dirty_expire_centisecs vm.dirty_writeback_centisecs \ vm.dirty_bytes vm.dirty_background_bytes vm.dirty_ratio = 20 vm.dirty_background_ratio = 10 vm.dirty_expire_centisecs = 3000 vm.dirty_writeback_centisecs = 500 vm.dirty_bytes = 0 vm.dirty_background_bytes = 0 
Knob Default here What it controls
vm.dirty_background_ratio 10 Dirty memory (%) at which flusher threads start writeback in the background
vm.dirty_ratio 20 Dirty memory (%) at which the process doing the writing is throttled
vm.dirty_background_bytes 0 Same as above, as an absolute byte count
vm.dirty_bytes 0 Same as above, as an absolute byte count
vm.dirty_expire_centisecs 3000 Age (in 1/100 s) after which a dirty page is eligible for writeback
vm.dirty_writeback_centisecs 500 How often (in 1/100 s) flusher threads wake up

Two traps are baked into these files.

Ratios and bytes are mutually exclusive. The kernel documentation says it plainly: writing one of them immediately makes the other read as 0. If you set vm.dirty_bytes = 536870912, your dirty_ratio becomes 0 and stays 0 until you write it again. Setting a ratio later zeroes the byte value in the same way. Pick one pair and persist only that pair.

Ratio is not a percentage of RAM. The documentation says:

Contains, as a percentage of total available memory that contains free pages and reclaimable pages, the number of pages at which the background kernel flusher threads will start writing out dirty data. The total available memory is not equal to total system memory.

-- Documentation/admin-guide/sysctl/vm.rst

In kernel 6.12 the dirtyable base is computed in mm/page-writeback.c as free pages minus the kernel reserve, plus NR_INACTIVE_FILE and NR_ACTIVE_FILE:

static unsigned long global_dirtyable_memory(void) { unsigned long x; x = global_zone_page_state(NR_FREE_PAGES); x -= min(x, totalreserve_pages); x += global_node_page_state(NR_INACTIVE_FILE); x += global_node_page_state(NR_ACTIVE_FILE); ... return x + 1; } 

So the denominator is roughly "free memory plus page cache", not the number printed by free -h. On a host where most RAM is anonymous memory, the dirty limit can be a small fraction of what the percentage implies.

Read the thresholds the kernel actually computed

You do not have to do that arithmetic. The kernel exports the results in /proc/vmstat, in 4 KiB pages:

$ grep -E 'nr_dirty|nr_writeback|nr_dirty_threshold|nr_dirty_background_threshold' /proc/vmstat nr_dirty 192 nr_writeback 0 nr_dirty_threshold 219672 nr_dirty_background_threshold 109702 $ awk '/^MemTotal:/{print $2" kB"}' /proc/meminfo 8134240 kB 

Convert pages to MiB by multiplying by 4 and dividing by 1024:

  • background threshold: 109,702 pages = 428 MiB
  • dirty threshold: 219,672 pages = 858 MiB

Twenty percent of 8,134,240 kB would be 1.55 GiB. The real threshold was 858 MiB, because the dirtyable base at that moment was about 4.29 GiB, not 7.76 GiB. This is the number that matters, and it moves as the page cache and free memory change.

A measured lab: 1.5 GiB that was not on disk yet

Create a 1.5 GiB file, time the write, then immediately look at Dirty and time a sync:

cd /var/tmp rm -f wb-proof start=$(date +%s%N) dd if=/dev/zero of=wb-proof bs=1M count=1536 status=none end=$(date +%s%N) echo "dd_ms=$(( (end - start) / 1000000 ))" grep -E '^(Dirty|Writeback):' /proc/meminfo start=$(date +%s%N) sync end=$(date +%s%N) echo "sync_ms=$(( (end - start) / 1000000 ))" rm -f wb-proof 

Result on this host:

dd_ms=2608 Dirty: 516104 kB Writeback: 147456 kB sync_ms=1639 

Read that carefully. dd returned after 2.6 seconds with the write "complete", while 504 MiB was still dirty and 144 MiB was actively in flight. Making the data durable took another 1.6 seconds. End to end, 1.5 GiB at 362 MiB/s, not the 590 MiB/s that dd reported.

A second run at 2 GiB peaked at 651,968 kB of Dirty (637 MiB) during the write. It stayed under the 858 MiB threshold, so nothing throttled and the copy looked uniformly fast. Had it crossed the threshold, the write would not have failed: the calling process would have been put to sleep inside balance_dirty_pages() until writeback caught up.

For contrast, forcing durability per file and bypassing the cache:

# buffered write + one flush at the end of this file $ dd if=/dev/zero of=/var/tmp/wb-sync bs=1M count=512 conv=fdatasync status=none # 1.557 s -> ~330 MiB/s # bypass the page cache (alignment is handled by dd here) $ dd if=/dev/zero of=/var/tmp/wb-direct bs=1M count=512 oflag=direct status=none # 1.374 s -> ~374 MiB/s 

conv=fdatasync includes the flush, which is why it is slower than the buffered write. oflag=direct skips the page cache, but O_DIRECT is not a durability guarantee either: it still does not flush a volatile device cache. If you need the data to survive power loss, you still call fsync().

Where the remaining delay comes from

Three independent timers decide when a dirty page leaves memory.

  1. The background threshold. Cross it and flusher threads start writing immediately, regardless of page age.
  2. The dirty threshold. Cross it and the writing process is throttled until the backlog shrinks.
  3. Expiry and wakeup. Below the thresholds, a page waits. dirty_expire_centisecs=3000 makes it eligible after 30 seconds; dirty_writeback_centisecs=500 means the flusher only checks every 5 seconds. A page can therefore sit dirty for roughly 30 to 35 seconds with no threshold pressure at all.

That is the normal, healthy case. It is also why an idle machine can lose the last half-minute of un-fsynced writes in a power failure, even though no limit was hit.

Filesystem journaling adds its own layer. The ext4 documentation for commit= (default 5 seconds) is explicit about the interaction:

This setting limits the maximum age of the running transaction to 'nrsec' seconds. The default value is 5 seconds. This means that if you lose your power, you will lose as much as the latest 5 seconds of metadata changes (your filesystem will not be damaged though, thanks to the journaling). ... Note that due to delayed allocation even older data can be lost on power failure since writeback of those data begins only after time set in /proc/sys/vm/dirty_expire_centisecs.

-- Documentation/admin-guide/ext4.rst

So "ext4 is journaled" is not "my file write is durable". Journaling protects filesystem consistency; it does not promise your data bytes are on media.

fsync is the contract, including its fine print

fsync(fd) flushes the file's data and metadata and blocks until the device reports completion. The man page adds two details people miss:

  • It flushes "a disk cache if present". On a device with a volatile write cache, the filesystem issues the flush; whether the drive honors it is a hardware property.
  • It does not guarantee the directory entry is durable. After creating or renaming a file, you need fsync() on the directory too.

A complete atomic-write pattern in Python:

import os tmp = "/var/tmp/config.json.tmp" dst = "/var/tmp/config.json" with open(tmp, "wb") as f: f.write(b'{"generation": 42}\n') f.flush() # push the buffer into the kernel os.fsync(f.fileno()) # data + inode metadata to disk os.replace(tmp, dst) # atomic rename within one filesystem dfd = os.open("/var/tmp", os.O_DIRECTORY) try: os.fsync(dfd) # make the rename itself durable finally: os.close(dfd) 

Check the return value everywhere. Since Linux 4.13, writeback errors are reported to all file descriptors that could have dirtied the data, and they can surface at fsync() as EIO. An application that ignores that return value has a silent data-loss path.

sync() is the system-wide hammer. Linux waits for I/O completions, so it provides the same guarantee as fsync() on every file. syncfs(fd) does the same for one filesystem and, since Linux 5.8, reports errors if inodes failed to write back. Neither is a substitute for a per-transaction fsync if you care about commit latency and error attribution.

Tuning that helps, and tuning that just moves the pain

Start from measurements, not folklore. You need three numbers: the computed thresholds, sustainable write throughput, and your application's p99 fsync latency. If the p99 is fine and Dirty never approaches the threshold, change nothing.

When writeback bursts are hurting latency, lower the background threshold first. That starts cleaning earlier, before the hard threshold throttles writers:

# /etc/sysctl.d/99-writeback.conf # Absolute values: setting these zeroes the corresponding ratios. vm.dirty_background_bytes = 134217728 vm.dirty_bytes = 536870912 vm.dirty_expire_centisecs = 1500 vm.dirty_writeback_centisecs = 500 

Apply and verify:

sudo sysctl --system sysctl vm.dirty_background_bytes vm.dirty_bytes \ vm.dirty_expire_centisecs vm.dirty_writeback_centisecs 

systemd-sysctl.service reads /etc/sysctl.d/*.conf early in boot, with /etc taking precedence over /run, /usr/local/lib and /usr/lib. Files are applied in lexicographic order, and the last assignment wins. Name the file so it sorts after the distribution defaults, as above.

Notes from experience:

  • 128 MiB / 512 MiB is a starting point, not a rule. On this 8 GB host with a ~370 MiB/s disk, 512 MiB is about 1.4 seconds of writes. On a 15k SAS array or a slow USB disk, it is far too much.
  • Do not set dirty_bytes very low and expect better throughput. Writeback becomes nearly synchronous, and a workload that was previously batched now pays the disk latency on every burst.
  • Keep background below the hard limit. If the background threshold is at or above the dirty threshold, there is no early warning window left; you go straight to throttling.
  • These knobs are host-wide. cgroup v2 gives you memory.stat counters such as file_dirty and file_writeback, but no per-cgroup dirty ratio. A container sees and is affected by the host's writeback policy.
  • Do not disable periodic writeback. dirty_writeback_centisecs=0 turns off the periodic flusher wakeups. It does not make writes faster; it makes the timing less predictable.

The database angle

If PostgreSQL is on the host, the vm.dirty_* knobs are not the durability control. fsync=on and synchronous_commit=on are. The documentation describes the commit path directly:

Specifies how much WAL processing must complete before the database server returns a "success" indication to the client. ... The local behavior of all non-off modes is to wait for local flush of WAL to disk.

-- PostgreSQL documentation, runtime-config-wal

On Linux the default wal_sync_method is fdatasync. Every committed transaction therefore pays a flush, unless you deliberately set synchronous_commit=off and accept losing recent transactions after a crash (the documented maximum delay is three times wal_writer_delay).

What dirty tuning can do is smooth the background writeback so a checkpoint or a bulk load does not fill the dirty buffer and stall unrelated commits. What it cannot do is make fsync() faster than the device. If commit latency is the problem, measure the device flush latency before touching a sysctl.

A five-minute diagnostic sequence

# 1. Current dirty state and the kernel's real limits (pages -> MiB: *4/1024) grep -E '^(Dirty|Writeback):' /proc/meminfo grep -E 'nr_dirty|nr_writeback|nr_dirty_threshold|nr_dirty_background_threshold' /proc/vmstat # 2. Which knobs are in force (remember: one of each pair is 0) sysctl vm.dirty_ratio vm.dirty_background_ratio vm.dirty_bytes \ vm.dirty_background_bytes vm.dirty_expire_centisecs \ vm.dirty_writeback_centisecs # 3. Per-cgroup attribution (use your service's cgroup path) grep -E 'file_dirty|file_writeback' \ /sys/fs/cgroup/system.slice/myapp.service/memory.stat # 4. Is the disk the bottleneck, or the timer? iostat -xz 1 5 

How to read it:

  • Dirty climbing toward nr_dirty_threshold, high await, disk busy: the device cannot keep up. Lower the background threshold or add throughput; raising dirty_ratio only builds a larger cliff.
  • Dirty high, disk mostly idle: you are waiting on expiry or the 5-second flusher wakeup. Lower dirty_expire_centisecs if that latency matters.
  • Writeback nonzero but not draining: look at the device and transport, not the VM tunables.
  • file_dirty concentrated in one cgroup: that workload is creating the burst. Fix it at the source or move it to its own disk.

What to remember

  • write() success means "in page cache", not "on disk".
  • The dirty limit is a percentage of free memory plus page cache, not of RAM. Read nr_dirty_threshold instead of calculating it.
  • Background threshold starts writeback; hard threshold throttles the writer. Neither returns an error.
  • Below both thresholds, a page can wait 30 to 35 seconds. Journaling does not shorten that.
  • fsync() is the durability contract, including the directory fsync after a rename, and its return value must be checked.
  • Tune from measured thresholds and p99 fsync latency. Lowering the background threshold buys smoother latency; raising the hard threshold only buys a bigger backlog.

The 2.6-second dd was not wrong. It answered a different question than the one most of us are asking.

Sources