Crash-safe file writes on dedicated servers
A configuration generator truncates an existing file before writing its replacement. If the process exits at just the wrong moment, the next startup may read an empty file. Task checkpoints, service address mappings, and small state files on dedicated servers face the same risk. A file that parses successfully is not proof that its latest version has reached durable storage, and a successful write does not mean the directory entry has been synchronized. This article uses Python 3 to build a verifiable write procedure on a local file system under Ubuntu Server 24.04 LTS. All operations stay within a separate test directory.
1. Define the old version, the new version, and the success boundary
The goal is not to “finish as much of the write as possible.” It is to ensure that readers reopening the target path receive either the complete old version or the complete new version, never a mixture of the two. Readers that already have the old file open can continue reading the old inode. Atomic replacement does not automatically redirect existing file descriptors to the new version.
Acceptance testing must separate three questions: Is the content complete? Has the path switched to the new file? Has the operation reached its durability boundary? Process-level tests can demonstrate the first two. The third also depends on the file system and storage stack.
Atomicity determines “which version is visible.” Durability determines “which version survives a failure.” Forcibly terminating a process is not the same as cutting power to the device.
The discussion below applies only to a single writer, a trusted directory, and regular local files. Do not apply this procedure directly to network file systems, moves across file systems, or transactions involving multiple files.
2. Create a test workspace away from production files
Run the following commands as a regular user to confirm that Python 3 is available and create a randomly named working directory. Do not change the target to a configuration file currently in use, and do not simulate failures by rebooting a production machine.
python3 --version
work=$(mktemp -d)
chmod 700 "$work"
cd "$work"
printf '%s\n' '{"generation": 1, "status": "old"}' > state.json
python3 -m json.tool state.json
Keep track of the working directory path in the current terminal. All subsequent scripts and results belong here. The test files must reside on the same local file system. In particular, do not create the temporary file on another mount point and then move it back.
Before deploying this approach in production, also record the file's owner, permissions, extended attributes, and how readers access it. The example creates a new file with permissions of 0600. It does not automatically inherit the old file's ACLs, security labels, or hard-link relationships, so it must not replace an existing configuration without prior checks.
3. Synchronize the file and its parent directory in order
Save the following as durable_write.py in the working directory. The script finishes serialization first, then creates a temporary file in the target directory. It synchronizes the data before replacing the target, then synchronizes the parent directory. The two early exit points are for testing only.
import json
import os
from pathlib import Path
import sys
import tempfile
target = Path("state.json").resolve()
stage = sys.argv[1] if len(sys.argv) > 1 else "complete"
if stage not in {"complete", "before-replace", "after-replace"}:
raise SystemExit("Invalid stage")
payload = (
json.dumps({"generation": 2, "status": "new"}, sort_keys=True) + "\n"
).encode("utf-8")
fd, name = tempfile.mkstemp(prefix=".state-", dir=target.parent)
temporary = Path(name)
try:
with os.fdopen(fd, "wb") as stream:
os.fchmod(stream.fileno(), 0o600)
stream.write(payload)
stream.flush()
os.fsync(stream.fileno())
if stage == "before-replace":
os._exit(91)
os.replace(temporary, target)
if stage == "after-replace":
os._exit(92)
directory_fd = os.open(
target.parent, os.O_RDONLY | os.O_DIRECTORY
)
try:
os.fsync(directory_fd)
finally:
os.close(directory_fd)
finally:
temporary.unlink(missing_ok=True)
flush() passes Python's buffered data to the operating system; it does not make that data durable. Calling fsync() on the file requests synchronization of its data and associated metadata. os.replace() switches the target path within the same file system, and fsync() on the parent directory then synchronizes the directory entry change.
Every synchronization error must be reported. Do not catch an exception and then return success, and do not proceed to replace the old version if file synchronization fails. If the environment does not support directory synchronization, explicitly treat the implementation's durability contract as unmet rather than silently skipping that step.
4. Inject process exits before and after replacement
An exit before replacement must preserve the old version
Restore the old version before each run so that the previous result does not affect the test. The failure exit code is expected evidence and must not be treated by a pipeline as normal completion.
printf '%s\n' '{"generation": 1, "status": "old"}' > state.json
python3 durable_write.py before-replace
rc=$?
printf 'exit=%s\n' "$rc"
python3 -c 'import json; assert json.load(open("state.json"))["generation"] == 1'
find . -maxdepth 1 -type f -name '.state-*' -print
The expected exit code is 91, and the target should still contain the first generation. Because os._exit() does not run cleanup logic, a temporary file remains. This is exactly the state to inspect; the presence of a temporary file must not be mistaken for damage to the target.
An exit after replacement must leave the complete new version readable
printf '%s\n' '{"generation": 1, "status": "old"}' > state.json
python3 durable_write.py after-replace
rc=$?
printf 'exit=%s\n' "$rc"
python3 -c 'import json; assert json.load(open("state.json")) == {"generation": 2, "status": "new"}'
The expected exit code is 92, and the complete second generation should be readable in the currently running system. However, the script has not yet synchronized the parent directory. This result does not prove that the second generation would survive a power failure.
Finally, restore the old version again and run python3 durable_write.py complete. Require an exit code of zero and use the same assertion to verify the new version. Normal completion means only that the synchronization calls succeeded on this machine. It does not justify a promise that no data can be lost under any hardware failure.
5. Handle uncertain commits and concurrent overwrites
Directory synchronization can still fail after replacement succeeds. In that case, the caller receives a failure even though the target already contains the new version. Simply retrying an operation such as “add one to the balance” or “increment the sequence number” could apply it twice. Include an operation identifier or target version in the content. During recovery, check the actual version before deciding whether to retry.
Atomic replacement does not provide concurrent transactions either. If two writers both calculate their next version from the first generation, the last replacement to complete may overwrite the other result. A lock must cover the entire read, compute, and replace sequence, not just the final call. More complex state is better handled by transactional storage.
Readers should read the entire file in one pass after opening it, then parse the result. Avoid opening the same path twice and combining content from the two reads. Even if each file in a multi-file configuration is replaced atomically, readers may still see different generations across files. An additional version-publication protocol is needed.
6. Include acceptance results in the application handoff
The handoff record should include at least the runtime environment, file system type, script version, exit codes for all three stages, and the results of parsing the target file. If actual power-loss behavior must be verified, use a separate disposable environment with its own recovery plan. Do not use production data disks for fault injection.
Leftover temporary files may be removed only after confirming that no writer is active. Do not indiscriminately delete every object with a matching filename prefix. Recovery logic must not automatically select the “newest temporary file” either: that file may not have finished synchronization or application-level validation.
The final checklist is: create the temporary file in the same directory, synchronize it after writing is complete, replace the target atomically, synchronize the parent directory, propagate errors, and make the version verifiable. This protects the integrity of single-file updates. It does not replace off-site backups or application transactions. File writes have practical acceptance criteria only when both the success boundary and the recovery steps after failure are clearly defined.
Frequently asked questions
Does os.replace guarantee that a file survives a power loss?
No. Atomic replacement addresses visibility of the path change. Typically, the temporary file must be synced before replacement and the parent directory synced afterward. Durability also depends on the filesystem and storage stack honoring those operations.
Can terminating the process prove power-loss safety?
No. It checks file states at specific program stages while the kernel and device keep running. Power-loss durability requires separate storage fault tests in an isolated environment.
Does atomic replacement prevent lost updates from concurrent writers?
No. It does not merge concurrent changes, and the last replacement can overwrite an earlier result. Use a single writer, a lock covering the full read-modify-write transaction, or transactional storage with version checks.
AMD EPYC 7543P Dedicated Server
From $468/month. Total due = monthly total × number of months.