Sub topic 6
Writing Checkpoints Atomically
This chapter assumes you can read Python and JSON, and that you know what a checkpoint is from the earlier chapters: a small file that records which steps of a task are finished. Here you will learn how to write that file so a crash cannot corrupt it.
The problem: a crash in the middle of a write
A checkpoint exists to survive interruptions. The moment you update it is also the moment an interruption does the most damage. The obvious way to save state looks like this:
with open("checkpoint.json", "w") as f:
json.dump(state, f)Opening a file in "w" mode truncates it to zero bytes immediately. If the process is killed, the disk fills up, or the machine loses power before json.dump finishes, the file holds a partial JSON document or nothing at all. The old checkpoint is gone and the new one is incomplete. The task has lost its memory at exactly the point where it needed it.
The failure is also hard to notice. A truncated file raises JSONDecodeError on the next start, and a script that treats "cannot read" as "no checkpoint" will quietly start the task from the beginning. That can repeat side effects such as uploads or emails.
What "atomic" means here
An operation is atomic if an observer sees either the state before it or the state after it, and never anything in between. For checkpoints the goal is simple: after any crash, the file at the checkpoint path is either the complete old checkpoint or the complete new one.
The file system gives you one primitive that works this way: renaming a file onto an existing path. On POSIX systems, rename within one file system replaces the target in a single step. Python exposes this as os.replace. You build atomic writes from it:
- Write the new content to a temporary file in the same directory.
- Force that content to disk.
- Rename the temporary file over the real checkpoint.
The real file is never opened for writing, so it can never be half-written.
The implementation
This version is the one from the plan, with a directory sync added at the end. The sync is explained below.
import json
import os
import tempfile
def save_checkpoint(path, state):
directory = os.path.dirname(os.path.abspath(path))
fd, tmp_path = tempfile.mkstemp(dir=directory, suffix=".tmp")
try:
with os.fdopen(fd, "w") as f:
json.dump(state, f, indent=2)
f.flush()
os.fsync(f.fileno())
os.replace(tmp_path, path)
except BaseException:
if os.path.exists(tmp_path):
os.unlink(tmp_path)
raise
fsync_directory(directory)
def fsync_directory(directory):
if os.name == "nt":
return # Windows cannot open a directory this way
fd = os.open(directory, os.O_RDONLY)
try:
os.fsync(fd)
finally:
os.close(fd)
def load_checkpoint(path):
try:
with open(path) as f:
return json.load(f)
except FileNotFoundError:
return NoneWhy each part is there
| Line or call | What it protects against |
|---|---|
| `mkstemp(dir=directory)` | A rename across file systems is not atomic. Putting the temp file beside the target keeps both on the same file system. |
| `mkstemp` (unique name) | Two writers never share one temp file, and a leftover temp file from an old crash never collides with a new one. |
| `f.flush()` | Python buffers writes. Without a flush, the data may still be in your process when `fsync` runs. |
| `os.fsync(f.fileno())` | The operating system also buffers. `fsync` asks it to push the file's data to the storage device before you continue. |
| `os.replace` | Swaps the new file in as one step, and overwrites an existing target on both POSIX and Windows. `os.rename` fails on Windows if the target exists. |
| `except BaseException` | Cleans up the temp file on errors and on `KeyboardInterrupt`, then re-raises so the caller still sees the failure. |
| `fsync_directory` | The rename itself is a change to the directory. Syncing the directory makes the rename durable. |
The order matters. If you rename before the data is synced, a power loss can leave the new name pointing at a file whose contents never reached the disk. Some file systems then show a zero-length checkpoint. Sync first, rename second.
Seeing it work
This script is complete and runs as written. It writes a good checkpoint, then tries to save a state that cannot be serialized. It does this once with the atomic function and once with the naive one.
import json
import os
import tempfile
def naive_save(path, state):
with open(path, "w") as f:
json.dump(state, f)
def atomic_save(path, state):
directory = os.path.dirname(os.path.abspath(path))
fd, tmp_path = tempfile.mkstemp(dir=directory, suffix=".tmp")
try:
with os.fdopen(fd, "w") as f:
json.dump(state, f)
f.flush()
os.fsync(f.fileno())
os.replace(tmp_path, path)
except BaseException:
if os.path.exists(tmp_path):
os.unlink(tmp_path)
raise
def load(path):
with open(path) as f:
return json.load(f)
with tempfile.TemporaryDirectory() as d:
path = os.path.join(d, "checkpoint.json")
good = {"completed": ["fetch"]}
bad = {"completed": ["fetch", "transform"], "oops": object()}
atomic_save(path, good)
try:
atomic_save(path, bad)
except TypeError as e:
print("atomic save failed:", e)
print("after atomic:", load(path))
print("files:", os.listdir(d))
try:
naive_save(path, bad)
except TypeError:
pass
try:
load(path)
except json.JSONDecodeError:
print("after naive: checkpoint is corrupt")The atomic save raises, but the old checkpoint still loads and no temp file remains. The naive save raises too, and it leaves a truncated file that no longer parses.
Edge cases and limits
Same file system only
os.replace is atomic only when source and target are on the same file system. This is why the temp file goes in the checkpoint's own directory. Writing to /tmp and renaming into your project directory can fail with an error or silently fall back to copy-and-delete, which is not atomic.
Network and synced file systems
Atomic rename depends on the file system's guarantees. Local file systems such as ext4, XFS, APFS, and NTFS provide it. NFS, SMB shares, and cloud-sync folders can behave differently: a rename may be visible to other machines late, or a sync client may upload the temp file as a separate file. If checkpoints must live on shared storage, check its documented rename semantics, or keep the checkpoint on local disk and copy it out afterward.
File permissions
mkstemp creates files with mode 0600, readable only by the owner. After os.replace, the checkpoint has that mode, even if the old one was more open. If another account or agent must read it, call os.chmod(tmp_path, 0o644) before the rename.
Stray temp files
A crash between creating and renaming leaves a .tmp file behind. These are harmless, because nothing reads them, but they accumulate. A startup routine can delete *.tmp files in the checkpoint directory. Do this only when you know no other writer is active, or you may delete another process's file in progress.
Cost
fsync is slow compared with a plain write, often milliseconds on an SSD and more on a spinning disk. Checkpointing after each step of a task that takes minutes is cheap. Checkpointing inside a tight loop of thousands of iterations is not. Save after meaningful units of work, not after every row.
Large state
Every save rewrites the whole file. If state grows to many megabytes, consider keeping the checkpoint small, with step names and cursors, and storing bulk output in separate files that are themselves written atomically and listed in the checkpoint.
What atomic writes do not solve
Atomic replacement protects one file against torn writes. It does not decide what the checkpoint says, and it does not coordinate several writers.
- Wrong content. If you save the checkpoint before a step's side effect finishes, or after it but without recording it, a crash still leaves the checkpoint disagreeing with reality. The resume chapters cover this.
- Lost updates. Two processes that each read the checkpoint, change it, and replace it will each produce a valid file, and one change disappears. That needs locking, covered in the chapter on conflicting writers.
- Corruption after the fact. Disk faults and manual edits can still damage a file. For important state, keep the previous checkpoint as
checkpoint.json.bakby hard-linking or copying it before the replace, so you have a fallback.
Summary of the pattern
- Never open the real checkpoint for writing.
- Create the temp file in the same directory.
- Write, flush, and
fsyncthe temp file. - Rename it into place with
os.replace. - Sync the directory where the platform allows it.
- Remove the temp file on any failure and re-raise.
Exercise
In save_checkpoint, a developer moves the os.fsync call to after os.replace to "save time before the swap". The program is later killed by a power loss just after the replace. What can the checkpoint file contain, and why?
Show answer
It can be empty or contain only part of the new JSON. The rename can reach the disk before the file's data does, so the checkpoint name points at a file whose contents were never written out. fsync must run on the temp file before os.replace, so the data is durable before the new name becomes visible.
Exercise
You change the code to create the temp file with tempfile.mkstemp(dir="/tmp") while the checkpoint lives in /home/user/job/. Tests pass on your laptop, but production fails intermittently. Give the most likely cause and the fix.
Show answer
/tmp and the job directory may be on different file systems. os.replace across file systems raises an error, and an equivalent copy-and-delete is not atomic. The fix is to create the temp file in the checkpoint's own directory with dir=os.path.dirname(os.path.abspath(path)).
Exercise
Two worker processes both call load_checkpoint, append their own step name to completed, and call save_checkpoint. Every save uses the atomic pattern, yet one worker's step is sometimes missing from the final file. Why does atomic writing not prevent this, and what kind of fix is needed?
Show answer
Each save is a complete, valid file, but the second worker overwrites the first worker's update because both started from the same old state. Atomic replacement prevents torn files, not lost updates. You need coordination: a lock around the read-modify-write cycle, or a single writer that owns the checkpoint.