Suppose I have three reports to calculate and two threads to do the work. I can give each thread a report straight away. Who gets the third one? If I wait specifically for thread 1, thread 2 might finish early and sit idle. This was the practical question behind my original “how to implement worker pool in js”.
What happens when the database finishes and the calculation begins?
A JavaScript request handler can suspend at await readRows() while the database is working. When the rows arrive, the JavaScript loop that calculates the report resumes on the original thread. If another thread should run that loop, Node provides worker_threads. As the manual puts it, “Workers (threads) are useful for performing CPU-intensive JavaScript operations.” The main thread sends a message describing the job and can continue serving requests until the reply arrives. How Python, Go and Node.js schedule that work.1
Starting a fresh Worker for each report would also run the calculation elsewhere, but each request would pay to start a thread and load the script. A worker pool keeps several Workers alive and assigns them successive jobs. Let's implement a single batch first. We know the inputs up front and want the results in submission order, even if the second report finishes first.
How does a Worker stay available for the next report?
To make the answer easy to check, each job counts the primes from 2 through a supplied limit. A prime is an integer greater than 1 divisible only by 1 and itself. Save this as count.cjs in an empty directory. This is the code that runs in each worker thread.
const { parentPort } = require("node:worker_threads");
function countPrimes(limit) {
let count = 0;
for (let n = 2; n <= limit; n++) {
let prime = true;
for (let d = 2; d * d <= n; d++) {
if (n % d === 0) {
prime = false;
break;
}
}
if (prime) count++;
}
return count;
}
parentPort.on("message", (limit) => {
parentPort.postMessage(countPrimes(limit));
});
parentPort is the messaging endpoint connected to the thread that created the Worker. The listener registered by on("message", …) stays in place after the first reply. Send 10 and the Worker replies with 4. Send 20 to that same Worker and it replies with 8. Each message carries one number. Sending an entire report would introduce another cost because ordinary JavaScript objects in these messages are copied using structured cloning.2
Where is the third job while both Workers are busy?
Save the following as pool.cjs alongside count.cjs. The main thread owns the input array, limits, and the index of the first unassigned job, next. Each Worker has at most one outstanding job. Its current index tells the main thread where to put the reply.
const { Worker } = require("node:worker_threads");
const path = require("node:path");
async function runBatch(limits, size = 2) {
if (!Number.isSafeInteger(size) || size < 1) {
throw new RangeError("size must be a positive integer");
}
if (!limits.every(n => Number.isSafeInteger(n) && n >= 0)) {
throw new RangeError("limits must be nonnegative integers");
}
const results = new Array(limits.length);
const workers = [];
let next = 0;
function runSlot() {
return new Promise((resolve, reject) => {
const worker = new Worker(path.join(__dirname, "count.cjs"));
workers.push(worker);
let current;
function dispatch() {
if (next === limits.length) {
resolve();
return;
}
current = next++;
worker.postMessage(limits[current]);
}
worker.on("message", (count) => {
results[current] = count;
dispatch();
});
worker.once("error", reject);
worker.once("exit", (code) => {
reject(new Error(`worker exited before finishing (code ${code})`));
});
dispatch();
});
}
try {
const slots = Math.min(size, limits.length);
await Promise.all(Array.from({ length: slots }, runSlot));
return results;
} finally {
await Promise.all(workers.map(worker => worker.terminate()));
}
}
runBatch([200000, 10, 1000]).then(console.log).catch((error) => {
console.error(error);
process.exitCode = 1;
});
Run node pool.cjs with Node.js 22.12.0. No package installation is required. The output is [ 17984, 4, 168 ]. The three numbers preserve input order. To see how work was actually assigned, follow the messages.
| When | What the main thread does |
|---|---|
| The batch starts | Send 200000 to one Worker and 10 to the other. The third limit, 1000, is still in the array at next. |
| The first reply arrives | Store the answer at that Worker's index. Send 1000 to the Worker that just replied. Either Worker is eligible, regardless of which one was created first. |
| The remaining replies arrive | Once all inputs have been assigned, each Worker finishes its last job. Return results in their original order and terminate the Workers. |
Each Promise represents one Worker's share of the batch. Promise.all waits for all of them. A worker error or an early exit with work outstanding rejects its Promise. The caller sees the failure and the finally block cleans up the Workers. Retrying a report that may already have written a file requires a decision about that file, so this example leaves retries to its caller.
For jobs arriving as separate HTTP requests, the pool has to live longer than any one request. Create it when the service starts. A pending job needs the input and a way to resolve the Promise held by the corresponding request. On a reply, resolve that request and dispatch the oldest waiting job to the available Worker. Ten simultaneous requests that each create two Workers would start twenty threads. A shared two-Worker pool bounds the active calculations at two. A bounded queue also gives the service a point at which to ask the next client to retry later.
When all the inputs are known up front, you can reuse runBatch as written. For a reference implementation of a pool that accepts jobs as they arrive, see two methods in workerpool. The exec method adds each new job to the back of the queue. Once _next finds an available Worker, it takes a job from the front and sends it to that Worker.3
In the three-report example, the third calculation can go to either thread because it hasn't started. Once a Worker is halfway through counting primes, that calculation continues there. The reply itself tells the main thread who is available next.
If the three reports are waiting for SQL, two permits can limit how many queries the batch sends at once. As soon as either query finishes, the third can start. How a semaphore works alongside a database connection pool (in Chinese).
Footnotes
-
Node.js contributors. (2024). Worker threads. Node.js v22.12.0 Documentation. Worker threads, introductory paragraphs on CPU-intensive work and pooling. ↩
-
Node.js contributors. (2024). Worker threads. Node.js v22.12.0 Documentation. parentPort · Cloning, transferring and sharing message values. ↩
-
workerpool contributors. (2024, October 11). Pool.js (workerpool v9.2.0). GitHub. Queueing a job · Dispatching the next job. ↩