Scale your Node.js application

সবার আগে শুরু করি Node.js এর ক্লেইম করা একটা লাইন দিয়ে “Node.js is designed to build scalable network applications”।

Node.js ডিজাইন করা হয়েছে scalable network application এর জন্য, আমরা নরমাল্লি ও শুনে থাকি Node.js is highly scalable, কিন্তু কি ভাবে ??

Cluster module

Node.js এর built in modules দিয়ে দেখানোর চেষ্টা করব কি ভাবে একটা single multicore machine এ horizontally scale করা যায়।

const cluster = require('cluster');
const http = require('http');
// number of cpu cores
const numberOfCPU = require('os').cpus().length;

if (cluster.isMaster) {

 console.log(`Master is running: ${process.pid}`);

 // Fork workers.
 for (let i = 0; i < numberOfCPU; i++) {
  cluster.fork();
 }

 cluster.on('exit', (worker, code) => {
  console.log(`worker ${worker.process.pid} died`);
  // to increase the availability of the application
  // we create new worker using fork() method if the worker is crushed.
  // so that we can increase our applications availability.
  if (code !== 0 && !worker.exitedAfterDisconnect) {
    console.log(`Worker ${worker.id} crashed. \nStarting a new worker...`);
    cluster.fork();
  }
 });

} else {

 // Create a HTTP server
 http.createServer((req, res) => {
  res.writeHead(200);
  res.end('hello world\n');
 }).listen(4000);

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

const cluster = require('cluster');
const http = require('http');
// number of cpu cores
const numberOfCPU = require('os').cpus().length;

if (cluster.isMaster) {

 console.log(`Master is running: ${process.pid}`);

 // Fork workers.
 for (let i = 0; i < numberOfCPU; i++) {
  cluster.fork();
 }

 cluster.on('exit', (worker, code) => {
  console.log(`worker ${worker.process.pid} died`);
  // to increase the availability of the application
  // we create new worker using fork() method if the worker is crushed.
  // so that we can increase our applications availability.
  if (code !== 0 && !worker.exitedAfterDisconnect) {
    console.log(`Worker ${worker.id} crashed. \nStarting a new worker...`);
    cluster.fork();
  }
 });

} else {

 // Create a HTTP server
 http.createServer((req, res) => {
  res.writeHead(200);
  res.end('hello world\n');
 }).listen(4000);

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

running the node application in different cpu’s
// to increase the availability of the application
// we create new worker using fork() method if the worker is crushed.
// so that we can increase our applications availability.
if (code !== 0 && !worker.exitedAfterDisconnect) {
    console.log(`Worker ${worker.id} crashed. \nStarting a new worker...`);
    cluster.fork();
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *