0
0
Node.jsframework~3 mins

Why Forking workers per CPU core in Node.js? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your server could magically use every CPU core to handle more users without extra hassle?

The Scenario

Imagine you have a Node.js server that handles many user requests at once, but it runs on a single CPU core.

When many users connect, the server slows down and some requests wait a long time.

The Problem

Using just one core means your server can only do one thing at a time.

This causes delays and poor performance when traffic is high.

Trying to manage multiple tasks manually is complex and error-prone.

The Solution

Forking workers per CPU core lets Node.js create multiple processes, one for each core.

Each worker handles requests independently, making full use of all CPU cores.

This improves speed and reliability without complicated manual management.

Before vs After
Before
const http = require('http');
http.createServer((req, res) => {
  res.end('Hello World');
}).listen(8000);
After
const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
  for (let i = 0; i < numCPUs; i++) {
    cluster.fork();
  }
} else {
  http.createServer((req, res) => {
    res.end('Hello from worker');
  }).listen(8000);
}
What It Enables

This approach enables your server to handle many requests quickly by using all CPU cores efficiently.

Real Life Example

A busy online store uses forking workers to serve thousands of shoppers at once without slowing down during sales.

Key Takeaways

Single-core servers struggle with many requests.

Forking creates multiple workers, one per CPU core.

This improves performance and reliability easily.