Node.js Cluster & WebSocket (ClusterWS?)

Dmitrii G
3 min readSep 25, 2017

--

THIS ARTICLE IS OUTDATED !!!

Node.js is getting more and more popular in development world as well as WebSocket (real time connection), but it is still hard to make WebSocket and Node.js Cluster work well together. In this article I am going to introduce simple, minimalist framework (yes, yes i am a developer) which will make building Node.js Cluster and WebSocket apps easy.

Before we start with framework I would like that you understand what is Node.js Cluster. Of cause the best place to get started is official Node.js documentation. But I know that almost no one is gonna read it properly, so this is main part:

A single instance of Node.js runs in a single thread. To take advantage of multi-core systems the user will sometimes want to launch a cluster of Node.js processes to handle the load. The cluster module allows easy creation of child processes that all share server ports. FROM. Also Node.js processes you can call Workers.

In couple of words it is just : “boost your Node.js app by utilizing all cores of your server computer”.

I hope you understand why Node.js Cluster is awesome :) Next is going WebSocket.

Amm. What to say…. Oh Yes, real time connection you probably have met it a lot before but did not know that it is WebSocket. The basic example is chat, where you send message to the user and user gets it straight away without reloading page.

You can read more about WebSocket HERE (but it is a bit complicated).

Ok, why can’t we make Node.js Cluster and WebSocket work together easily.

If you have two users connected to different Workers in Node.js Cluster, you wont be able to send message from one user to another. Because Workers do not have share state between them. To solve this problem you may need to develop your own share state between Workers by using Redis or some other libraries to handle your messages between Workers. After all of that your code may get bulky, confusing and during development you may meet a lot of complications with WebSocket.

Eventually time of ClusterWS (yes it is the name of the framework, you probably have noticed that already, in the top left corner). So what does it do? If you want to build salable Node.js and WebSocket app this framework makes your life much easier. ClusterWS allows in couple of lines create Workers (as many as you want) in Node.js Cluster , and in each worker set up WebSocket connections. Also with ClusterWS you can use any other libraries for REST like Express, Koa, etc. To learn more about ClusterWS i would strongly recommend to read README on GitHub.

Example Chat built with ClusterWS:

--

--