Node runs your JavaScript on a single thread, which is fine for work that mostly waits, such as database and network calls. It is not fine for work that keeps the processor busy, such as resizing images, hashing many passwords, or a big calculation. While that runs, nobody else is served. Modern computers have many cores, and Node gives you three tools to use them. Each fits a different problem, and choosing the right one is a common interview question.
Worker threads: heavy calculations
A worker thread is another JavaScript thread inside the same Node process. It has its own event loop and its own memory, and it talks to the main thread by sending messages. Use it for CPU-heavy JavaScript. The example below calculates slow Fibonacci numbers in three workers at once. The main thread only starts them and waits for the messages, so it could keep answering requests meanwhile.
- Make a folder and open it in a terminal. Run
npm init -y, then openpackage.jsonand add"type": "module"so thatimportworks. - Save the code as
worker.jsand run it withnode worker.js.
import { Worker, isMainThread, parentPort, workerData } from 'node:worker_threads';
function fib(n) {
return n < 2 ? n : fib(n - 1) + fib(n - 2);
}
if (isMainThread) {
// Run slow, CPU-heavy work in separate threads so the main thread stays free.
const run = (n) =>
new Promise((resolve, reject) => {
const worker = new Worker(new URL(import.meta.url), { workerData: n });
worker.once('message', resolve);
worker.once('error', reject);
});
const results = await Promise.all([run(30), run(31), run(32)]);
console.log('Results:', results);
} else {
parentPort.postMessage(fib(workerData));
}
Results: [ 832040, 1346269, 2178309 ]
Notice that the same file contains both sides. isMainThread tells which side is running. Data sent between threads is copied, not shared, except for special shared memory. Starting a worker costs a few tens of milliseconds, so for a real server you create a small pool of workers at start and reuse them, using a library such as Piscina. Do not start a new worker for every request.
Child processes: other programs
A child process is a separate operating-system process. Use it to run another program, such as ffmpeg for video, a Python script, or git, or to run a second Node script that must be isolated. execFile runs a program and gives you its output. fork starts another Node script with a built-in message channel.
import { execFile, fork } from 'node:child_process';
import { promisify } from 'node:util';
import { fileURLToPath } from 'node:url';
const execFileAsync = promisify(execFile);
if (process.argv[2] === 'child') {
// This branch runs in the child process.
process.on('message', (message) => {
process.send({ doubled: message.value * 2 });
process.exit(0);
});
} else {
// 1. Run another program and read its output. Arguments are an array, never one joined string.
const { stdout } = await execFileAsync('node', ['-e', 'console.log(6 * 7)']);
console.log('Child program printed:', stdout.trim());
// 2. Fork a Node process and talk to it with messages.
const child = fork(fileURLToPath(import.meta.url), ['child']);
child.on('message', (reply) => console.log('Forked child replied:', reply));
child.send({ value: 21 });
}
Child program printed: 42
Forked child replied: { doubled: 42 }
Cluster: copies of your server
The cluster module starts several copies of the same server, one per core, that share one port. The operating system or Node spreads new connections between them. If one copy crashes, the others keep serving, and the primary process can start a replacement. This is the simplest way to use all the cores for a normal web server, because each request is handled completely by one copy.
import cluster from 'node:cluster';
import http from 'node:http';
const WORKERS = 2;
if (cluster.isPrimary) {
// The primary process starts one worker per core you want to use, and restarts any that die.
let ready = 0;
for (let i = 0; i < WORKERS; i++) cluster.fork();
cluster.on('listening', () => {
ready += 1;
if (ready === WORKERS) {
// Ask the shared port twice and see which worker answered.
const asks = [1, 2, 3, 4].map(() => new Promise((resolve) => {
http.get('http://127.0.0.1:3199', (res) => {
let body = '';
res.on('data', (c) => (body += c));
res.on('end', () => resolve(body));
});
}));
Promise.all(asks).then((answers) => {
console.log('Answers came from', new Set(answers).size, 'worker process(es)');
for (const id in cluster.workers) cluster.workers[id].kill();
setTimeout(() => process.exit(0), 100);
});
}
});
} else {
http.createServer((req, res) => res.end('worker ' + process.pid)).listen(3199);
}
Answers came from 2 worker process(es)
The number may vary: the system may happen to give all four requests to the same worker. In practice you rarely write cluster code yourself. The process manager pm2, which lesson 42 uses, can run your app in cluster mode with one setting. Container platforms and load balancers do the same by starting several copies.
Choosing the right tool
- Waiting work (database, network): nothing special. The event loop already handles many at once.
- Heavy JavaScript calculation: worker threads, ideally from a pool.
- Another program or language: child process, with
execFileand an argument array. - More throughput for a web server: cluster, pm2, or more containers behind a load balancer.
- Very heavy or slow work: a background job queue, as in lesson 35, so the web request does not wait at all.
One warning applies to all copies of a server. Each copy has its own memory. A user logged in on copy A is unknown to copy B if you keep sessions or caches in a normal variable. Store shared state in a database or in Redis, and keep your servers stateless.
Your task
- Change the worker example to take the numbers from
process.argvand compare the time with and without workers. - Run the child example, then change it to run
node --versionand print the result. - Run the cluster example with three workers, and print the process id each answer came from.
How to check it worked
- Your outputs match the outputs above.
- You can say which tool fits an image resize, a call to ffmpeg and a normal web server.
- You can explain why an in-memory session breaks with several copies.