Skip to content

About

Crash-safe, race-free file writes for Go — TOCTOU protection via fingerprint verification, cross-platform file locking, atomic rename, and fsync for crash durability.

Topics

Resources

Contributing

Security policy

Stars

2 stars

Watchers

0 watching

Forks

Latest commit

 

History

265 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

go-atomic-write: the atomic swap

go-atomic-write

Crash-safe, race-free file writes for Go.

Go Reference

License: MIT

CI

Documentation · API Reference


Every os.WriteFile call has three failure modes that silently corrupt data: a concurrent writer overwrites you, a crash leaves a half-written file, and two writers interleave their bytes. This library eliminates all three — a fingerprint check turns a lost update into an error, a single rename means the file is never partially written, and fsync keeps the write after a power loss.

Why?

Writing a file safely is harder than it looks:

  • TOCTOU races — between reading and writing, another process can modify the file. You overwrite their changes without knowing.
  • Partial writes — a crash mid-write leaves a corrupt, half-written file. The old content is gone.
  • Concurrent writers — two processes write the same file. Bytes interleave. Data is lost.

os.WriteFile handles none of these. A naive write-to-temp-then-rename handles one. go-atomic-write handles all three.

Comparison

Approach TOCTOU-safe Crash-durable Concurrent-safe Dependencies
os.WriteFile None
DIY write + rename Partial None
go-atomic-write ✓ ✓ ✓ 2 (xxhash, flock)

How it works

  1. Fingerprint — compute an xxhash64 digest when you read the file
  2. Write to unique .tmp — stage new content in a uniquely-named temp file (prevents concurrent writers from corrupting each other)
  3. fsync — flush the temp file to disk for crash durability
  4. Lock + verify — acquire an exclusive file lock (flock on Unix, LockFileEx on Windows), re-read the file, and verify the fingerprint still matches
  5. Atomic rename — rename the temp file to the target (single rename(2) on POSIX, MoveFileEx on Windows)
  6. fsync directory — sync the directory entry to make the rename durable (POSIX)

If the fingerprint doesn't match, WriteVerified returns ErrConcurrentModification — the caller should re-read and retry.

Use cases

  • Configuration files — read-modify-write cycles where another process might edit the same config
  • State and checkpoint files — database state, job progress, session stores — corruption means data loss
  • Log and data rotation — append or replace files without readers seeing partial content
  • Cache invalidation — write-through caches that must never serve a half-written file
  • CI/CD tooling — generated manifests, lock files, build artifacts written under concurrent pipelines

Install

go get github.com/larsartmann/go-atomic-write

Usage

package main

import (
    "fmt"
    "os"

    atomicwrite "github.com/larsartmann/go-atomic-write"
)

func main() {
    path := "/path/to/config.json"

    // Read + fingerprint
    data, err := os.ReadFile(path)
    if err != nil && !os.IsNotExist(err) {
        panic(err)
    }
    fp := atomicwrite.FingerprintFromBytes(data)

    // Modify
    newData := []byte(`{"updated": true}`)

    // Write with TOCTOU protection
    err = atomicwrite.WriteVerified(path, newData, fp)
    if err != nil {
        panic(err)
    }
}

First write (no existing file)

Use Write when there is no prior content to protect (first write, temp files):

err := atomicwrite.Write(path, data)

Or pass a zero-value Fingerprint to WriteVerified if you need concurrent-creation detection (the write fails if another process creates the file first):

err := atomicwrite.WriteVerified(path, data, atomicwrite.Fingerprint{})

Write only if content changed

Use WriteIfChanged when re-running a tool should not produce spurious diffs (config writers, code generators, lock-file updaters):

changed, err := atomicwrite.WriteIfChanged(path, newData)
if err != nil {
    panic(err)
}
if changed {
    fmt.Println("config updated")
} else {
    fmt.Println("config already up to date")
}

No content change means no file mutation, no mtime bump, no file-watcher trigger.

Detecting concurrent modification

err := atomicwrite.WriteVerified(path, newData, fp)
if errors.Is(err, atomicwrite.ErrConcurrentModification) {
    // Re-read the file, merge changes, and retry
}

Streaming large content with WriteFunc

When content is large or produced incrementally (JSON encoders, diagram renderers), use WriteFunc to stream via a callback instead of holding the full payload in memory:

err := atomicwrite.WriteFuncVerified(path, func(w io.Writer) error {
    enc := json.NewEncoder(w)
    return enc.Encode(largeObject)
}, fp)

For streaming without TOCTOU verification, use WriteFunc(path, fn).

Fingerprinting a file

// From raw bytes
fp := atomicwrite.FingerprintFromBytes([]byte("content"))

// From a file path (returns zero Fingerprint if file doesn't exist)
fp, err := atomicwrite.FingerprintFile(path)

// Check if it represents no prior file
if fp.IsZero() {
    // First run — no file existed
}

// Check if content matches
if fp.Matches(currentData) {
    // File hasn't changed
}

API

Symbol Description
Fingerprint [8]byte — xxhash64 digest of file content at read time
Fingerprint.IsZero() Returns true for zero-value (no prior file)
Fingerprint.Matches(data) Returns true if data produces the same fingerprint
FingerprintFromBytes(data) Computes fingerprint from raw bytes
FingerprintFile(path) Computes fingerprint from a file (zero if nonexistent)
Write(path, data) Atomic write, no TOCTOU check (first write, single-writer)
WriteWithPerm(path, data, perm) Atomic write with explicit file permission
WriteVerified(path, data, fp) Atomic write with fingerprint race-check
WriteIfChanged(path, data) Writes only if content differs; returns (changed, err)
WriteFunc(path, fn) Streams content via callback, no TOCTOU check
WriteFuncWithPerm(path, fn, p) Streams content with explicit permission, no TOCTOU check
WriteFuncVerified(path, fn, fp) Streams content via callback with TOCTOU check
ErrConcurrentModification Sentinel error: file changed between read and write

Design decisions

  • xxhash64 over SHA-256 — the fingerprint detects changes, not attackers. xxhash64 is ~11× faster, zero allocations, and reaches ~23–27 GB/s on an idle machine. SHA-NI hardware acceleration is already included in the SHA-256 numbers.
  • Unique temp files via crypto/rand — each writer gets a uniquely-named staging file (path + "." + randomHex + ".tmp"), preventing concurrent writers from corrupting a shared temp file.
  • flock, not mutexes — file locks protect across processes, not just goroutines. flock(2) on Unix, LockFileEx on Windows.
  • Single rename(2) on POSIX — one atomic syscall replaces the target. No two-rename window where the file could be missing.
  • fsync before and after — temp file is synced before rename (data durability); target directory is synced after rename (metadata durability, POSIX only).
  • Missing parent directories are created — every write entrypoint stages through tempPathFor, which runs MkdirAll on the target's parent (0755, umask-narrowed) before creating the temp file. A first write into a fresh cache or config directory succeeds instead of failing with a bare ENOENT — the failure mode that once left two real consumers' caches silently dead for weeks (mr-sync 2026-11 incident).
  • Minimal dependencies — only xxhash for hashing and flock for locking. Both are intentional and not candidates for replacement.

Error contract

  • All errors are wrapped with fmt.Errorf and %w — use errors.Is / errors.As to inspect
  • ErrConcurrentModification is a sentinel error you can check with errors.Is
  • Temp files (.tmp) are cleaned up on any failure
  • Missing parent directories of the target path are created on demand (MkdirAll, 0755); failures wrap the original error
  • File permissions are preserved from the existing file (defaults to 0644 for new files)
  • Data is fsync'd before rename; the directory is fsync'd after (POSIX) for crash durability

Dependencies

Dependency Purpose
cespare/xxhash Fast non-cryptographic hash for fingerprinting
gofrs/flock Cross-platform file locking (flock on Unix, LockFileEx on Windows)

Benchmarks

xxhash64 vs crypto/sha256 — 100K iterations per benchmark, single core.

Hardware: AMD Ryzen AI MAX+ 395, Go 1.27.0, linux/amd64 — min–max over 3 runs (2026-11-03) on a shared machine under heavy concurrent load. xxhash64 is memory-bandwidth-bound and takes the contention hit; SHA-256 (SHA-NI, compute-bound) is load-stable. On an idle machine xxhash64 reaches ~23–27 GB/s.

Hash Size ns/op (min–max) Throughput (min–max) Allocations
xxhash64 1 KB 58–108 9,498–17,797 MB/s 0
SHA-256 1 KB 559–582 1,758–1,833 MB/s 1 × 32 B
xxhash64 10 KB 558–846 12,100–18,358 MB/s 0
SHA-256 10 KB 4,834–4,923 2,080–2,119 MB/s 1 × 32 B
xxhash64 100 KB 5,389–5,961 17,177–19,000 MB/s 0
SHA-256 100 KB 52,774–53,559 1,912–1,940 MB/s 1 × 32 B
xxhash64 1 MB 46,101–50,278 20,855–22,745 MB/s 0
SHA-256 1 MB 524,842–545,518 1,922–1,998 MB/s 1 × 32 B

xxhash64 is ~11× faster than SHA-256 on an idle machine (7–12× under the load above), zero allocations, and reaches ~23–27 GB/s when idle — effectively RAM bandwidth. No hardware accelerator exists or is needed; the hash is memory-bound, not compute-bound. SHA-256 results already include SHA-NI hardware acceleration.

Run yourself:

go test -bench=. -benchmem -benchtime=100000x

Platform support

Works everywhere Go compiles. File locking uses:

  • flock(2) on Linux, macOS, BSD
  • LockFileEx on Windows

Atomic rename and durability:

  • POSIX: single rename(2) (atomic replace) + fsync on the directory
  • Windows: MoveFileEx with MOVEFILE_REPLACE_EXISTING, retried on ERROR_ACCESS_DENIED/ERROR_SHARING_VIOLATION (antivirus contention)

API stability

This library follows Go module versioning:

  • Pre-v1.0.0 (v0.x.y): The API may change between minor versions. We minimize breaking changes, but reserve the right to rename or adjust public symbols based on user feedback.
  • Post-v1.0.0: Standard Go compatibility guarantees apply. No breaking changes without a major version bump.

The core Write / Fingerprint API is stable and unlikely to change.

License

MIT

About

Crash-safe, race-free file writes for Go — TOCTOU protection via fingerprint verification, cross-platform file locking, atomic rename, and fsync for crash durability.

Topics

Resources

Contributing

Security policy

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages