Linux
04 Sep 2026
8 min read
Write Files Atomically on Linux with rename and fsync
Updating a small file looks simple: open it, truncate it, write the new contents, and close it. That works when nothing interrupts the write. The failure mode appears when a process crashes, the machine loses power, or another process reads the file while it is being rewritten. A reader can observe an empty or partially written file, and a crash can leave the pathname referring to incomplete data. For configuration files, state snapshots, generated metadata, and similar single-file updates, a better pattern is to write a complete replacement beside the original file and then rename it into place.