Nodejs cluster to scale application
Hi All, Today we all know the popularity of nodejs, and the reason behind it is in-build modules available in nodejs to perform each and every type of task. Since nodejs is very powerfull to handle request in comparison to other similar technologies and this is the main reason behind its popularity. More or less these are the main reason due to which all types of IT companies work on nodejs.
As we are aware that nodejs runs on single thread, and by default memeroy limit is 512 MB for 32 bit systems and 1024 MB for 64 bit system. Now suppose a situation where due to so high request from front end server gets deadlock situation in normal case, so for handling such situation nodejs provides the option to scale the application. and uses the core of our server and generally a server contains atleast 4 cores.
Suppose we started our application on a port say 3000, Then it runs on single thread and in this case our application don't use the rest 3 cores available in the server. So for utilizing all the cores of the server nodejs provides cluster module and this process is called nodejs clustering.
What is Clustering actually??
Mainly this feature will allow our application to run our application on all the cores available on the server. For example, we are running an application on port 3000, and as I mentioned above that normally it uses single core of the server from the available cores. And here cluster module in nodejs allow us to run the single process on all the cores of the server. So the Cluster module provide a way to easily create the child process, which are spawned by child_process.fork(). child process nothing but your worker process.
Let's see the working code:
In the above code, in line 1 to 5 we have simply required basic modules express and http. In line no. 7 & 9 we have required the module which are actually reponsible for the scaling the application. In 9th line we just counted the number of cores available on server and then finally at bottom applied for loop on the cores count and as per the cores count number of child process created.
Hope this was helpful to you! Thanks alot.
You can download complete code from here. Download Code