Advertisement
Intermediate Node.js, Clustering & Worker Threads

How do you gracefully terminate a worker thread, and what's the difference between worker.terminate() and letting it exit naturally?

Short answer

worker.terminate() forcibly and immediately stops execution regardless of current work, abandoning in-progress work -- appropriate for canceling unneeded tasks.

Save Node.js mock interview
Advertisement
AModel answer
worker.terminate() forcibly and immediately stops execution regardless of current work, abandoning in-progress work -- appropriate for canceling unneeded tasks. Letting a worker exit naturally allows pending operations to complete first, providing a cleaner shutdown when its own work is genuinely finished.
setTimeout(() => worker.terminate(), 30000); // cancel if it takes too long
worker.on('exit', (code) => console.log(`Worker exited with code ${code}`));
Real-world example
A request-timeout mechanism calls worker.terminate() on a task running over 30 seconds, ensuring a stuck task doesn't tie up pool capacity indefinitely, at the cost of losing partial progress.
Likely follow-ups
  • What cleanup responsibilities does code inside a worker have before being forcibly terminated?
  • How would you implement graceful cancellation where the worker checks a flag periodically rather than being killed?
Related topics