Restart a worker thread when it crashes
Restart a crashed Node.js 24 worker thread from its exit event with a capped number of restarts and a short backoff, so one bad job cannot loop forever.
An uncaught exception in a worker thread kills that worker, not your process, and nothing brings it back. The main thread has to notice and start a new one, with a limit so a worker that crashes on start does not restart forever.
import { Worker, isMainThread, workerData } from 'node:worker_threads';
if (isMainThread) {
const maxRestarts = 3;
const start = (attempt) => {
const worker = new Worker(new URL(import.meta.url), { workerData: { attempt } });
worker.on('error', (err) => console.log(`worker ${attempt} crashed: ${err.message}`));
worker.on('exit', (code) => {
if (code === 0) return console.log(`worker ${attempt} finished`);
if (attempt >= maxRestarts) return console.log('giving up');
setTimeout(() => start(attempt + 1), 100 * 2 ** attempt);
});
};
start(1);
} else if (workerData.attempt < 3) {
throw new Error('bad state on startup');
} else {
console.log('worker running');
}worker 1 crashed: bad state on startup
worker 2 crashed: bad state on startup
worker running
worker 3 finishedAn uncaught error in the worker fires error on the Worker object with the thrown error, then exit with code 1. Restarting from exit rather than error catches every way a worker can stop, including process.exit() inside it. The delay doubles each time, and after maxRestarts the supervisor stops. Here the worker fails twice on purpose, then runs. See the exit event.
A restart loses whatever the worker held in memory and any job it was running, so resend the job or mark it failed. If crashes come from a bug, restarting only hides it: log the error and alert once the restart count climbs.