DEV Community

Atomic State Files in Python: tmp + os.replace

A trading bot wakes up every 15 minutes, loads state.json, reconciles positions, and writes the file back.

One afternoon the process is killed mid-write - or the host loses power at exactly the wrong millisecond. The next run opens state.json, json.load raises JSONDecodeError on a truncated payload, the bot crashes, and a supervisor restarts it. It crashes again.

Meanwhile every position the bot was tracking has effectively become orphaned cash: the exchange still holds the assets, but the bot has no record of entry prices, stop levels, or sizing, so it cannot manage or exit them.

The root cause is not exotic. open(path, 'w') truncates the file to zero bytes before a single byte of new content is written. Any interruption between truncation and the final write() leaves you with an empty or half-written file. There is a window - small, but hit often enough across thousands of restarts - where the on-disk state is invalid.

The fix is the standard durable-write pattern: write the complete payload to a sibling temp file in the same directory, flush and fsync it, then atomically rename it over the target with os.replace. Pair that with a loader that quarantines corrupt files instead of crashing forever.

Why open(path, 'w') is unsafe

Three distinct failure modes:

  • Truncate-then-write. The file is emptied the moment you open it for writing. A crash before the write completes leaves an empty file.
  • Partial writes. write() may not flush everything to disk immediately; the OS buffers it. A power cut can persist some pages and not others.
  • No atomicity guarantee. Even a completed write() followed by a crash during metadata update can leave the file in an inconsistent state on some filesystems.

If you serialize with json.dump(obj, f) directly to the target, you also have a window where the JSON is syntactically invalid - the closing brace isn't there yet. Anything reading concurrently sees garbage.

The pattern: temp file + fsync + os.replace

import json
import os
import tempfile

def write_state(path: str, state: dict) -> None:
    directory = os.path.dirname(os.path.abspath(path))
    os.makedirs(directory, exist_ok=True)
    fd, tmp_path = tempfile.mkstemp(prefix=".state-", suffix=".tmp", dir=directory)
    try:
        with os.fdopen(fd, "w", encoding="utf-8") as f:
            json.dump(state, f, indent=2, sort_keys=True)
            f.flush()
            os.fsync(f.fileno())
        os.replace(tmp_path, path)
    except BaseException:
        try:
            os.unlink(tmp_path)
        except FileNotFoundError:
            pass
        raise

Key details, in order of importance

The temp file must live in the same directory.

os.replace is atomic only within a single filesystem. If you create the temp file in /tmp (often a separate tmpfs or mount) and the state file lives on /var/lib/bot, the rename becomes a copy-then-delete, which is not atomic and can leave a partial target. tempfile.mkstemp(dir=directory) guarantees the temp file is a sibling of the target, so the rename is a pure directory-entry swap on the same device.

This also matters on Windows: os.replace maps to MoveFileEx with MOVEFILE_REPLACE_EXISTING, which has been atomic for same-volume renames since Python 3.3. Cross-volume it degrades to a copy. Same directory, same volume, always.

flush() then fsync().

flush() pushes Python's buffer into the OS. fsync() pushes the OS buffer to the storage device. Without fsync, a power loss can leave the temp file's contents in the page cache while the rename (a metadata operation) may or may not have hit disk. The ordering you want is: data durable before the rename is visible.

On POSIX you'd additionally fsync the directory to make the rename itself durable, but for a state file rewritten every 15 minutes the cost/benefit rarely justifies it. The fsync on the file is the one that prevents the "empty file after power cut" scenario.

os.replace, not os.rename.

os.rename fails on Windows if the destination exists. os.replace overwrites atomically on both platforms. Use it unconditionally.

Hide the temp file.

The .state- prefix keeps the temp file out of casual ls output and, more importantly, out of globs like *.json that other parts of your pipeline might use. If your loader scans a directory for state files, a leftover .tmp from a crashed write should not be picked up.

The quarantine loader

An atomic writer eliminates the common corruption path, but it cannot fix a file that is already corrupt - from a previous version of the code, a manual edit, a bad disk, or a write from some other process. The loader must be defensive: on JSONDecodeError, move the bad file aside with a timestamp, log loudly, and rebuild from defaults rather than crashing on every restart.

import json
import logging
import os
import time

log = logging.getLogger(__name__)

DEFAULT_STATE = {
    "version": 2,
    "positions": {},
    "last_reconcile": None,
    "cash_buffer": 0.0,
}

def load_state(path: str) -> dict:
    if not os.path.exists(path):
        return dict(DEFAULT_STATE)
    try:
        with open(path, "r", encoding="utf-8") as f:
            loaded = json.load(f)
    except (json.JSONDecodeError, UnicodeDecodeError) as exc:
        bad_path = f"{path}.{int(time.time())}.bad"
        log.error(
            "state file %s is corrupt (%s); quarantining to %s and "
            "rebuilding from defaults",
            path,
            exc,
            bad_path,
        )
        os.replace(path, bad_path)
        return dict(DEFAULT_STATE)
    return _merge_defaults(loaded, DEFAULT_STATE)

def _merge_defaults(loaded: dict, defaults: dict) -> dict:
    merged = dict(defaults)
    merged.update(loaded)
    return merged

The quarantine step is what turns a fatal error into a recoverable one. The bot starts from a clean default state, logs the event, and continues. An operator can later inspect the .bad file to see what was lost and reconcile manually. Crashing in a restart loop, by contrast, guarantees you never get to that inspection.

Note that os.replace is used for the quarantine rename too - cheap, atomic, and it means a crash during quarantine leaves either the original or the .bad file, never a half-moved one.

Schema evolution: the load-merge pattern

State files outlive code versions. You add a field, ship the new build, and the first load reads a file written by the old build that doesn't have it. If your code does state["new_field"] you get a KeyError and the same restart loop.

The _merge_defaults helper above handles the common case - top-level keys missing from the loaded state get backfilled from DEFAULT_STATE. For nested structures, recurse:

def _merge_defaults(loaded, defaults):
    if not isinstance(defaults, dict) or not isinstance(loaded, dict):
        return loaded if loaded is not None else defaults
    merged = dict(defaults)
    for key, value in loaded.items():
        if key in defaults and isinstance(defaults[key], dict):
            merged[key] = _merge_defaults(value, defaults[key])
        else:
            merged[key] = value
    return merged

This gives you forward-compatible reads without a migration step for additive changes. For breaking changes - renaming a field, changing a type - bump version and branch on it in the loader. Keep the default state's version in sync with the code that writes it.

Why pretty-print

json.dump(..., indent=2, sort_keys=True) costs a few hundred bytes and buys you a great deal during a postmortem. When a position goes sideways at 03:00 and you're cat-ing the state file from a backup, a single-line 40 KB blob is effectively unreadable.

Indented, sorted output diffs cleanly against yesterday's state, so diff state.json state.json.bad immediately shows what changed before the corruption. Sort keys for the same reason: it makes diffs stable across writes. Without it, dict iteration order (insertion order in modern Python) can shuffle after a load-merge and produce noisy diffs that hide the real change.

The 15-minute write interval means the extra serialization time is irrelevant. Optimize for the human reading the file at 3 a.m., not for the writer.

Putting it together

The full cycle:

state = load_state(STATE_PATH)
# ... mutate state: update positions, record reconcile time ...
write_state(STATE_PATH, state)

Failure behavior:

  • Crash during write_state: the target file is untouched. The leftover .tmp is harmless and gets overwritten next run (or cleaned up by the except branch if the exception propagates). On next start, load_state reads the previous good state.
  • Power cut during fsync: the target is still the old file. The temp file may contain garbage; it's ignored.
  • Power cut between fsync and os.replace: same - old file intact.
  • Power cut during os.replace: the rename is atomic at the filesystem level; you get either the old or the new file, never a mix.
  • Corrupt target from any other cause: load_state quarantines it and rebuilds from defaults.

The one thing this pattern does not protect against is a bug that writes valid but wrong state. That's a logic problem, not a durability problem, and the quarantine loader won't help. Version your state, log every transition, and keep the .bad backups around long enough to diagnose.

A note on directory durability

If you want the rename itself to survive a power cut on POSIX, fsync the parent directory after os.replace:

dir_fd = os.open(directory, os.O_RDONLY)
try:
    os.fsync(dir_fd)
finally:
    os.close(dir_fd)

This forces the directory entry update to disk. It's cheap on most filesystems and worth adding if your state file is the only record of open positions. On Windows, directory handles can't be opened this way in the same manner, so skip it - os.replace plus the file fsync is the practical ceiling there.

The pattern is small, boring, and eliminates an entire class of incidents. Every state file your bot writes should go through it.

More notes like this ship every week on this site.

Daily Picks

The following pairs are selected from the multi-timeframe trend scanner (Gate.io futures) and are for technical-analysis study only - not investment advice. Data updated: 2026-11-23 08:46:19

Long Pair Signal Price Take Profit Stop Loss R/R BULLA 短平快做多 $0.0193 $0.0199 $0.0188 1:1.2 1 picks selected. Scanner runs every 15 minutes.

Read on DEV Community ↗ ← Back to News

Comments

No comments yet. Start the discussion.