Skip to content
jshacks.dev
Node.js

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.

2 min read
Summarize in AI

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.

supervisor.mjsJavaScript
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');
}
Text
worker 1 crashed: bad state on startup
worker 2 crashed: bad state on startup
worker running
worker 3 finished

An 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.

Taggednode 24
Share

More snippets

Node.js

Read a text file with fs promises

Read a text file with fs promises in Node.js: await readFile with an encoding, and catch the error code when the file is missing. Node.js 24.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.