download

Why can an updated config file end up empty after power loss?

Systems~10 minReviewed 3 Dec 2026Free · No sign-in

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.

  1. Why can direct writes tear data, and why can temp-file rename without fsync() leave a zero-byte file?
  2. Fix save_config with the full crash-safe sequence.
  3. Why must the temporary file live in the same directory as path?
"CODE · PYTHON"
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)
  1. "PAGE CACHE REORDERING"

    write() copies bytes into volatile OS page cache. Can the filesystem commit a metadata rename before the new file's data blocks reach disk?

  2. "SAME FILESYSTEM RENAME"

    rename(2) is atomic only inside one mounted filesystem. Putting tmp in /tmp fails with EXDEV if /tmp is a separate mount.

  3. "FLUSH FILE AND DIR"

    Create the temp file in path.parent, call flush() and os.fsync(fd), close it, call os.replace, then fsync the 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.

"SOLUTION · PYTHON"
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"))
"OUTPUT"
{"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:

  1. Wrong directory (/tmp). rename(2) only works inside one mounted filesystem. If /tmp is tmpfs or a separate partition, os.replace raises EXDEV (Invalid cross-device link). Putting the temp file in path.parent guarantees the same mount.
  2. 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 crash config.json exists with length 0.
  3. No directory fsync(). As fsync(2) warns, syncing the file flushes its inode and blocks, not the parent directory entry. Without fsync on path.parent, a crash right after rename can revert to the old config or drop a newly created file.
stepwhat it guarantees
Create temp file in path.parentSame 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()) without f.flush() first. Python's buffered file object can still hold bytes in userspace, so os.fsync flushes an empty kernel buffer.
  • Writing the temp file to /tmp or using a fixed temp name. /tmp breaks with EXDEV across mounts, and a fixed name races if two writers save at once.
  • Calling os.replace on Windows while the temp file handle is still open. Windows blocks renaming an open file, so close the handle before os.replace.
  • Assuming fsync() on the file also persists the rename. POSIX requires a separate fsync() on the parent directory descriptor to make the directory entry durable.

Follow-up questions

  • "What is the difference between fsync() and fdatasync()?" fsync() flushes file data plus all inode metadata such as mtime and atime. 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 rename for 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), call fdatasync() 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 →

Original OfferVibe question. fsync(2) · rename(2) · os.fsync · os.replace.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.