Python atomic configuration replacement: preserve the old file until validation succeeds
Prevent readers from seeing a partially written configuration using a same-directory temporary file and os.replace. Separate atomic visibility from crash durability and concurrent-writer control.
TL;DR: Validate the complete candidate first, write it to a temporary file on the destination filesystem, then replace the destination atomically. This protects readers from partial content; it does not provide a multi-file transaction, writer serialization or automatic power-loss durability.
Truncating the live file creates a failure window
Opening the current configuration with mode w truncates it before the candidate is fully written. A crash, serialization error or disk-full failure can leave readers with an empty or partial file. Building the replacement separately keeps the current file intact until the publication step.
Python documents os.replace and secure temporary-file creation in tempfile. Put the temporary file in the destination directory so replacement does not cross filesystem boundaries. This example assumes a trusted directory controlled by the operator.
A small Linux configuration writer
The function deliberately creates a restrictive file rather than preserving arbitrary destination ownership, mode or ACLs. Decide the required reader permissions before adapting it to a service.
import json
import os
import tempfile
from pathlib import Path
def publish_config(destination, port):
if type(port) is not int or not 1024 <= port <= 65535:
raise ValueError('port must be an integer from 1024 to 65535')
destination = Path(destination)
payload = json.dumps({'port': port}) + '\n'
name = None
try:
with tempfile.NamedTemporaryFile(
mode='w', encoding='utf-8', dir=destination.parent,
prefix='.candidate-', delete=False,
) as stream:
name = stream.name
stream.write(payload)
stream.flush()
os.fsync(stream.fileno())
os.replace(name, destination)
finally:
if name is not None and os.path.exists(name):
os.unlink(name)
with tempfile.TemporaryDirectory() as folder:
target = Path(folder) / 'service.json'
publish_config(target, 8080)
print(target.read_text().strip())
Expected output is {"port": 8080}. Passing True, a string or an out-of-range port must fail before writing. The exact type check avoids accepting a Boolean as an integer configuration value.
Name what atomic replacement does not do
| Requirement | Supplied by this example? | Additional design |
|---|---|---|
| Complete file visible at publication | Yes, on supported same-filesystem replacement | Verify target filesystem semantics |
| Invalid candidate preserves old file | Yes | Test the actual schema and values |
| Survive a sudden power loss | Not fully established | Directory synchronization and filesystem guarantees |
| Two writers cannot overwrite each other | No | Lock, generation check or single writer |
| Service has loaded the new config | No | Reload protocol and application verification |
File fsync flushes the temporary file's data, but durability of the directory entry after replacement has its own platform/filesystem requirements. Readers that already opened the old file can continue reading that object; new opens see the replacement. This behavior is useful and should be understood when a service caches configuration.
Test an initial valid write, an invalid update preserving byte-identical old content, a valid replacement and a failed replacement with temporary-file cleanup. Use a disposable directory. Then define how the actual service validates/reloads the candidate and how an operator restores the previous known-good version if application verification fails.
Self-check: two writers each use os.replace correctly. Can one still overwrite the other's update? Yes. Each replacement can be atomic while the overall read-modify-write sequence loses an update.
Practice a damaged live configuration.