Using the Node.js cluster
Node.js comes with a cluster package that can be used to run Node on multiple threads, as opposed to the single thread that it runs on normally. The child processes that cluster creates will all be able to run on the same port, which means that you can effectively load-balance without running your server on multiple ports.
Unfortunately, there is some boilerplate needed to determine the number of CPUs available to run Node processes and fork the original node. For this, we can use a module called sticky session. This is a load balancer that automatically spawns and manages multiple node sessions with the cluster module.
Getting ready
For this recipe, we will use the sticky session npm module. This can be installed by running npm install sticky-session
.
How to do it…
To create a Node server using sticky session, follow these steps:
Begin by requiring your dependencies. This will include the sticky session module and cluster that is installed along with the node. We will...