Forking workers per CPU core helps your Node.js app use all the computer's power. It makes your app faster and can handle more users at the same time.
0
0
Forking workers per CPU core in Node.js
Introduction
When your app needs to handle many requests at once without slowing down.
When you want to use all CPU cores to improve performance.
When you want to keep your app running even if one worker crashes.
When you build a server that should be fast and reliable.
Syntax
Node.js
import cluster from 'cluster'; import os from 'os'; if (cluster.isPrimary) { const cpuCount = os.cpus().length; for (let i = 0; i < cpuCount; i++) { cluster.fork(); } cluster.on('exit', (worker, code, signal) => { console.log(`Worker ${worker.process.pid} died. Restarting...`); cluster.fork(); }); } else { // Worker code here, e.g., start server }
cluster.isPrimary checks if the current process is the main one that controls workers.
cluster.fork() creates a new worker process.
Examples
This example forks one worker per CPU core and each worker prints its process ID.
Node.js
import cluster from 'cluster'; import os from 'os'; if (cluster.isPrimary) { const cpuCount = os.cpus().length; for (let i = 0; i < cpuCount; i++) { cluster.fork(); } } else { console.log(`Worker ${process.pid} started`); }
This example creates an HTTP server in each worker to handle requests in parallel.
Node.js
import cluster from 'cluster'; import os from 'os'; import http from 'http'; if (cluster.isPrimary) { const cpuCount = os.cpus().length; for (let i = 0; i < cpuCount; i++) { cluster.fork(); } } else { http.createServer((req, res) => { res.writeHead(200); res.end(`Handled by worker ${process.pid}`); }).listen(8000); }
Sample Program
This program uses the cluster module to fork one worker per CPU core. The primary process logs its start and forks workers. Each worker runs an HTTP server that responds with its process ID. If a worker dies, the primary process restarts it automatically.
Node.js
import cluster from 'cluster'; import os from 'os'; import http from 'http'; if (cluster.isPrimary) { const cpuCount = os.cpus().length; console.log(`Primary process ${process.pid} is running`); console.log(`Forking ${cpuCount} workers`); for (let i = 0; i < cpuCount; i++) { cluster.fork(); } cluster.on('exit', (worker, code, signal) => { console.log(`Worker ${worker.process.pid} died. Restarting...`); cluster.fork(); }); } else { http.createServer((req, res) => { res.writeHead(200); res.end(`Hello from worker ${process.pid}`); }).listen(8000); console.log(`Worker ${process.pid} started and listening on port 8000`); }
OutputSuccess
Important Notes
Each worker is a separate process, so they do not share memory directly.
Use cluster to improve performance on multi-core machines.
Restarting workers on exit helps keep your app reliable.
Summary
Forking workers lets your app use all CPU cores.
The primary process controls workers and restarts them if needed.
Workers can run servers or other tasks in parallel.