Run a pool of worker threads
Run CPU-heavy tasks on a fixed pool of Node.js 24 worker threads sized by os.availableParallelism, queue the rest, and get each result as a promise.
Starting a new worker for every task costs a fresh JavaScript engine each time. A pool starts a few workers once and hands each the next task from a queue as it frees up.
import { Worker, isMainThread, parentPort } from 'node:worker_threads';
import { availableParallelism } from 'node:os';
if (!isMainThread) {
const fib = (n) => (n < 2 ? n : fib(n - 1) + fib(n - 2));
parentPort.on('message', (n) => parentPort.postMessage(fib(n)));
} else {
const size = Math.min(availableParallelism(), 4);
const idle = Array.from({ length: size }, () => new Worker(new URL(import.meta.url)));
const queue = [];
const run = (n) => new Promise((resolve) => { queue.push({ n, resolve }); dispatch(); });
function dispatch() {
while (idle.length && queue.length) {
const worker = idle.pop();
const { n, resolve } = queue.shift();
worker.once('message', (result) => { resolve(result); idle.push(worker); dispatch(); });
worker.postMessage(n);
}
}
console.log(await Promise.all([30, 31, 32, 33, 34, 35].map(run)));
for (const worker of idle) await worker.terminate();
}[ 832040, 1346269, 2178309, 3524578, 5702887, 9227465 ]Each worker loads the same file, sees isMainThread is false and becomes a task runner. dispatch pairs idle workers with queued tasks, and a worker returns to the idle list when it answers, so at most size tasks run at once and the rest wait. Promise.all keeps results in input order even though they finish out of order. See worker_threads.
availableParallelism (Node.js 18.14.0) is the right size cap, since more workers than cores only adds switching. This pool does not handle a worker crashing mid-task, which would leave that promise pending forever; production code should listen for error and reject. Libraries such as Piscina add that, plus timeouts and cancellation.