Scaling node.js application with cluster
node.js’s single thread default architecture prevents it from utilizing multi-cores machines. When you create a new
node.js application in WebStorm for example, this is what you get:
This code snippet will create a simple HTTP server on the given port, executed in a single-threaded process; doesn’t matter how many cores your machine has. This is where
cluster comes in.
cluster allows you to create multiple processes, which can share the same port. Ideally, you should spawn only 1 thread per core.
That’s how you do it on a single machine. With a few more lines of code, you application can now utilize better modern hardware. If this isn’t enough and you need to scale across machines, take a look at load balancing using
nginx. I will cover that in another post.