0
0
Node.jsframework~5 mins

Cluster vs reverse proxy decision in Node.js

Choose your learning style9 modes available
Introduction

Using a cluster or a reverse proxy helps your Node.js app handle many users smoothly. They both improve performance but work differently.

You want to use all CPU cores to run your Node.js app faster.
You need to balance traffic between several app instances.
You want to add security and hide your app details from users.
You want to serve static files efficiently alongside your app.
You want to easily manage multiple apps on one server.
Syntax
Node.js
const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;

if (cluster.isPrimary) {
  for (let i = 0; i < numCPUs; i++) {
    cluster.fork();
  }
} else {
  http.createServer((req, res) => {
    res.writeHead(200);
    res.end('Hello from worker ' + process.pid);
  }).listen(8000);
}

The cluster module lets you create child processes to use multiple CPU cores.

A reverse proxy like Nginx runs separately and forwards requests to your app instances.

Examples
Simple cluster example with one worker process.
Node.js
const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;

if (cluster.isPrimary) {
  cluster.fork(); // create one worker
} else {
  http.createServer((req, res) => {
    res.end('Worker ' + process.pid);
  }).listen(3000);
}
Nginx forwards requests to your Node.js app running on port 3000.
Node.js
server {
  listen 80;
  location / {
    proxy_pass http://localhost:3000;
  }
}
Sample Program

This Node.js program uses the cluster module to create one worker per CPU core. The primary process manages workers. Each worker runs an HTTP server that responds with its process ID.

Node.js
const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;

if (cluster.isPrimary) {
  console.log(`Primary ${process.pid} is running`);

  for (let i = 0; i < numCPUs; i++) {
    cluster.fork();
  }

  cluster.on('exit', (worker, code, signal) => {
    console.log(`Worker ${worker.process.pid} died`);
  });
} else {
  http.createServer((req, res) => {
    res.writeHead(200);
    res.end(`Hello from worker ${process.pid}`);
  }).listen(8000);

  console.log(`Worker ${process.pid} started`);
}
OutputSuccess
Important Notes

Clusters help use all CPU cores but do not add security or caching features.

Reverse proxies can handle SSL, caching, and protect your app from direct internet access.

You can use both together: cluster for CPU use, reverse proxy for traffic management.

Summary

Clusters let Node.js apps use multiple CPU cores by creating worker processes.

Reverse proxies forward requests and add features like security and load balancing.

Choose clusters for CPU efficiency, reverse proxies for traffic control, or both for best results.