research/atomic-file-writes-in-node
Atomic File Writes in Node.js: Write to a Temp File and Rename, Tested by Killing the Writer Mid-Save
Engineering Note · November 26, 2026 · 8 minute read · Node.js · Files · Reliability · Testing
To save a file so that a crash never leaves it half-written, write the new contents to a temp file in the same directory, fsync it, then rename it over the old file. We tested this by rewriting a 2 MB JSON file in a loop and killing the process at a random moment, 200 times per method, in two runs. A plain fs.writeFileSync left an empty or truncated file after 34 and 41 of the 200 kills. Temp file plus rename left a file that parsed every time, 400 out of 400, plus 200 more in a run with startup cleanup. The rename approach has two details that matter: each write needs its own temp name, and leftover temp files need cleaning up.
Everything below was run on Linux (ext4) with Node.js 22.23.5. The outputs are real.
Why would a small app write JSON files at all?
Plenty of small tools keep their state in a file rather than a database: a settings file, a cache of the last import, the list of closure days for a booking page, a queue of posts to publish. Files are easy to read, back up and edit by hand.
The risk is the moment of saving. If the process is stopped partway through, by a deploy, a crash, an out-of-memory kill or a restart, the file can be left empty or cut off. The next start then fails to read its own settings.
Why is a plain write not safe?
fs.writeFileSync(file, data) uses the 'w' flag by default. The Node.js documentation describes it as: “Open file for writing. The file is created (if it does not exist) or truncated (if it exists).” Truncating comes first, writing comes after. For a moment, the file on disk is empty, and then partly written.
rename behaves differently. The documentation says that if the new path “already exists, it will be overwritten,” and points to the operating system’s rename(2) for details. The idea is that the swap happens in one step, so anyone opening the path gets the old file or the new one. We could not open the Linux or POSIX manual pages from this environment, so the test below is our evidence for how it behaved here.
What did we run?
A writer that rewrites a file forever, with one of two save functions:
import fs from 'node:fs';
import path from 'node:path';
const [mode, file] = process.argv.slice(2);
const rows = Array.from({ length: 20000 }, (_, i) => ({ id: i, name: `Customer ${i}`, note: 'x'.repeat(60) }));
function writeDirect(file, data) {
fs.writeFileSync(file, data);
}
function writeAtomic(file, data) {
const tmp = path.join(path.dirname(file), `.${path.basename(file)}.${process.pid}.${Date.now()}.tmp`);
const fd = fs.openSync(tmp, 'w');
try { fs.writeSync(fd, data); fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
fs.renameSync(tmp, file);
}
const write = mode.startsWith('atomic') ? writeAtomic : writeDirect;
for (let v = 1; ; v++) write(file, JSON.stringify({ version: v, rows }));
The JSON is 2,117,802 bytes. A test harness starts the writer, waits a random 150 to 500 ms, sends SIGKILL (which the process cannot catch or clean up after), and then tries to read and parse the file:
for (let i = 0; i < Number(runs); i++) {
const child = spawn(process.execPath, ['writer.mjs', mode, file, '0'], { stdio: 'inherit' });
await sleep(150 + Math.random() * 350);
child.kill('SIGKILL');
await new Promise((r) => child.once('exit', r));
let text;
try { text = fs.readFileSync(file, 'utf8'); } catch { missing++; continue; }
if (text.length === 0) { empty++; continue; }
try { JSON.parse(text); ok++; } catch { truncated++; }
}
The temp file lives in the same directory as the target on purpose. A rename cannot cross file systems. When we tried to rename a file from /dev/shm (a memory file system) to /tmp here, Node.js threw:
EXDEV EXDEV: cross-device link not permitted, rename '/dev/shm/x/a' -> '/tmp/claude-0/a'
A system temp directory such as /tmp can be a different file system from the app’s data, so a temp file there can fail at the last step.
What happened when we killed the writer?
Two runs of 200 kills for each method:
direct: 200 kills -> parsed 166, empty 21, truncated 13, missing 0; leftover .tmp files: 0
atomic: 200 kills -> parsed 200, empty 0, truncated 0, missing 0; leftover .tmp files: 66
direct: 200 kills -> parsed 159, empty 28, truncated 13, missing 0; leftover .tmp files: 0
atomic: 200 kills -> parsed 200, empty 0, truncated 0, missing 0; leftover .tmp files: 75
With a plain write, 17 and 20.5 percent of kills left a file that would not load: mostly empty, sometimes cut off mid-JSON. Each one is a program that would fail on its next start. With the temp file and rename, every kill left a complete file, either the previous version or the new one.
The price is the leftover temp files: 66 and 75 after 200 kills, about one for every three. Each is a 2 MB partial write that nothing will ever read.
How do you clean up the leftover temp files?
At startup, before the first write, remove temp files that match your own naming pattern and are older than some age:
function removeStaleTemps(file, maxAgeMs = 60_000) {
const dir = path.dirname(file), prefix = `.${path.basename(file)}.`;
for (const name of fs.readdirSync(dir)) {
if (!name.startsWith(prefix) || !name.endsWith('.tmp')) continue;
const full = path.join(dir, name);
if (Date.now() - fs.statSync(full).mtimeMs > maxAgeMs) fs.rmSync(full, { force: true });
}
}
The age limit protects a temp file another process is still writing. In the test there is only one writer at a time, so we passed an age of 0:
atomic-clean: 200 kills -> parsed 200, empty 0, truncated 0, missing 0; leftover .tmp files: 0
Every file still parsed, and no temp files piled up. At most one can be left behind by the very last kill, until the next start removes it.
Why does the temp name need to be unique?
A common shortcut is a fixed temp name: write data.json.tmp, rename it to data.json. That is fine with one writer. With two, it breaks. We started two processes that each saved the same file 150 times, while a reader in the parent parsed it every 2 ms. Three runs with each naming scheme:
fixed temp name: 62 reads, 3 unreadable; writer errors {"ENOENT":128}; final file parses: true
unique temp name: 63 reads, 0 unreadable; writer errors {}; final file parses: true
fixed temp name: 57 reads, 2 unreadable; writer errors {"ENOENT":126}; final file parses: true
unique temp name: 67 reads, 0 unreadable; writer errors {}; final file parses: true
fixed temp name: 59 reads, 3 unreadable; writer errors {"ENOENT":123}; final file parses: true
unique temp name: 60 reads, 0 unreadable; writer errors {}; final file parses: true
With a shared name, writer A renames data.json.tmp into place while writer B still has the same file open and is rewriting it. B’s half-written data is now data.json, and the reader sees it. B’s own rename then fails with ENOENT because the temp file is gone. With a name that includes the process ID and a counter or timestamp, each writer renames only its own complete file. The last rename wins, which is still a lost update, so two writers on one file need a lock or a database. But nobody reads a broken file.
What does fsync cost?
fsync asks the operating system to push the data to the storage device before the rename. We timed 50 saves of the same 2 MB file each way, after 5 warm-up saves:
direct median 1.72 ms, slowest 2.56 ms (2.1 MB, 50 writes)
temp + rename median 1.78 ms, slowest 2.88 ms (2.1 MB, 50 writes)
temp + fsync + rename median 5.85 ms, slowest 12.68 ms (2.1 MB, 50 writes)
The rename itself is close to free. fsync roughly triples the time. For a settings file saved now and then, 6 ms does not matter. For a file rewritten many times a second, it does, and that is usually a sign the data belongs in a database such as SQLite, which handles this for you.
Our kill test does not show what fsync buys. Killing a process differs from crashing the machine: the data the process had already handed to the operating system was kept after the process died. fsync matters when the power goes or the machine crashes before the data reaches the disk. That needs real hardware to test, so we did not.
A checklist for saving files safely
- Write to a temp file in the same directory as the target.
- Give the temp file a unique name per write: process ID plus a counter or timestamp.
fsyncthe temp file before closing it, unless the file can be rebuilt from elsewhere.- Rename it over the target. Never truncate the target in place.
- On startup, remove stale temp files that match your own naming pattern, with an age limit if other processes might be writing.
- If more than one process writes the same file, the last rename wins. Use a lock or a database if updates must not be lost.
Limitations
- We simulated crashes with
SIGKILLon one Linux machine with ext4. We did not test power loss, a kernel crash, network file systems, Windows or macOS, where rename and flush behave differently. - We did not
fsyncthe directory after the rename. Some guidance recommends it so the rename itself survives a power loss; we could not test that here, so we make no claim either way. - The kill tests ran 1,000 kills in total with random timing, 600 of them against the temp-file version. A rare failure that happens less than once in a few hundred kills could still exist.
- The timing numbers are from one machine and a 2 MB file. Smaller files and faster disks will show different ratios.
- We tested the synchronous
fsfunctions. The same steps apply tofs.promises, but we did not run them.
Sources
Related reading
- Expiring Old Rows in SQLite Without Blocking Writers
- Business Days With a Holiday List: Computing the Next Open Day in Node.js
- Before You Close for the Holidays: What to Set on Your Website, Bookings, Email and Alerts
Frequently asked questions
Is fs.writeFileSync atomic in Node.js?
No. It opens the file with the 'w' flag, which truncates it, and then writes the new contents. If the process dies in between, the file is left empty or cut off. In our test, 34 and 41 of 200 random kills in two runs left a file that would not parse as JSON.
How do I write a file atomically in Node.js?
Write the new contents to a temporary file in the same directory, call fsync on it, close it, then rename it over the original with fs.renameSync. Readers see either the old file or the new one, never a half-written one. In our test this survived 600 random kills without a single unreadable file.
Why must the temp file name be unique?
If two processes share one temp name such as data.json.tmp, one can truncate and rewrite the temp file while the other renames it into place. In our test with a fixed name, a reader found an unreadable file in 2 or 3 of about 60 reads per run, and the writers hit 123 to 128 ENOENT errors. With a unique name per write, both were zero.
Do I need fsync before the rename?
For a process crash, our test did not need it: the operating system still finished writing the data. fsync is there for a power loss or a machine crash, which we could not test here. It made each 2 MB save take about 5.9 ms instead of 1.8 ms, so skip it only for files you could rebuild.
What happens to the temp file if the process crashes?
It stays on disk. In our test, 66 and 75 temp files were left after 200 kills. Delete stale temp files when the program starts, matching only your own naming pattern, and only when no other process is writing the same file.