Storage and file systems: the page cache, fsync, journaling, and checkpoints

What happens between torch.save returning and your checkpoint surviving a crash, and between read() and the bytes arriving: devices, the VFS, the page cache, writeback, fsync, journaling, direct I/O, network file systems and checkpoint files. Measured on a Linux 5.10 VM, kernel source quoted with line numbers. A child page of Topic: operating-systems. Data as of October 2026. Reading: 43 min, plus 19 in closed details.

The idea in one screen

Returned is not durable. write() and torch.save return once the bytes are in kernel memory, the page cache; the kernel moves them to the device later, in its own order and on its own schedule. What a crash can leave is decided only by fsync (of the file, and of its directory) and rename; what a read costs is decided by whether the page cache and readahead can serve it.

  1. write() returns at the page cache: 1.4 us. The 4 KiB is copied into a cached page, which is marked dirty. The device has received nothing.
  2. sync_file_range returns when the device acknowledges: 161 us. The page went through the block layer to the drive, which acknowledges from its volatile cache. No metadata, no cache flush.
  3. fdatasync pushes the data to stable media: 393 us. A cache flush gets it past the device cache. An overwrite changes neither the size nor the block map, so there is no journal commit; the new modification time stays in memory.
  4. fsync also commits the metadata: 1,305 us. The inode's change (the new time) goes through a journal commit as well, a second ordered write and flush (section 5).
  5. Power cut: only what is below the red line survives. The bytes of write and sync_file_range are lost although both calls returned; fdatasync keeps the data and loses only the time stamp; fsync keeps everything.

Fig. 1: the layers your bytes cross, top to bottom (the page cache is sections 3 and 4, the block layer and the device cache section 1, the media section 5); orange is the data, purple the file's metadata change. Medians of 1,000 overwrites of one 4 KiB record on ext4 measured; fsync needs a journal commit, fdatasync on an overwrite does not (section 5).

CallWhen it returns, what is guaranteedCost here measured
write()the bytes are in the page cache; other processes can read them; nothing is on the device1.4 us
fsync(fd)the file's data and its metadata (size, block map, times) are on stable storage, device cache flushed1,305 us
fdatasync(fd)the data, plus only the metadata needed to read it back (size, block map); not the times393 us
sync_file_range()the pages were sent to the device; no metadata, no device cache flush: not durable161 us
rename(tmp, final)atomic for every reader now; durable only after the next journal commit or an fsync of the directorypart of the protocol (section 6)
fsync(dir_fd)the directory's entries (names created, renamed, removed) are durable2.3 ms (after a rename)

Medians of 1,000 overwrites of one 4 KiB record of a preallocated file on ext4 (section 5 has appends and the 99th percentiles); the directory fsync is from the 256 MiB checkpoint runs of section 10.

You need: file descriptors and system calls (Processes and the system-call API, section 7) and the page cache as memory that is reclaimed and counted against containers (Virtual memory). The root Topic: operating-systems section 7 gives the intuition (returned is not durable, and the four-step safe checkpoint); this page is the mechanism, measured.

Page cache
kernel memory holding file pages; every buffered read and write goes through it.
Dirty page
a cached page changed in memory and not yet written to the device.
Writeback
the kernel writing dirty pages to the device, by age, by threshold, or because someone called fsync.
Device cache, FLUSH, FUA
the drive's own volatile memory; a flush or a Force Unit Access write is what pushes data past it.
Inode, extent
the per-file record (size, owner, where the data lives); an extent is one "start, length" run of blocks.
Journal (jbd2)
ext4's log: metadata changes are written there first and committed as transactions, so a crash replays or discards them whole.
Readahead
the kernel fetching the next pages of a file before a sequential reader asks.
O_DIRECT
an open flag that moves data between your buffer and the device without the page cache.
The page in six claims
  1. Returned is not durable. The 256 MiB checkpoint of section 10 left 256 MiB of dirty data in memory when torch.save returned (section 4).
  2. When the kernel writes is not a promise. The textbook says "within 30 seconds"; here the same 16 MiB stayed dirty anywhere from 0.4 to 30 seconds after the write, depending on what else the machine was doing (section 4).
  3. The safe checkpoint is five calls: write to ckpt.pt.tmp, fsync it, rename it over ckpt.pt, fsync the directory; and never overwrite the last good checkpoint in place. It cost 365 ms against 263 ms for the plain save (section 6).
  4. Libraries differ. PyTorch's distributed checkpoint fsyncs every file but deletes the old .metadata before renaming the new one in, and never fsyncs the directory: save each step to a new directory (section 10).
  5. Sequential beats random, because the kernel reads ahead: 512 small reads of a cold file became 20 device requests (section 3). Shards, not millions of small files.
  6. If fsync fails, the data is gone: the kernel may already have dropped the dirty pages. Rewrite the checkpoint from memory; never retry the fsync and carry on (section 5).
How this page was measured (provenance)

Docker Desktop's Linux VM on an Apple M1 laptop (Linux 5.10.104-linuxkit, arm64, 5 CPUs, about 10 GB), October 2026, image kb-os-lab:1 (the root's lab image: fio 3.33, strace 6.1, e2fsprogs 1.47, PyTorch 2.14.1 CPU). Files were written to /data, an anonymous Docker volume: a directory on the VM's ext4 disk (data=ordered, commit=5, delayed allocation), with no overlay file system in between. Containers were not privileged. The disk is virtual: a virtio block device backed by a file on the laptop's SSD, which macOS caches, so device reads and flushes here are faster than on a real NVMe drive and cold reads are inflated; the ratios between methods carry over, the absolute numbers do not. Things that need privileges, a real crash, NVMe hardware, a network file system or a GPU are taught from primary sources and tagged not run here. Labels: measured ran here; source read from kernel source or documentation. Kernel source is quoted at v5.10 with line numbers. Scripts and raw outputs: src/exp/ and src/raw/ in the repository.

OSTEP chapter map for this page (reference)
OSTEP chapterHereWhat this page adds
36 I/O Devices; 37 Hard Disk Drives; 44 Flash-based SSDs1NVMe queues and doorbells, blk-mq, schedulers, queue depth measured; device write caches, FLUSH and FUA
39 Files and Directories2, 5, 6the VFS objects, fsync family semantics, rename and directory fsync
40 File System Implementation; 41 Locality and FFS2, 3a real ext4 inode and extent tree, block groups, readahead's window measured
42 Crash Consistency: FSCK and Journaling; 43 Log-structured File Systems6, 7jbd2, ext4's data modes, delayed allocation, application-level crash states; copy-on-write file systems in brief
45 Data Integrity and Protection5fsync error reporting (errseq_t), fsyncgate
49 Sun's Network File System9close-to-open in Linux's NFS client; object stores and FUSE mounts

OSTEP is free at pages.cs.wisc.edu/~remzi/OSTEP. Read 39, 40 and 42 alongside sections 2, 5 to 7 here.

1. Devices and the block layer: what is at the bottom

A storage device keeps data without power, but it is thousands of times slower than memory, works in blocks rather than bytes, and usually has its own volatile cache. Everything above it exists to hide those three facts; every durability bug forgets one of them.

Latency is not one number: it depends on how many requests are in flight

A device serves many requests in parallel, so more in flight buys throughput until it saturates; after that, each extra request only waits longer. A DataLoader that reads one sample at a time from one thread runs at QD 1, the top bar. More workers, prefetching or asynchronous I/O move it down the chart.

At queue depth 64, fio measured about 54,700 reads per second at a mean latency near 1.15 ms. What throughput does Little's law predict for 64 requests in flight at 1.15 ms each?
4 KiB random reads at four queue depths measured

fio, O_DIRECT (no page cache, section 8) on a 1 GiB file, 5 s per point. Queue depth (QD) is how many requests are in flight at once.

QD 1 to 64: throughput x5.1, mean latency x14.4. Little's law (requests in flight = throughput x latency) at QD 64: 64 / 1,152.6 us = 55,527 per second, against 54,723 measured (+1.5%). The virtual disk reports itself as rotational: 1, which it is not; read the shape, not the absolute numbers.

How a request reaches the device: per-CPU queues all the way down

A file system describes an I/O as a bio (direction, starting sector, list of memory pages); bios that touch neighbouring sectors merge into a request. Since Linux 3.13 the block layer is blk-mq: each CPU puts requests in its own software queue, which feeds one of the device's hardware queues (kernel docs: blk-mq). On NVMe, the interface modern SSDs speak over PCIe, each hardware queue is a submission and completion queue pair in host memory: the driver writes a command and rings a doorbell register; the drive fetches it by DMA, does the work, posts a completion and raises an interrupt. The specification allows up to 65,535 I/O queue pairs of up to 65,536 entries each (NVM Express base specification).

Each CPU has its own path to the drive, so no shared lock

This VM's disk as the kernel reports it: 5 CPUs, scheduler none, 5 hardware queues (one per CPU), up to 256 requests per queue, at most 1,280 KiB per request measured. The NVMe part is from the specification not run here (this disk is virtio).

Why an SSD writes more than you asked: remapping and garbage collection

Two erase blocks of four pages each illustrative; real blocks hold hundreds of pages. Mechanism and typical times from OSTEP ch. 44.

Inside a flash drive: every overwrite goes to a fresh page

Flash is read and written in pages of a few KiB but erased only in much larger erase blocks, and a page cannot be rewritten before its block is erased. The flash translation layer (FTL) inside the drive therefore writes every update to a fresh page, remaps it, and garbage-collects old blocks in the background; the extra internal writes are write amplification. Typical times for SLC flash: read about 25 us, program (write) 200 to 300 us, erase 1.5 to 2 ms (OSTEP ch. 44).

  1. A new drive: every page is erased. Two erase blocks of four pages. A page can be programmed (written) once after its block is erased.
  2. Write A, B and C. The FTL places them in free pages of block 0 and records logical page to physical page in its map.
  3. Overwrite A: it goes to a fresh page. Flash cannot rewrite page 0 in place, so the new A goes to page 3, the map now points there, and the old copy is marked invalid. One host write, one flash write.
  4. Overwrite B: block 0 is full, so block 1. Block 0 now holds two dead pages that cannot be reused until the whole block is erased.
  5. Garbage collection copies the live pages out. To free block 0 the FTL copies its valid pages (C and A′) to block 1: two flash writes the host never asked for. This is write amplification.
  6. Erase block 0. An erase takes 1.5 to 2 ms against 200 to 300 us to program a page (SLC, OSTEP ch. 44). A discard (TRIM) of dead data would have spared the copies. Write amplification here: 7 flash writes / 5 host writes = 1.4.

The device's cache. Most drives acknowledge a write once it is in their internal DRAM. If power fails before it reaches flash or platter, the write is lost although the drive said "done". The kernel has two tools for this (kernel docs: writeback cache control): a cache flush (REQ_PREFLUSH: "flush the volatile cache before this I/O") and FUA, Force Unit Access (REQ_FUA: "this write completes only once it is on stable storage"). A file system's fsync ends with one of them: that, not the write, is the red line in the hero figure.

Disks, schedulers, TRIM on this VM, and the commands that show the block layer (depth)

Hard disks. A spinning platter and a moving arm: a random read waits for the arm to move (seek) and the platter to turn (rotation), several milliseconds, so a few hundred random reads per second; sequential reads are fast because nothing moves. OSTEP ch. 37 works the numbers.

Plugging and schedulers. A thread may plug its queue while it submits a batch, so the batch is merged before it is sent. An optional I/O scheduler may reorder requests: none, mq-deadline (bounds how long a request waits), kyber (latency targets) or bfq (fair shares between processes). For fast NVMe drives none is the usual choice because reordering costs more than it saves.

TRIM. A discard (TRIM on SATA, Deallocate on NVMe) tells the drive which blocks a deleted file freed, so its garbage collector stops copying dead data. ext4 can send discards at every delete (mount option discard) or you run fstrim periodically. This VM mounts its disk nodiscard and runs a small service that calls /sbin/fstrim /var/lib/docker after deletes (seen in the VM's process list with docker run --pid host ... ps) measured.

This disk reports a write-back cache and no FUA support, so the kernel emulates FUA with a write followed by a full flush. A drive that wrongly reports write through, or firmware that ignores flushes, silently breaks every guarantee on this page; only power-cut tests can find that. What the kernel believes about this disk:


Commands that show it
  • lsblk -o NAME,SIZE,ROTA,SCHED,MOUNTPOINT and cat /sys/block/nvme0n1/queue/{scheduler,nr_requests,max_sectors_kb,read_ahead_kb,write_cache}
  • iostat -x 1: per device, r/s w/s (requests per second), rkB/s, r_await (average ms per read, queueing included), aqu-sz (average queue depth), %util (time with at least one request in flight; near 100% does not mean saturated on a device that serves many requests in parallel)
  • cat /proc/diskstats: the raw counters behind iostat; in a cgroup v2 container, cat /sys/fs/cgroup/io.stat gives your container's own rbytes wbytes rios wios (used for every device count on this page)
  • cat /sys/fs/cgroup/io.max: a bandwidth or IOPS limit; the root's Debug lab case "Slow storage: workers sleep in D state on page faults" (Debug lab) throttles reads to 1 MiB/s this way

Reading the counters. You seldom tune the block layer, but you read it. "The disk is at 100% util" on iostat while r/s keeps rising with more workers means the device still has room; a large r_await with a small aqu-sz means each request is slow (a remote or throttled device), not that you are queueing.

2. Files, names and inodes: the VFS and ext4's layout

Programs want named files with sizes, owners and times, and they want the same open, read, write to work on ext4, XFS, tmpfs, NFS or /proc. The VFS (virtual file system switch) gives every file system one set of objects and calls to implement (kernel docs: VFS). Below, mke2fs built a 64 MiB ext4 file system inside an ordinary file and debugfs (which reads the image directly, so no mount and no privileges) copied in a 3,000,000-byte "checkpoint" and a small file with two names measured. The figure is that real image seen through the kernel's objects.

Four objects. The superblock, one per mounted file system: its type, block size, and the operations on its inodes (struct super_block, fs.h line 1416). The inode, one per file whatever its names: type, permissions, owner, size, times, link count, where its data lives, and an address_space (line 451) holding that file's pages in the page cache. The dentry, one per name in a path, cached: "the name ckpt.pt in directory X is inode 13"; a negative dentry caches "this name does not exist". The file, one per open(): offset, open flags, pointers to dentry and inode; file descriptors index a per-process table of these (Processes and the system-call API section 7 draws the three tables).

Names are not files. A directory is itself a file whose content is a table of (name, inode number). A hard link is a second entry for the same inode (hello.txt and hardlink.txt are both inode 14, Links: 2); a symbolic link is a small file containing a path. The inode is freed when its link count is zero and no process has it open, so deleting a checkpoint that a running process still holds open frees no space until it closes; lsof +L1 lists such deleted-but-open files.

Extents. Inode 13's data is one extent: logical blocks 0 to 732 stored in physical blocks 2066 to 2798, contiguous. That is 733 blocks of 4,096 bytes, the fewest that hold 3,000,000 bytes (3,000,000 / 4,096 = 732.4), and Blockcount: 5864 counts the same space in 512-byte sectors (733 x 8). ext2 and ext3 listed every block number; an extent says "start, length" once, so a large file costs ext4 almost no metadata. ext4 also groups inodes and their data into block groups so a file's inode sits near its data (OSTEP ch. 41 credits the idea to FFS). The journal (section 7) is itself an inode, 4 MiB here.

A name points at an inode; the inode, not the name, is the file

Inode numbers, link counts and the extent are copied from the debugfs output (in the closed block below). struct file, struct dentry and struct inode are the kernel's objects (include/linux/fs.h lines 916 and 610, include/linux/dcache.h line 89, v5.10).

What metadata costs: the same 40 MiB as 10,240 files or one

Every small file pays for a path lookup, an inode, a directory entry, a share of a journal transaction and its own block allocation; every cold read of one is at least one device request that readahead (section 3) cannot merge with its neighbours. On a network file system each open and stat is also a round trip to a server (section 9), so the gap grows from tens to thousands of times.

As 10,240 small files, the same 40 MiB is 7.2x slower to create and 56x slower to read cold

Orange: 10,240 files of 4 KiB; blue: one file of 40 MiB, on ext4 measured. Creating the small files took 7.2x as long, reading them warm 10.6x, cold 56x. Cold means each file's pages were dropped with posix_fadvise(DONTNEED) after an fsync.

The debugfs output, path lookup, and the commands (depth)

Read it from the bottom up: the directory out is a table (ckpt.pt is inode 13; hello.txt and hardlink.txt are inode 14), inode 13's EXTENTS line is the extent, and the journal is an inode of its own.

Path lookup. open("/data/out/ckpt.pt") walks the path one component at a time, looking each name up in the dentry cache and asking the file system only on a miss (fs/namei.c). The root's Syscall tracer shows import torch making hundreds of newfstatat calls that fail with ENOENT: Python searching its path. Each failure leaves a negative dentry, so the second import is cheap.

Commands that show it
  • stat file (inode number, links, size, blocks, times); ls -li (inode numbers)
  • df -h (space) and df -i (inodes: a file system can run out of inodes with free space left, the small-files failure)
  • filefrag -v file (extents of a file on a mounted ext4 or XFS); debugfs -R "stat <13>" image
  • lsof +L1 (deleted files still open, still using space)

3. Reading: the page cache and readahead

A device request has a large fixed cost; programs often read 4 KiB at a time, and often read the same file again (every epoch). Two answers: keep what was read in memory, the page cache, and when a program reads sequentially, fetch the next pages before it asks, readahead. How the page cache competes for memory and is reclaimed is Virtual memory's; this section is how data gets into it.

measured A cold 8 MiB file read 4 KiB at a time; after every read() the script read the container's io.stat, so each device request and its size is visible. Predict first: with a 128 KiB (32-page) maximum window, how many device requests do 512 sequential 4 KiB reads cost? Then watch Fig. 2.

  1. A cold file. It was just evicted from the page cache with posix_fadvise(DONTNEED): nothing is cached. The maximum window is 32 pages (128 KiB).
  2. read() 1 misses: a synchronous readahead of 4 pages. get_init_ra_size(1) = 4: pages 0 to 3 in one request, the program waits for it. Page 1 carries the readahead mark.
  3. read() 2 hits the mark: 8 pages, fetched ahead. The next window (pages 4 to 11) is requested asynchronously while the program keeps reading pages already in memory.
  4. Reads 3 to 5: the window doubles to 16 pages. Reading page 4, the first page of the last window, fetches pages 12 to 27.
  5. Reads 6 to 13: 32 pages, the maximum. Page 12 triggers pages 28 to 59; from now on every window is 32 pages.
  6. Reads 14 to 29: one window ahead, always. Page 28 triggers pages 60 to 91. Most reads are memory copies; the device works ahead of the program.
  7. Reads 30 to 128: steady state. Windows of 32 pages at reads 61, 93 and 125: 128 reads cost 8 device requests (188 pages).
  8. The whole run: 512 reads, 20 requests. 572 pages fetched; with POSIX_FADV_SEQUENTIAL the window doubles to 64 pages and the same reads cost 13 requests. With readahead off, or at random offsets, every read is its own request: 64 reads, 64 requests.

Fig. 2: sequential reads cost few requests because each window is fetched one window ahead. Page 0 is front left, 16 pages to a row. Blue tiles are pages in the page cache, orange the windows fetched in the current step (streaming up from the device in front), dashed outlines pages not yet read; the dark glow is the page the latest read() asked for. Measured: 512 sequential reads cost 20 requests (572 pages) by default and 13 requests (636 pages) with POSIX_FADV_SEQUENTIAL; readahead off and random offsets cost one request per read. Defaults reproduce the measurement independently: the two source rules below predict every request of both sequential runs. Times are this VM's: the "device" is macOS's cache of the disk file.

With readahead on, the window grew 4, 8, 16, 32 pages and then stayed at the 32-page maximum, each requested one window ahead of the reader, so most reads never waited for the device. With readahead off the same reads cost one request each. Random reads get no readahead: the kernel only predicts sequential access, and the measured random case fetched exactly one page per read.

The rule, from mm/readahead.c source (v5.10). First window, get_init_ra_size (line 311): round the request up to a power of two, then x4 if it is at most 1/32 of the maximum, x2 if at most 1/4, else the maximum. Each later window, get_next_ra_size (line 329): x4 while under 1/16 of the maximum, then x2, capped at the maximum. The maximum is read_ahead_kb (128 KiB here, 32 pages); posix_fadvise(POSIX_FADV_SEQUENTIAL) doubles it for that open file (mm/fadvise.c line 92) and POSIX_FADV_RANDOM turns readahead off (line 88).

A DataLoader reads samples at random offsets from one big uncompressed file of fixed-size records, 4 KiB each, cold. How many device requests do 1,000 samples cost, roughly?
Cold and warm, and the honest caveat

The root's Debug lab case "The first epoch is slower than the rest: cold and warm page cache" measured a 512 MiB shard at 858 MiB/s cold against 3,831 MiB/s warm, and readahead off at 16,384 requests for 64 MiB against 516 with it on. On this VM "cold" still means "in macOS's cache of the virtual disk file": on a real local NVMe drive the cold number would be lower, and on a network file system much lower. Here the cold small-files read of section 2 was 56 times slower than reading the same 40 MiB as one file.

The read path in the source, and the knobs (depth)

source read(fd, buf, 4096) reaches ext4's ext4_file_read_iter, which calls the generic generic_file_buffered_read (mm/filemap.c line 2185, v5.10). For each page of the request it looks the page up in the file's address_space. A hit is a memory copy. A miss calls page_cache_sync_readahead (line 2235), which decides how much to fetch, allocates the pages, builds bios and submits them; the reader then sleeps until its page is unlocked. That sleep is the D state with wait channel wait_on_page_bit_common that the root's Debug lab case "Slow storage: workers sleep in D state on page faults" caught on a throttled disk. A page that carries the PG_readahead mark triggers page_cache_async_readahead (line 2247): the next window is fetched while the program is still reading the current one.

Commands and knobs
  • Per device: cat /sys/block/DEV/queue/read_ahead_kb, change with blockdev --setra SECTORS /dev/DEV (root; network file systems have their own, e.g. NFS's read_ahead_kb under /sys/class/bdi/).
  • Per open file: posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL | RANDOM | WILLNEED | DONTNEED), from Python os.posix_fadvise (posix_fadvise(2)); WILLNEED starts reading a range now; DONTNEED drops a file's clean pages (how this page made files cold without root).
  • For a mapping: madvise(MADV_SEQUENTIAL | MADV_RANDOM | MADV_WILLNEED); Virtual memory measured random rows through mmap fetching 13x more than they used, and MADV_RANDOM cutting it to 3.4x.
  • How much of a file is cached: fincore file (util-linux); whole system: free -m (buff/cache), grep -E "^(Cached|Dirty|Writeback):" /proc/meminfo; your container: grep -E "^file " /sys/fs/cgroup/memory.stat.

4. Writing: dirty pages, writeback and throttling

If every write() waited for the device, a checkpoint written in 4 KiB pieces would pay a device round trip for each. So write() copies the bytes into the cached page, marks it dirty (changed in memory, not yet on the device) and returns. Per-device flusher threads (kernel workers named kworker/u*:*-flush-*) write dirty pages back for one of three reasons (vm sysctl docs; mm/page-writeback.c lines 74 to 109):

  1. Age: every dirty_writeback_centisecs (500, so 5 s) the flusher wakes and writes data that has been dirty longer than dirty_expire_centisecs (3000, so 30 s).
  2. Background threshold: when dirty data passes dirty_background_ratio (10%) of dirtyable memory (free memory plus file pages that could be reclaimed, not total RAM: global_dirtyable_memory, line 362), the flusher writes everything, whatever its age.
  3. Hard threshold: near dirty_ratio (20%) the writing process itself is paused in balance_dirty_pages (line 1555, the pause at line 1795) so it cannot dirty memory faster than the device drains it. This is dirty throttling: write() becomes slow without any error.

With cgroup v2 each memory cgroup is also its own writeback domain, with thresholds scaled to its memory, so a container with a 1.5 GB limit is throttled long before the machine is (cgroup v2 docs, Writeback). measured Each run in Fig. 3 and the chart below it wrote a file into a fresh container (limit 1,500 MB) and sampled its memory.stat (dirty and under-writeback page cache) and io.stat (bytes the device received) every 100 ms.

  1. The write returns; all of it is dirty. Each lane is one run in its own fresh container: 16 MiB written in 0.01 or 0.02 s, 256 MiB in 0.29 s. Nothing has reached the device yet.
  2. fsync forces the 256 MiB out: 110 ms. The right lane calls fsync after its write: the dirty pages go under writeback and the device receives all 256 MiB before fsync returns.
  3. A fresh container's 16 MiB leaves 4.5 s after the write, at the flusher's next 5-second wake-up, long before it is 30 s old. Likely because a brand-new writeback domain has almost no share of the background threshold, so even 16 MiB counts as over it (our reading of wb_over_bg_thresh, not traced; see the question below).
  4. A primed container's 16 MiB stays dirty. This container had just written and synced 1 GiB, so it has a share and 16 MiB is under its threshold: the flusher wakes every 5 s and leaves the data alone.
  5. 30.2 s after the write, it leaves. That is when the age rule (dirty longer than dirty_expire_centisecs, 30 s, found at a 5-second wake-up) would send it. The other three primed runs left after 7.7, 18.0 and 0.4 s: when is not a promise.

Fig. 3: each lane's 16 tiles are sixteenths of what that run wrote: orange dirty in the page cache, blue received by the device (memory.stat and io.stat every 100 ms) measured. Time is seconds after the first sample that saw the write.

Six runs wrote 16 MiB (or 256 MiB) and then waited, with nothing calling fsync. The textbook rule is "written back once it is 30 s old". How long did the 16 MiB actually stay dirty?
When it bites in ML
  • A crash in the window loses data that every call said was written. The 256 MiB checkpoint of section 10 left 256 MiB dirty when torch.save returned. Killing the process does not lose it (the dirty pages belong to the kernel); only a kernel crash, a power loss or a VM or node being killed does.
  • Dirty throttling stalls training. In the "1.5 GiB, as fast as possible" run the writer was caught sleeping in balance_dirty_pages while the container's dirty data hovered at the domain's limits. A loop that saves a large checkpoint synchronously stalls the same way; a background writer thread moves the stall off the training thread but does not remove it.
  • Dirty pages count toward your container's memory and cannot be dropped until written, so a memory-limited container that writes faster than its device can be pushed toward the OOM killer by its own page cache (Virtual memory).
The same 16 MiB left memory 0.4 s after the write in one run and 30 s in another

The write path in the source, this VM's thresholds, commands and fixes (depth)

source write() on ext4 runs generic_perform_write (mm/filemap.c line 3288, v5.10): for each page, ext4_da_write_begin (fs/ext4/inode.c line 2934) finds or creates the page in the cache and reserves space without choosing disk blocks (delayed allocation, section 7), the bytes are copied in, the page is marked dirty, and balance_dirty_pages_ratelimited (line 3365) checks whether this writer has dirtied too much. Then write() returns. Nothing has touched the device.

On this VM the kernel computed a background threshold of MiB and a hard threshold of MiB VM-wide (/proc/vmstat) measured.

Commands and fixes
  • See it: grep -E "^(Dirty|Writeback):" /proc/meminfo (machine), grep -E "file_(dirty|writeback)" /sys/fs/cgroup/memory.stat (container), cat /proc/PID/wchan (a writer in balance_dirty_pages is being throttled), grep -E "nr_dirty(_background)?_threshold" /proc/vmstat.
  • Tune (hosts you own): vm.dirty_background_bytes and vm.dirty_bytes set absolute limits instead of ratios, which is saner on machines with hundreds of GB of RAM where 20% is far more than a device can drain in seconds.
  • In code: fsync what must survive (section 5); for a long streaming write, start writeback early with sync_file_range(SYNC_FILE_RANGE_WRITE) on each finished chunk and fdatasync once at the end, which keeps dirty data and the final fsync small.

This also explains the root's Debug lab "fsync" case, where 256 MiB was clean 5 s later: a fresh container's writeback domain is over its share at once.

5. Durability: fsync, fdatasync, and when fsync fails

A checkpoint, a database log or a "this checkpoint is complete" marker must survive a crash, so the program needs a call that returns only when the data is on stable storage, and it must know exactly what that call covers. fsync(fd) covers the file's data and all its metadata, then a device cache flush ("This includes writing through or flushing a disk cache if present", fsync(2)); not the directory entry that names the file. fdatasync(fd) covers the data plus only the metadata "needed in order to allow a subsequent data retrieval to be correctly handled": size and block map yes, modification time no. sync_file_range only starts or waits for writeback of a byte range; the kernel's own comment: "there are no guarantees here that the data will be available on disk after a crash" (fs/sync.c lines 351 to 355, v5.10).

source ext4_sync_file (fs/ext4/fsync.c line 129, v5.10) does three things in order: write the file's dirty pages and wait; wait for the journal transaction that last changed what this call covers; flush the device cache. Fig. 4 follows one 4 KiB overwrite through each call; pick a call, then compare the measured costs.

  1. pwrite() of 4 KiB. The call starts in your program with the 4 KiB record.
  2. pwrite() returns: 1.4 us. The bytes are copied into the cached page, which is marked dirty; the inode's new modification time joins the running journal transaction, in memory.
  3. Write the page and wait. file_write_and_wait_range (called from ext4_sync_file): the dirty page becomes a bio and goes through blk-mq to the driver.
  4. The device acknowledges. It reports the write complete as soon as it is in its volatile cache (write_cache: write back). A power cut now still loses it.
  5. Commit the journal transaction. ext4_fsync_journal (line 104): this inode last changed in the running transaction (i_sync_tid), so jbd2 must commit it: journal blocks, then the commit block.
  6. Commit block with PREFLUSH and FUA. jbd2 writes the commit block with REQ_PREFLUSH | REQ_FUA (fs/jbd2/commit.c line 157): the device flushes its cache, so the data page and the journal reach stable media.
  7. fsync returns: 1,305 us. Data and all metadata are durable.

Fig. 4: fsync pays for a journal commit that fdatasync skips on an overwrite; sync_file_range never reaches the media. Orange is the data page, purple the inode change; only what reaches the bottom block survives a power cut. Order from fs/ext4/fsync.c (v5.10), whole-call times measured.

On an overwrite, fdatasync cost about a third of fsync here. Why, given that both wrote the same 4 KiB?
What each call costs per 4 KiB record measured

1,000 records each; median and 99th percentile in microseconds. "Append" grows the file (size changes every time); "overwrite" rewrites a preallocated, already-synced file (only data and times change). tmpfs keeps files only in memory, so it has nothing to flush.

Log scale. On an overwrite, fdatasync cost 3.3x less than fsync (393 against 1,305 us); on an append only 1.3x less (997 against 1,265 us). sync_file_range is cheaper because it flushes nothing and commits nothing: it is not a durability call. On tmpfs every call costs about a microsecond.

The error now reaches everyone, but the data is still lost

Two descriptors on one file: A (the checkpoint writer) and B (another process, say a log shipper). Sequence from the LWN article and lib/errseq.c; simplified to one page.

When fsync fails

A device error during writeback is reported to the next fsync. Before Linux 4.13 the error could reach one caller only and the failed pages were marked clean, so a second fsync returned success with the data lost: the PostgreSQL "fsyncgate" story in the root's section 7. Since 4.13 the kernel records writeback errors in an errseq_t, a counter plus error code that "allow[s] any number of 'subscribers' to tell whether it has changed since a previous point where it was sampled" (lib/errseq.c lines 8 to 10, v5.10), so every file descriptor open at the time sees the error once (LWN, Improved block-layer error handling). The pages may still be gone.

  1. write() on A returns. The new checkpoint bytes are only in the page cache, dirty. No error is recorded.
  2. Writeback fails: the device returns EIO. The failed page is marked clean (so nothing will try to write it again, and it may be dropped), and an error flag (AS_EIO) is set on the file's mapping.
  3. B calls fsync first. B gets EIO. The flag is now cleared.
  4. A calls fsync. A, the writer that cares, gets 0: success. It believes the checkpoint is durable. This is the fsyncgate failure PostgreSQL hit.
  5. A calls fsync again. 0 again: retrying fsync cannot bring the bytes back, and does not even report the loss.

The rule: a failed fsync means that file's recent writes are lost; rewrite it from memory, or abort. With delayed allocation, running out of space can also surface only at fsync or close rather than at write, so check both: Python's f.close() raises OSError if the underlying close fails.

The rest of the family, and how to count calls in a running job (depth)
CallCoversSource
open(..., O_DSYNC) / O_SYNCevery write() behaves as if followed by fdatasync / fsyncopen(2)
syncfs(fd), sync()everything dirty on one file system, or on all of them; heavy, and in a shared machine you wait for other people's data toosync(2)

source The journal wait is ext4_fsync_journal (line 104): for fdatasync it waits only for the transaction that last changed what data retrieval needs (i_datasync_tid against i_sync_tid, line 109), and if that already committed there is nothing to wait for. It goes through ext4_fc_commit (line 115), a full journal commit unless the newer "fast commit" feature was enabled when the file system was created (a feature flag that needs privileges to read on this VM). The flush is blkdev_issue_flush (line 177).

  • An fsync per step is about a millisecond per call here and can be tens of milliseconds on cloud block storage not run here: fine once per checkpoint, ruinous once per logged metric line. Buffer logs and fsync on a timer.
  • Count the calls: strace -f -e trace=fsync,fdatasync,sync_file_range,rename,renameat -p PID, or strace -c for totals.
  • Never retry a failed fsync and continue. Save the checkpoint again to a new file.

6. Atomic replace: a crash sees old or new, never half

fsync makes data durable, not an update atomic: a crash in the middle of rewriting ckpt.pt leaves a file that is partly new, partly old or partly missing, and the previous good checkpoint is already destroyed. The fix is to build the new version under another name and switch in one step. rename: "If newpath already exists, it will be atomically replaced, so that there is no point at which another process attempting to access newpath will find it missing" (rename(2)). Atomic for readers now; durable only once the directory change is committed, which is what an fsync of the directory forces: "Calling fsync() does not necessarily ensure that the entry in the directory containing the file has also reached disk. For that an explicit fsync() on a file descriptor for the directory is also needed" (fsync(2)).

  1. Before: the last good checkpoint is on disk. The directory maps ckpt.pt to inode A, on disk and in its cached copy.
  2. torch.save into ckpt.pt.tmp. A new inode B under a new name, only in memory: its 256 MiB is dirty in the page cache. ckpt.pt is untouched.
  3. fsync the temporary file: 111 ms. B's data and inode reach the disk. A crash now still finds A under ckpt.pt; B may be left without a name, which is litter, not damage.
  4. rename over ckpt.pt. In memory the name now points at B, at once for every reader. The directory on disk still says A: a crash now brings back the old checkpoint, which is still a good one.
  5. fsync the directory: 2.3 ms. The new entry reaches the disk and A's space is freed. Old or new at every point, and now new for good. The whole protocol took 365 ms against 263 ms for the plain save.

Fig. 5: the safe save of the running job's checkpoint, from its trace (below); POSIX guarantees only, ext4 adds ordering (the crash lab). Times are the 256 MiB runs of section 10 measured.

measured The running job's checkpoint written two ways, under strace -f -y, keeping only calls on the checkpoint directory (shown as DIR), with runs of writes folded into one line:

The plain save opens the existing ckpt.pt with O_TRUNC: the old checkpoint is thrown away at the first system call, and the new one exists only in the page cache until writeback. The safe version never touches ckpt.pt until a complete, durable new file exists; renameat is the single switch; the directory fsync makes the switch durable.

torch.save(obj, "ckpt.pt")
tmp, fsync, rename, fsync the directory

The crash lab runs every protocol on this page through a crash at each point. Pick a protocol, then step the crash point: the left pane is what every file system promises, the right what this VM's ext4 adds. Call sequences from the real traces above and in section 10; the last protocol is our fix (DCP into a new directory plus the two directory fsyncs DCP does not make). A model with the rules in the closed block below, not a crash test: no power was cut. ALICE (Pillai et al., OSDI 2014) checks real applications the same way.

Across all protocols: plain torch.save loses the checkpoint at 3 of 4 crash points; fsync in place at 2 of 5; tmp then rename without fsync at 1 of 5 under POSIX only (0 on this ext4); tmp, fsync, rename, fsync(dir) at 0 of 7; DCP saving into the same directory at 10 of 11; DCP into a new step directory plus parent fsync at 0 of 13.

Crash the machine after any call and see what a restarted job finds

POSIX only: what every file system promises

ext4, data=ordered, delalloc, auto_da_alloc (this VM)

Every crash point at once, and the two models exactly (depth)

POSIX only. Durable: a file's data and its own metadata after an fsync of that file returns (fsync(2)); a directory's entries (create, rename, unlink, mkdir) after an fsync of that directory. Everything else may or may not have reached the disk, independently (each name change is atomic in itself, rename(2)). File data not yet synced may be absent, cut short, fully there, or (for a file rewritten in place without truncation persisting) a mix of old and new.

ext4 as configured here. Name and size changes go through one journal and reach the disk in order, so after a crash some prefix of them is there. An fsync of anything commits the whole running transaction, so every earlier name change is durable after it (fs/ext4/fsync.c, ext4_fsync_journal). File data is written by writeback or fsync; with delayed allocation, a file whose data was not yet written has size 0 or a shorter size after a crash, never garbage (data=ordered). auto_da_alloc: renaming over an existing file, or closing a file that was truncated, starts writing its data, and the commit that records a later name change waits for it (fs/ext4/namei.c lines 3782 to 3783, fs/ext4/file.c lines 140 to 143, ext4 docs).

Simplifications: the crash happens at some moment after the listed step and before the next; device caches honour flushes; one writer; a DCP checkpoint "loads" if its .metadata and shard come from the same save.

The checkpoint rules
  1. Write to a new name (ckpt.pt.tmp, or a new step_000200/ directory). Never open the last good checkpoint for writing.
  2. flush() Python's buffer, then os.fsync(f.fileno()) every file you wrote.
  3. os.replace(tmp, final) (a rename), or for a directory of shards, write a small "complete" marker last.
  4. os.fsync a descriptor of the directory that holds the name you changed (open it O_RDONLY).
  5. Keep the previous checkpoint (two or three) until the new one is durable, and on restart verify before trusting: load the newest, fall back to the previous one if it fails.
  6. If any fsync, write or close fails, treat that checkpoint as lost and write it again.
A job runs torch.save(state, "ckpt.pt.tmp"); os.replace("ckpt.pt.tmp", "ckpt.pt") with no fsync at all, on ext4 with default options. The machine loses power 2 seconds later. What can the restarted job find at ckpt.pt?
What ALICE found, ext4's auto_da_alloc heuristic, and two more tools (depth)

Pillai and colleagues recorded the system calls of eleven widely used systems ("databases, key-value stores, version control systems, distributed systems, and virtualization software") and computed every state a crash could leave under the guarantees file systems actually give. They found "a total of 60 vulnerabilities, many of which lead to severe consequences" (All File Systems Are Not Created Equal, OSDI 2014). The answer depends on the file system and its mount options: code that is safe on one can corrupt on another.

source ext4 carries a heuristic for the most common unsafe pattern, born from the 2009 zero-length-files story in the root's section 7: with the default auto_da_alloc mount option (this VM has it), renaming a file over an existing one makes ext4 allocate and start writing the source file's delayed data first (fs/ext4/namei.c lines 3782 to 3783, ext4_alloc_da_blocks), and closing a file that had been truncated to zero does the same (fs/ext4/file.c lines 140 to 143). With data=ordered, the commit that records the rename then waits for that data. So on ext4, write-then-rename without fsync usually ends with old or new rather than an empty file; but the rename is still not durable until the next commit, the heuristic exists only on ext4, and the ext4 documentation introduces it as help for "broken applications" that replace files without fsync(), providing "roughly the same level of guarantees as ext3" (ext4 docs, auto_da_alloc). Write the fsyncs.

renameat2 flags. RENAME_NOREPLACE fails instead of overwriting (two writers cannot clobber each other); RENAME_EXCHANGE swaps two names atomically (rename(2)). Rename is atomic only within one file system, so the temporary file goes in the same directory.

O_TMPFILE + linkat. Create a file with no name at all, write and fsync it, then give it a name with linkat: it can never be seen half-written, and a crash leaves no .tmp litter (open(2), O_TMPFILE). linkat will not replace an existing name, so it suits "write once" files such as shards.

7. Journaling: how ext4 keeps its own structures consistent

Creating, growing or renaming a file changes several blocks (the inode, a free-block bitmap, the directory). A crash between them leaves the file system's own structures inconsistent. ext4 hands the fix to a generic journaling layer, jbd2: every operation that changes metadata opens a handle on the current running transaction, many operations share one transaction, and the transaction is committed (its blocks written to the journal, then a commit block) when it is 5 seconds old (JBD2_DEFAULT_MAX_COMMIT_AGE, include/linux/jbd2.h line 48, v5.10; the commit=5 mount option), when the journal fills, or when someone's fsync needs it. After a crash, mount replays committed transactions and discards incomplete ones: seconds, not the full scan of fsck. The root's OS simulators tab crashes such an update at every block write; Fig. 6 is the order ext4 really uses; pick a data mode.

  1. Handles join the running transaction. The rename or create changed the inode, a directory block and a bitmap, in memory; the file's data is dirty in the page cache. Crash now: nothing new is on disk. Old state.
  2. Commit starts (5 s old, or an fsync): data first. Ordered mode writes the data blocks to their home locations before any metadata that points at them is logged. Crash now: new data sits in blocks nothing points to. Old state, no harm.
  3. Metadata blocks to the journal. The changed metadata blocks are copied into the journal area, the next slots of its ring. Crash now: no commit block, so replay discards the transaction. Old state.
  4. Commit block, with PREFLUSH and FUA. The device cache is flushed and the commit block written through to stable media: the transaction is committed. Crash now: replay copies the metadata home. The new file, with its data.
  5. Checkpoint: metadata written home, later. In the background the metadata blocks are written to their real places. Crash now: replay is harmless (it writes the same blocks again).
  6. Journal space freed. That part of the journal is reused by later transactions. Crash now: the new state, nothing to replay.

Fig. 6: one commit, step by step: in ordered mode the data reaches home before the metadata that points to it is committed. One transaction holding a new file's inode, its directory entry and a bitmap block (orange), plus the file's 4 data blocks (blue; grey with a red edge where a block still holds stale contents). Order from fs/jbd2/commit.c and the ext4 documentation; "Crash now" is what replay finds.

The journal always covers metadata; the data= mount option decides what happens to file data:

ModeFile dataAfter a crash (ext4 docs)
data=journalwritten to the journal too, then in place"bringing both data and metadata into a consistent state"; slowest for most workloads (every byte written twice)
data=ordered (default, this VM)"All data are forced directly out to the main file system prior to its metadata being committed to the journal"a file's metadata never points at blocks with stale contents; recently written data may be missing, never garbage
data=writeback"Data ordering is not preserved""incorrect data [can] appear in files which were written shortly before the crash"; the same level as "XFS and JFS in its default mode - metadata journaling"

Delayed allocation (delalloc, on here) is why ordered mode does not make your file complete. ext4 chooses disk blocks at writeback, not at write(), when it knows how big the file is, which gives large contiguous extents (the single extent of section 2). Until then there are no blocks to order, so the journal can commit a new file's name and size while its data is still only in memory: the zero-length files of 2009, and the reason for the auto_da_alloc heuristic of section 6.

Barriers. A commit block must not reach the media before the blocks it commits, so jbd2 writes it with a cache flush and FUA (REQ_PREFLUSH | REQ_FUA, fs/jbd2/commit.c line 157, v5.10; section 1) unless mounted barrier=0 (this VM: barrier, the default). Turning barriers off on a drive with a volatile cache trades crash safety for speed; never do it for a checkpoint volume.

When it bites in ML: through its defaults. A 5-second window in which renames and new names are not durable; ordered mode that keeps the file system sane but does not make your file complete; and different file systems on different clusters (ext4 locally, XFS on the big array, something else over the network) making "it worked on my machine" checkpoint code unsafe elsewhere.

This VM's journal statistics, XFS, copy-on-write file systems, and commands (depth)

measured This VM's journal since boot (/proc/fs/jbd2/vda1-8/info, readable from an unprivileged container; the disk is shared by every container on the VM):


Transactions here commit far more often than every 5 s (a transaction ran 158 ms on average) because 36,364 of the 36,654 commits were requested, by fsync calls from the containers sharing this disk; each commit logged about 11 journal blocks and took about 2.4 ms. Later the committed blocks are written to their real places (a checkpoint, in journaling's sense) and that journal space is reused.

XFS, common on large local arrays, journals metadata only, with a design ("delayed logging") that batches many changes into each log write (kernel docs: XFS delayed logging). Do not count on ext4's auto_da_alloc rename rule there or anywhere else: the fsync rules of section 6 are what every file system promises to honour. not run here (the kernel knows XFS, but mounting needs privileges)

Copy-on-write file systems (btrfs, ZFS) never overwrite a block in place: a change writes new blocks and new copies of every tree node above them, up to a new root, and the commit is the single write that switches to the new root. The file system is always consistent with no journal replay, and snapshots cost almost nothing (keep the old root). OSTEP ch. 43 develops the same idea as the log-structured file system. Durability of your file still needs fsync. not run here

Commands
  • findmnt -no OPTIONS /path or cat /proc/fs/ext4/DEV/options: data mode, commit interval, barrier, delalloc, auto_da_alloc
  • cat /proc/fs/jbd2/DEV-8/info: commits, average commit time
  • dumpe2fs -h /dev/DEV (features, journal size), xfs_info /mount

A database's write-ahead log is the same idea one level up, inside the database's own files: Storage engines and indexes owns it.

8. Direct and asynchronous I/O

The page cache is a bargain for data you read twice and for small writes, but a training job also streams data it reads once (a dataset bigger than RAM) and writes data it will not read back (a checkpoint). Copying that through the cache costs a memory copy per byte, evicts useful pages, and creates the dirty throttling of section 4. Two tools: skip the cache, and keep many requests in flight from one thread.

O_DIRECT asks the kernel to move data by DMA straight between your buffer and the device (open(2), O_DIRECT). The price is alignment: the buffer address, the length and the file offset must be multiples of the device's logical block size (512 bytes here), or the call fails measured:


O_DIRECT is not durable. It skips the page cache, not the device's cache, and does not commit metadata such as a new file size. In the fio runs below, adding fdatasync after each direct 4 KiB write cut the rate from 12,706 to 6,270 writes per second.

Where the bytes are copied on each path

Buffered I/O copies once by CPU into the page cache, and the device later moves it by DMA. O_DIRECT moves it by DMA between your (aligned) buffer and the device. GPUDirect Storage moves it between GPU memory and storage, with no bounce buffer through the CPU not run here. None of the three flushes the device's cache: durability still needs fdatasync.

When to use it. Checkpoint writers and data loaders that manage their own buffers use it to keep the page cache for what matters and make throughput predictable; GPUDirect Storage requires it. Not for small reads you will repeat (no caching, no readahead), nor from Python on unaligned bytes objects (use an aligned buffer, e.g. mmap.mmap(-1, n), which is page aligned).

Buffered and direct, side by side measured

The direct sequential numbers are far above any single NVMe drive's because macOS serves the VM's disk file from its own cache; read the relations (direct sequential at queue depth 8 beats buffered single-threaded writes; random 4 KiB costs the same either way when nothing is cached), not the absolute values.

Asynchronous I/O. A plain read blocks the thread, so one thread has one request in flight: queue depth 1 in section 1. libaio (io_submit, io_getevents) is truly asynchronous only with O_DIRECT. io_uring (Linux 5.1+) shares two ring buffers between program and kernel: the program writes submission entries and reads completion entries, often with no system call per I/O (io_uring(7)); Concurrency owns the ring design and the event loops built on it. Here fio's io_uring engine ran 51,050 reads per second at queue depth 16, against 48,455 with libaio measured, once a memory-lock limit was raised:

Why io_uring first failed in a container, and the alignment rules on newer kernels (depth)

measured On this 5.10 kernel, fio's io_uring engine first failed with Cannot allocate memory: the rings are charged to RLIMIT_MEMLOCK unless the process has CAP_IPC_LOCK (fs/io_uring.c lines 7869, 9273 and 9335, v5.10), and the container's default limit is 64 KiB (the same limit the Virtual memory page met for pinned memory). Even root is short of it: on 5.10 that limit is counted per user ID, so every container running as UID 0 shares one 64 KiB budget across the whole VM, and the BPF programs runc attaches are charged to it too (Containers and isolation measures it). With docker run --ulimit memlock=-1:-1 it ran:


tmpfs has no device to DMA to, so on this kernel it refuses O_DIRECT at open. Linux 6.1 added STATX_DIOALIGN to statx to ask a file for its exact alignment rules (statx(2)) not run here.

9. Storage you do not own: what network file systems promise

On a cluster the dataset and the checkpoint directory usually live on a server, a parallel file system or an object store, and each keeps a different subset of the local guarantees above. Nothing in this section ran here (no network storage in the VM) not run here; it is taught from each system's own documentation. How those systems are built and sized (Lustre's servers and striping, object stores, staging, bandwidth) is Storage and data movement's; this section is the semantics a checkpoint writer depends on.

NFS: close-to-open. One server exports a file system; clients cache data and attributes. Linux's client gives close-to-open consistency: at open it revalidates with the server, and "when the application closes the file, the NFS client writes back any pending changes to the file so that the next opener can view the changes. This also gives the NFS client an opportunity to report write errors to the application via the return code from close(2)" (nfs(5)). fsync asks the server to commit the data to its own stable storage (the COMMIT procedure of RFC 1813).

A job on 64 nodes writes its checkpoint shards to an NFS mount, each rank calls fsync on its shard, and rank 0 then writes a COMPLETE marker file. A restarted job on another node sees the marker. Is every shard guaranteed to be readable there?
Another node sees your shard only after you close it and it opens it

Time runs down. Rank 7 writes a shard, rank 0 writes the marker after a barrier, and a restarted job on node B reads them. The ordering that matters is across ranks: the marker is written only after every rank has closed (or fsynced) its shard. Per nfs(5); the message names are NFSv3's.

Check the return value of close: on NFS that is where write errors appear. And many small files cost a network round trip each for open and stat.

Object stores and FUSE mounts have no rename and no fsync in the local sense, so "write then rename" becomes "upload under a new key, then write a small pointer or marker object last": a checkpoint is complete when its marker exists. Code that relies on os.replace, on appending, or on rewriting part of a file fails or behaves differently on such mounts; read each mount's semantics page before pointing a checkpoint writer at it.

Lustre, object stores, FUSE mounts and GPUDirect Storage: what each changes for a checkpoint writer (reference)
SystemHow it worksWhat changes for you
Lustre (and GPFS, WekaFS, ...)Metadata servers hold names and directories; file data is striped over many object storage targets. How it is built, striped and sized is Storage and data movement's.Big files spread over many targets are fast; metadata is the shared bottleneck, so millions of small files, or thousands of ranks calling stat at start-up, slow the whole cluster.
Object stores (S3, GCS, Azure Blob)Objects are written whole (or in multipart uploads) and appear atomically when the upload completes; S3 has given "strong read-after-write consistency" for all applications since December 2020 (AWS, 2020-12). There is no rename and no fsync. Since August 2024 a PUT can carry If-None-Match to fail rather than overwrite an existing key (AWS, 2024-08).New key, marker last. A conditional write keeps two jobs from overwriting each other's checkpoint.
FUSE mounts of object stores (Mountpoint for S3, gcsfuse, s3fs)A user-space process implements the file system calls on top of the object API. Mountpoint, for example, writes "sequentially from a single client at a time", uploads asynchronously, and on general-purpose buckets "does not emulate operations like rename"; "if your application needs to guarantee that a new file has been uploaded to S3, it should call fsync on the file before closing it" (Mountpoint semantics).No os.replace, no appends, no partial rewrites; fsync before close.
GPUDirect Storage"enables a direct data path for direct memory access (DMA) transfers between GPU memory and storage, which avoids a bounce buffer through the CPU" (GDS overview). Programs use the cuFile API; its reference guide's examples open the file with O_DIRECT before registering it (cuFile API reference).Skips the page cache and pinned host memory entirely (section 8's rules apply: alignment, and durability still needs a sync). Worth it when host memory bandwidth or CPU copies limit checkpoint or data loading speed on GPU servers with supported NVMe or network storage.

10. Checkpoints: torch.save, distributed checkpoint, async saves

The running example, scaled up. The root's job saves a 0.28 MB state. Here the same write paths save a 256 MiB state (), five times each on ext4, plus PyTorch's distributed checkpoint (DCP) in three settings and its asynchronous save. "Dirty after" is how much of the checkpoint was still only in memory when the call returned. measured

torch.save writes a zip archive: a pickle of the object structure plus one record per tensor storage. Given a path, it opens the file itself (O_WRONLY|O_CREAT|O_TRUNC in the trace of section 6), writes and closes: no fsync, and the old file's contents are discarded at open. Loading needs the zip's central directory, written last; a file cut short anywhere fails to load, the error the root's Debug lab case "Disk full mid-checkpoint: a cryptic error and a destroyed checkpoint" shows (failed finding central directory).

Safety costs about 100 ms on a 263 ms save; the saves that skip fsync return with all 256 MiB still in memory

Medians of 5 runs (min and max in src/raw/ckpt_time.txt). fsync added 86 ms to a 263 ms save; the full safe protocol 102 ms, of which the directory fsync was 2.3 ms. Four writer threads made DCP faster than one. On this VM the device absorbs 256 MiB in about a tenth of a second; a device that writes 250 MB/s (an illustrative cloud-volume rate) would need 268 MB / 250 MB/s = about 1.1 s for the same fsync.

torch.distributed.checkpoint source PyTorch 2.14.1 (the version in this image, git 5c48869), torch/distributed/checkpoint/filesystem.py. Every rank writes its own files, named __{rank}_{n}.distcp, one per writer thread (thread_count); with sync_files=True (the default) each is flushed and fsynced before closing (lines 470 to 474). Then the coordinator rank, in finish (line 762), writes the global .metadata.tmp, fsyncs it (lines 779 to 783), deletes any existing .metadata (line 796) and renames the temporary file into place (line 798). It never fsyncs a directory. The traced save, overwriting an existing checkpoint directory:


The window this leaves, and the fix
Saving again into the same directory truncates the old shards at openat(..., O_TRUNC), so the old checkpoint is gone at the first call. Between unlinkat(.metadata) and the moment the rename is durable (the next journal commit, up to 5 s on ext4), a crash leaves a directory with no .metadata, which DCP cannot load: no checkpoint at all. And because the directory is never fsynced, even after dcp.save has returned a crash can bring back the old .metadata next to the new, fsynced shard: a checkpoint whose metadata and data come from different saves. With a new directory per step there is nothing to delete or truncate, and a crash can only lose the step being written. This is what torchtitan does ("Standardized checkpoint path, e.g. checkpoints/step-100", torchtitan base.py line 379). Add an fsync of the parent directory after the save so the new directory's name is durable too, and treat a step directory without .metadata as incomplete. This is our reading of the source and the trace, shown as states in the crash lab (pick the two DCP protocols); it is not a reported incident.

Asynchronous saves. dcp.async_save first stages the state (copies tensors to CPU memory), returns a future, and writes in the background, so training continues during the slow part. Here it blocked training for 66 ms of a 501 ms save. Two costs remain: a second copy of the state in host memory while it is written, and the writes still compete for the device and the dirty-page budget (section 4), so a step that runs during the background write can be slower.

Checkpoint checklist for a real job
  • One directory per step (step-000200/); each rank writes and fsyncs its own shard; barrier; one rank writes the metadata or a COMPLETE marker, fsyncs it, then fsyncs the step directory and its parent.
  • Keep the last two or three; delete older ones only after the new one is complete; on restart choose the newest complete one and fall back if loading fails.
  • Check free space and inodes first (shutil.disk_usage); handle OSError from write, fsync and close as "this checkpoint failed".
  • On object stores and FUSE mounts follow section 9: new keys, marker last.
  • Distributed Training covers what to put in a checkpoint, Power, cooling, reliability how often to write one, Fault tolerance at scale recovery designs, and Storage and data movement checkpoint I/O at cluster scale; this page covers getting it onto the disk.
torch.save with a file object, and CheckFreq (depth)

Given a file object instead of a path, torch.save writes into it and leaves flushing, syncing and renaming to you: that is how the safe protocol of section 6 wraps it. CheckFreq describes the same split as async_save, a quick in-memory "snapshot" and a background "persist", and chooses how often to checkpoint from measured costs (CheckFreq, FAST 2021).

11. Data loading: the same mechanisms, applied

Mohan and colleagues measured nine models on production servers at Microsoft and found that "in many cases, DNN training time is dominated by data stall time: time spent waiting for data to be fetched and preprocessed" (Analyzing and Mitigating Data Stalls in DNN Training, VLDB 2021). The storage half of that is this page's mechanisms; dataset formats, sharding and loader prefetch are Storage and loading at scale's.

  • Few big files, read sequentially: readahead (section 3) needs sequential access and every file pays metadata (section 2: 56x slower cold for small files here; far worse on a network file system). Hence tar shards, Arrow and Parquet files, and memory-mapped token arrays; shuffle the order of shards and within an in-memory buffer instead of reading random records.
  • Queue depth: one reader thread is queue depth 1 (section 1); workers, prefetching and asynchronous readers keep many requests in flight, which matters most on remote storage with long latencies.
  • The page cache is a free dataset cache while the dataset fits in memory: epoch 2 reads RAM. When the dataset is a little larger than memory, an LRU-like cache can evict each page just before it is needed again; the same paper reports this thrashing and proposes a cache that keeps a fixed subset instead. The page cache counts toward a container's memory limit (Virtual memory).
  • Stage to local disk when the shared file system is slow or shared with many jobs: copy shards to local NVMe at start, then read locally.
  • Look before tuning: workers in state D with wait channel wait_on_page_bit_common or io_schedule wait for storage; high system time with many small read calls is the root's Debug lab case "High system time: millions of tiny reads"; iostat -x shows whether the device is busy.

Depth: mistakes and interview rehearsal

Common mistakes, as a checklist (each links to the section that explains it)
MistakeWhat happensFix
torch.save(state, "ckpt.pt") over the last good checkpointthe old file is truncated at open; a crash or full disk before the end leaves nothing loadabletemporary name, fsync, rename, fsync the directory (6)
"It returned, so it is saved"the data sits dirty in the page cache for seconds; a node crash loses itfsync before you rely on it (4, 5)
fsync of the file but not of the directoryafter a crash the new name may be missing although the data is on diskopen the directory and fsync it after the rename
Retrying a failed fsyncthe retry can succeed with the data already droppedtreat the file as lost; write it again from memory
Ignoring the return of closeon NFS and with delayed allocation, write errors and ENOSPC can surface therelet f.close() raise; do not swallow OSError
DCP saves into the same directory every timeold shards truncated first, .metadata deleted before the new one is renamed inone directory per step; fsync the parent (10)
Millions of small files on a shared file systemmetadata servers saturate; cold reads one request eachshards; sequential reads; stage locally (2, 11)
Benchmarking a loader once, or twicethe first run times the disk, the second times RAMsay which; evict with posix_fadvise(DONTNEED) or measure both (3)
%util at 100% means the disk is saturatednot on devices that serve many requests at oncelook at throughput and latency against queue depth (1)
Assuming rename works everywhereobject stores have none; FUSE mounts may reject itnew keys plus a marker written last (9)
Deleting old checkpoints to free space while a process holds them openno space is freed until the process closes themlsof +L1; close or restart the holder (2)
Interview questions, with model answers (optional rehearsal)
What does write() guarantee when it returns, and what does fsync() add?
write guarantees the bytes are in the kernel's page cache: visible to every process on this machine, but only in memory. fsync returns when the file's data and metadata have reached stable storage, including flushing the device's volatile cache. It does not cover the directory entry naming the file; that needs an fsync of the directory.
How do you replace a file atomically and durably on Linux?
Write the new contents to a temporary file in the same directory, fsync it, rename it over the target (atomic for readers: they see old or new), then fsync the directory so the rename survives a crash. Same directory, because rename is atomic only within one file system. Alternatives: O_TMPFILE plus linkat for new names, renameat2(RENAME_EXCHANGE) to swap.
fsync versus fdatasync: when is fdatasync cheaper?
fdatasync skips metadata not needed to read the data back, chiefly timestamps. When a write changes only data (an overwrite of allocated blocks), fdatasync needs no journal commit, only the data write and a cache flush; fsync still has to log the new mtime. When the write extends the file, the size must be persisted, so both need the journal. Measured here on an overwrite: about 0.39 ms against 1.3 ms.
Explain ext4's data=ordered mode and delayed allocation, and how they interact.
Ordered mode journals metadata only but writes a file's data blocks before committing the metadata that points to them, so metadata never points at stale blocks. Delayed allocation picks blocks only at writeback; until then there is nothing to order, so a commit can record a new file's name with no data yet, which after a crash gives an empty file. ext4's auto_da_alloc forces allocation on rename-over-existing and truncate-then-close to cover the common unsafe patterns, but the portable fix is fsync.
A program writes 10 GB quickly and then its writes become very slow without any errors. What is happening?
Dirty throttling: once dirty page-cache data passes the dirty limits (for the machine, or for the program's cgroup writeback domain), balance_dirty_pages pauses the writer so it cannot outrun the device. /proc/PID/wchan shows balance_dirty_pages; Dirty and Writeback in /proc/meminfo stay high. Fixes: accept device speed, write in a background thread, use dirty_bytes limits, start writeback early with sync_file_range, or O_DIRECT.
What is readahead and when does it not help?
When the kernel sees sequential reads, it fetches the following pages before they are requested, growing the window (4, 8, 16, 32 pages here) up to read_ahead_kb, and triggers the next window asynchronously from a marked page. It does nothing for random access, which is why random small reads cost one device request each and why datasets are stored as sequential shards.
Why can O_DIRECT be slower than buffered I/O, and does it make writes durable?
It removes caching and readahead, so small or repeated reads each go to the device, and it imposes alignment. It does not flush the device cache or commit metadata, so durability still needs fdatasync. It wins for large streaming transfers you will not reuse, and when you manage your own cache.
How would you checkpoint a 64-rank job to a shared file system so that a crash at any moment leaves a loadable checkpoint?
New directory per step; each rank writes and fsyncs its shard; barrier; one rank writes the metadata (or a COMPLETE marker) to a temporary name, fsyncs, renames, fsyncs the step directory and the parent; keep the previous complete checkpoint until then; on restart pick the newest directory that has the marker and loads. On an object store, the same with new keys and a marker object written last.
A dataset reads at 3 GB/s in your benchmark but 300 MB/s in the real job. What do you check?
Whether the benchmark hit the page cache (it ran twice, or the file was just written); whether the job's access pattern is random (no readahead) or small-file (metadata); the queue depth (worker count); whether the job's container has an io.max limit or a smaller memory limit (less cache); and whether workers sit in state D (ps -eo stat,wchan).