Video in progress
Describe the full protocol for updating an important file on disk (say, a local state snapshot) so it survives a power loss.
Write the new content to a temporary file, fsync that file, swap it in with an atomic rename, then fsync the directory itself. At startup you clean up leftover .tmp files and verify the content with a checksum.
📖 Answer
An atomic rename feels sufficient to many people. But after a crash there can be three bad outcomes: the file name is new but the content is zero length; the old file is gone and the new one is missing; or everything is fine. The reason is that the kernel writes the content and the directory entry to disk separately, in its own order.
The full sequence:
Path tmp = dir.resolve(name + ".tmp");
try (FileChannel ch = FileChannel.open(tmp, CREATE, WRITE, TRUNCATE_EXISTING)) {
ch.write(ByteBuffer.wrap(withChecksum(data)));
ch.force(true); // 1) the content is on disk
}
Files.move(tmp, dir.resolve(name), ATOMIC_MOVE, REPLACE_EXISTING); // 2) atomic swap
try (FileChannel d = FileChannel.open(dir, StandardOpenOption.READ)) {
d.force(true); // 3) the new name is on disk (works on Linux)
}
Without step 1, the rename can point to an empty file. On ext4, data=ordered softens this in many cases, but on XFS and other setups there is no guarantee. Without step 3, the rename itself can be lost. Opening a directory with FileChannel doesn't work on Windows, so this part has to be wrapped depending on the platform.
The recovery side is part of the protocol too:
- at startup, delete the
*.tmpfiles; - verify the content with a checksum; if it is corrupt, fall back to the previous snapshot (which is why keeping the last 2-3 copies is useful);
- if
fsyncfails, stop the process, because a later successfulfsyncdoes not bring back the lost pages.
This kind of code is rarely written and rarely tested. To be sure, you need a crash test: forcibly powering off the VM during a write, or dropping the disk's unwritten pages with tools like dm-flakey/LazyFS. If the amount of that work is scary, using an embedded storage like SQLite or RocksDB is often the better decision.
Sign up to mark studied questions and save your progress.