Categories
JavaScript Tutorials

Understanding the Dynamics of Node.Js Cluster

If you are a seasoned developer for quite a while and not living under the rocks then you must be aware of Node.Js and how it has emerged as a standalone platform for running single-threaded architecture, even though files and network events could leverage multiple threads. This implies that it will only perform one function at a time, while rejecting the other. This architecture thereby easily binds the performance of each application to a common CPU core that the thread is connected with.

node-js

However, the process is good up to the point where we are okay with the way our app is handling the requests well while working on a single-threaded mode. But, there are times when the amount of traffic gets increased, and it becomes difficult to handle multiple requests simultaneously and that too in a very fast manner. In such a scenario, what we can do?

Alright, this is a time when the role of Node.Js cluster becomes prominent. It’s a program which improves the default single-threaded nature of Node.js by providing a cluster module. The cluster module allows you to create a small network of some individual processes which can conveniently share server ports; this will in return gives a complete level of control and power to your server.

Cluster module of Node.js makes it extremely easy and straightforward for applications that have either little or new sharing state. Or they have to save their data into some external source like database or a web service.

In this guide, we are going to discuss about the nuts and bolts of Node.Js cluster module and how it can be used to establish a multi-process architecture with an absolute ease.

1. Getting Started with The Master Process

The cluster module is basically comprised of master-slave/parent-child paradigm. So, to get started with the cluster module, we need to first encounter the master process. As the name suggests, the master process is the main controller of all the processes which can launch new programs called workers with a call to cluster.fork (), or many other related “workers” which are expected to perform common functions. This is how the program looks:

var http = require(“http”);

var cluster = require(‘cluster’);
if (cluster.isMaster) {
var worker = cluster.fork();
}
else {
http.createServer(function(req, res){
res.end(“Hello World”);
}).listen(1337);
}

In the snippet above, you can see we have used the ‘cluster.isMaster’ to start the process. Since, cluster.isMaster is necessary so, be sure you are forking it simultaneously. We can now begin with the new process via ‘else’ block and start creating the child process, whose main objective is to perform the functions related to the server porting. However, you can see that the process we have mentioned above is going to create only two processes: one child and one master, where master performs nothing other than launching the child processes.

nodejs-mysql

2. Let’s Write Code for Multiple Child Processes and Control It Via Master

The next section of this guide is dedicated to creating multiple processes while ensuring that all of them are terminated as and when the master process is brought to an end.

var http = require(“http”);

var cluster = require(‘cluster’);
if (cluster.isMaster) {
var workers = [];
for(var i=0; i<5; i++) {
workers.push(cluster.fork());
}
process.on(‘SIGINT’, function(){
console.log(“exiting “+process.pid);
for(var i=0; i<5; i++) {
console.log(“destroying “+worker.process.pid);
workers[i].destroy();
}
});
}
else {
console.log(“Child process “+process.pid+” being created and listening to port 1337″);
http.createServer(function(req, res){
res.end(“Hello World”);
}).listen(1337);
}

In the above code, you can observe, we have created total five processes and list them to a common 1337 port. As far as the master process is concerned, it is also performing some crucial tasks and also taking care of when should be the entire process terminated. This way, there will be no orphan program be left around the entire system.

Now, all these programs will be able to share a common server porter and can be listened together. Now, we don’t have to worry much if out of five programs 4 are busy in their own work. It still has enough space to accept the requests made by the fifth one.

3. Rectifying the Errors and Failures

There are situations when the Node.Js app gets crashed or doesn’t perform well due to some errors within the process. In such cases, majority of the times we use ‘supervisord’ software, which closely monitors the situation and restarts everything automatically if the process gets crashed or faces some performance related issues. To make sure that your application is always running accurately, there is another method, which we can use internally. Here’s how we can do that:

var child = cluster.fork();
cluster.on(‘exit’, function (worker, code, signal) {
//logging details about what happend
child = cluster.fork();;
});

in the above process, as and when an exit event become alive, the master process will launch new child programs, to ensure an equal availability of the entire processes.

4. Eliminating The Guess Work

To master the Node.Js app, it is important for us to first learn the art of determining the number of child processes we wish to create and everything that matters. This way, you’ll be able to save your time and efforts when it comes to playing around Node.Js. For this, you can use “clustered-node” library, which allows you to strengthen and ease the whole processes of creating your nodejs/server application in multi-process clustered mode.

5. Wrapping Up

If you are yet to master the Node.js and its cluster module, it’s a good time to get started. Hopefully, you find the guide useful in gaining an in-depth understanding of Node.js cluster and everything you could possibly learn about it.

For more Web Tutorials, Check ValuableTuts.com!

Author Bio – Being a well-known blogger from Markupcloud Ltd., Mike gives valuable and best tips on context of PSD to WordPress theme conversion and design technique. Also, he is enthusiast of sharing his innovative ideas related to web design technologies.

By Creative Alive Staff

is here to write about latest trendy web designing and development tips and techniques which are used to produce a good brand or product in market. We are energetic and having zeal knowledge of simple tutorials, time-saving methods. Hope we will help you to make web better and alive enough. Lets spread some creativity out there... Cheers!!!

One reply on “Understanding the Dynamics of Node.Js Cluster”

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.