0
0
Node.jsframework~3 mins

How cluster module works in Node.js - Why You Should Know This

Choose your learning style9 modes available
The Big Idea

What if your Node.js server could magically use all CPU cores to handle huge traffic without crashing?

The Scenario

Imagine running a Node.js server that handles many users at once, but it only uses one CPU core.

When traffic spikes, the server slows down and users wait longer.

The Problem

Node.js runs on a single thread by default, so it can only use one CPU core.

This means it can't handle many requests in parallel efficiently, causing slow responses and crashes under heavy load.

The Solution

The cluster module lets you create multiple Node.js processes (workers) that share the same server port.

This way, your app can use all CPU cores, handling many requests at once smoothly.

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

You can build fast, reliable servers that use all CPU cores to serve many users at the same time without slowing down.

Real Life Example

A popular chat app uses the cluster module to run multiple worker processes, so thousands of users can send messages instantly without delays.

Key Takeaways

Node.js single-thread limits performance under heavy load.

Cluster module creates multiple worker processes to use all CPU cores.

This improves speed and reliability for busy servers.