Why can an updated config file end up empty after power loss?
Question
A daemon overwrote config.json in place with open(path, "wb") and hit half-written files after power cuts. A teammate switched to writing a temporary file and calling os.replace(tmp, path) without fsync(), yet after another crash config.json came back zero bytes.
- Why can direct writes tear data, and why can temp-file
renamewithoutfsync()leave a zero-byte file? - Fix
save_configwith the full crash-safe sequence. - Why must the temporary file live in the same directory as
path?
import os from pathlib import Path def save_config(path: Path, data: bytes) -> None: tmp = Path("/tmp/config.json.tmp") with open(tmp, "wb") as fh: fh.write(data) os.replace(tmp, path)
Show hints (3)
- "PAGE CACHE REORDERING"
write()copies bytes into volatile OS page cache. Can the filesystem commit a metadatarenamebefore the new file's data blocks reach disk? - "SAME FILESYSTEM RENAME"
rename(2)is atomic only inside one mounted filesystem. Puttingtmpin/tmpfails withEXDEVif/tmpis a separate mount. - "FLUSH FILE AND DIR"
Create the temp file in
path.parent, callflush()andos.fsync(fd), close it, callos.replace, thenfsyncthe parent directory on POSIX.
Show checked explanation
Overwriting in place truncates config.json first, so a crash mid-write leaves a torn or empty file. Without fsync(), the filesystem can journal the rename before flushing the temp file's bytes from page cache, leaving a zero-byte file. Create the temp file in path.parent, flush() + os.fsync() it, close it, call os.replace, then fsync the parent directory on POSIX.
import os from pathlib import Path import tempfile def save_config(path: Path, data: bytes) -> None: with tempfile.NamedTemporaryFile(dir=path.parent, delete=False) as f: f.write(data) f.flush() os.fsync(f.fileno()) os.replace(f.name, path) if hasattr(os, "O_DIRECTORY"): dfd = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY) try: os.fsync(dfd) finally: os.close(dfd) with tempfile.TemporaryDirectory() as d: cfg = Path(d, "config.json") save_config(cfg, b'{"port":8080}') print(cfg.read_text("utf-8"))
{"port":8080}Ran the atomic temp-file, os.fsync, and os.replace solution and call-order checks on CPython 3.12.10 (Windows x64); POSIX fsync(2) and rename(2) rules checked against man7.org. Checked by an editor other than the author.
Walkthrough
Opening config.json with "wb" truncates the file to zero bytes before writing anything. If power fails before the new bytes flush, you lose both the old and new configs.
Moving to a temp file plus os.replace fixes concurrent readers, because POSIX rename(2) swaps the directory pointer atomically. Yet it still breaks on power loss for three reasons in the starter:
- Wrong directory (
/tmp).rename(2)only works inside one mounted filesystem. If/tmpistmpfsor a separate partition,os.replaceraisesEXDEV(Invalid cross-device link). Putting the temp file inpath.parentguarantees the same mount. - No file
fsync().write()only lands in Python's userspace buffer and the OS page cache. Filesystems can flush metadata (the new inode and rename) before flushing data blocks, so after a crashconfig.jsonexists with length 0. - No directory
fsync(). Asfsync(2)warns, syncing the file flushes its inode and blocks, not the parent directory entry. Withoutfsynconpath.parent, a crash right afterrenamecan revert to the old config or drop a newly created file.
| step | what it guarantees |
|---|---|
Create temp file in path.parent | Same mount, unique name, old target untouched |
flush() then os.fsync(fd) | Userspace buffer and kernel page cache reach disk |
Close then os.replace(tmp, path) | Atomic swap; readers see only old or complete new file |
fsync(parent_dir_fd) (POSIX) | Updated directory entry itself survives power loss |
On Windows, os.fsync calls _commit (FlushFileBuffers) and os.replace swaps a closed target file. Unlike POSIX, Windows does not allow os.open on a directory for fsync, hence the O_DIRECTORY guard. In production, wrap the write in try/except to unlink orphaned temp files on error.
Common mistakes
- Calling
os.fsync(f.fileno())withoutf.flush()first. Python's buffered file object can still hold bytes in userspace, soos.fsyncflushes an empty kernel buffer. - Writing the temp file to
/tmpor using a fixed temp name./tmpbreaks withEXDEVacross mounts, and a fixed name races if two writers save at once. - Calling
os.replaceon Windows while the temp file handle is still open. Windows blocks renaming an open file, so close the handle beforeos.replace. - Assuming
fsync()on the file also persists therename. POSIX requires a separatefsync()on the parent directory descriptor to make the directory entry durable.
Follow-up questions
- "What is the difference between
fsync()andfdatasync()?"fsync()flushes file data plus all inode metadata such asmtimeandatime.fdatasync()flushes data and only the metadata needed to read it back (like file size), saving extra disk I/O for append-only logs. - "Why don't databases use temp-file plus
renamefor every row update?" Rewriting a whole multi-gigabyte file per update is far too slow. Databases append small records to a write-ahead log (WAL), callfdatasync()on commit, and flush data pages asynchronously. - "Can a disk lie to
fsync()even when your code does every step right?" Yes. Consumer drives or misconfigured write-back caches can acknowledge flushes while holding bytes in volatile drive RAM. Reliable storage needs battery-backed caches or write barriers that honor cache-flush commands.
What a strong answer covers
Explains in-place truncation, page-cache metadata reordering, and EXDEV across mounts. Writes a same-directory temp file, calls flush() and fsync(), closes and runs os.replace, fsyncs the parent directory on POSIX, and notes the Windows handle rule.
Open in interactive practice deck →