A Node service on my home server restarted 43,522 times in one boot and never started once. The cause was the most ordinary line of code in it.
The short answer
If your Node app dies on start with SyntaxError: Unexpected end of JSON input and the JSON file it reads is 0 bytes, the file was emptied mid-save. fs.writeFileSync empties the file first and then writes, so a power cut or crash in between leaves nothing. Save to a temporary file and rename it over the old one instead, and make the loader treat an empty or broken file as “no data yet” rather than crashing.
Where this comes from
This was on a small always-on Linux machine in my homelab that loses power now and then. Host names, paths and service names are changed. The lesson applies to any program that saves its state as a single JSON file.
The symptom
The service would not start. journalctl showed the same stack trace every five seconds:
SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)
at loadDb (.../db/database.js)
at Object.<anonymous> (.../db/database.js)
systemctl status showed the restart counter climbing. On that boot it had reached 43,522. On the next boot it hit 506 in two hours.
The data file it was reading was 0 bytes.
Nobody had noticed for weeks. A service with Restart=always that fails in under a second and comes straight back looks “active” in almost every quick check.
Why the file was empty
The save function was one line:
fs.writeFileSync(FILE, JSON.stringify(data));
That looks atomic. It isn’t. writeFileSync opens the file in write mode, which truncates it to zero bytes first, and then writes the new content. Between those two steps the file on disk is empty.
That window is tiny, but this service saved often and the machine loses power abruptly. Eventually the power went at exactly the wrong moment. The file was emptied and the new content never landed. The data was gone.
Why it could never recover
On its own, an empty file is a lost-data problem. What made it a dead service was the loader:
const db = JSON.parse(fs.readFileSync(FILE, 'utf8')); // at the top of the module
That runs when the module is first loaded, before any error handler, before the server binds its port. JSON.parse('') throws Unexpected end of JSON input, the process exits, systemd restarts it, and the same thing happens again five seconds later. For ever.
writeFileSync truncates before writing, so a power cut in between leaves 0 bytes.
A bare JSON.parse at module scope turned bad data into a process that can never start.
Restart=always kept the unit “active” while it had never once worked.
Fix 1: write to a temp file, then rename
The standard fix is to never write over the real file directly. Write the new content to a temporary file next to it, then rename the temporary file over the real one:
const fs = require('fs');
const path = require('path');
function saveDb(data) {
const tmp = path.join(path.dirname(FILE), `.${path.basename(FILE)}.tmp`);
const fd = fs.openSync(tmp, 'w');
try {
fs.writeSync(fd, JSON.stringify(data));
fs.fsyncSync(fd); // make sure the bytes are on disk
} finally {
fs.closeSync(fd);
}
fs.renameSync(tmp, FILE); // atomic swap on Linux
}
On Linux, rename within the same filesystem is atomic. Anyone reading the file sees either the whole old version or the whole new version, never half of one and never an empty file. The temp file must be in the same directory, because a rename across filesystems becomes a copy and loses that guarantee.
The fsync matters for power cuts specifically. Without it, the rename can reach the disk before the file’s contents do, and after a crash you can still find an empty file. With it, the contents are on disk before the swap.
To be honest about my own setup: the fixed service writes the temp file and renames it, but it does not call fsync. That fully covers a process being killed mid-save. It mostly, but not fully, covers a power cut. If your machine loses power as often as mine, add the fsync.
If you would rather not write this yourself, the write-file-atomic package on npm does the same thing.
Fix 2: load lazily and treat broken data as empty
The loader should never be able to stop the process from starting:
function loadDb() {
try {
const raw = fs.readFileSync(FILE, 'utf8');
if (!raw.trim()) return defaultDb();
return JSON.parse(raw);
} catch (err) {
if (err.code === 'ENOENT') return defaultDb();
log.error(`data file unreadable, starting empty: ${err.message}`);
fs.copyFileSync(FILE, `${FILE}.corrupt-${Date.now()}`); // keep it for inspection
return defaultDb();
}
}
Call it from your start-up code, not at the top of a module. Keep a copy of the broken file before carrying on, so you can still look at it later. Whether starting empty is acceptable depends on the service. For mine it was. For something holding money or orders, you might prefer to refuse to start, but with a clear log message rather than an endless crash loop.
Fix 3: notice when a service never actually starts
Restart=always is not resilience. A unit that crashes instantly and restarts looks the same as a healthy one unless you check something real. Cheap checks that would have caught this in minutes:
- Alert when a unit’s restart count goes up:
systemctl show -p NRestarts myservice. - Add
StartLimitIntervalSecandStartLimitBurstto the unit, so systemd gives up after a few quick failures and the unit shows as failed, which most monitoring does notice. - Check that the service answers on its port, not just that the process exists.
The twist: don’t revive the wrong copy
My first instinct was to repair the file and restart the service. That would have been a mistake.
When I traced where this service came from, it turned out to be a leftover copy from an earlier migration. The real instance was running elsewhere, already used temp file plus rename (its code even had the comment // Atomic write via temp-file + rename), and had a healthy data file. Bringing the old copy back would have started a second backend, with push notifications switched on, against an empty database.
The right fix for that machine was to disable the leftover service and keep its unit file and data, so the change could be undone. Before you fix a crash loop, check that the thing crashing is still supposed to exist.
Checklist
- Search for
writeFileSync(andwriteFile(on any file you read back on start-up. Replace with temp file, fsync, rename. - Never
JSON.parsea state file at module scope. Load it in start-up code inside atry. - Decide what an empty or broken file should mean: start empty, or refuse with a clear message. Not crash in a loop.
- Add start limits to your systemd units and alert on restart counts.
- Before fixing a crash loop, confirm the service is the live one.
Takeaway
Two ordinary lines, a save and a load, each fine on its own, together produced a service that could not start after one badly timed power cut. If your program keeps its state in a single file, writing it safely takes about ten more lines. That is not over-engineering. It is the minimum.
Your turn
How does your project save its state?
AI assisted with finding the cause and drafting this article. The machine, the logs and the counters are from my own homelab.
