0
0
Node.jsframework~3 mins

Why Master and worker processes in Node.js? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your app could use all your computer's power without breaking under pressure?

The Scenario

Imagine you have a busy restaurant kitchen where one chef tries to cook all dishes alone, handling every order from start to finish.

The Problem

When one chef does everything, orders pile up, mistakes happen, and customers wait too long. The chef gets overwhelmed and slows down.

The Solution

Master and worker processes split the work: the master assigns tasks, and workers cook orders in parallel, making the kitchen faster and more reliable.

Before vs After
Before
const http = require('http');
http.createServer((req, res) => {
  // handle all requests here
  res.end('Hello World');
}).listen(3000);
After
const cluster = require('cluster');
if (cluster.isMaster) {
  cluster.fork();
  cluster.fork();
} else {
  require('http').createServer((req, res) => {
    // handle requests
    res.end('Hello World');
  }).listen(3000);
}
What It Enables

This lets your app handle many tasks at once, using all CPU cores efficiently without crashing everything if one part fails.

Real Life Example

A web server uses master and worker processes to serve thousands of users simultaneously, keeping the site fast and stable.

Key Takeaways

One process doing all work is slow and fragile.

Master assigns tasks, workers do the work in parallel.

Improves speed, reliability, and resource use.