Create a Node cluster with Koa and TypeScript

Cluster

Any JavaScript program runs in single OS process but of course is able to process requests asynchronously.  On the Node server we are able to start multiple processes.  To do that we use cluster module, so you are not really limited to one CPU core anymore.

Before start you need to install project prerequisites:

If you need help with basic project setup look at this blog article where I describe basic setup steps.

Create Koa web server application

The purpose of this server application is for testing cluster technology only.  The application support two routes , first is default route (/) for checking on which process runs and another (/stop) for stopping active process. The console log show workers statuses from starting , stopping and restarting.

If you want to debug this server application just create simple index.ts and start the ServerRun class.

Create cluster server start

To start this server in the cluster we need to fork process workers and start koa application.

To start this server we need to compile everything to TypeScript first and then start node with “run_cluster” procedure.

As we see on the console the server start multiple processes and listen on the same port. Well, that’s whole point, to be able to send requests to the same address and server will divide load to multiple processes.

Test the server

Now if you go to browser and navigate to “localhost:3002/”, the server will respond with value of the current process id and count variable. Try refreshing multiple times, the counter will always increase by 1. If you then kill the process and navigate again, you will get another process id and the counter will start again with one. Each process has his own Koa application instance.

Kill the process and test server robustness

If you navigate to “localhost:3002/stop”, you will essentially kill current process. After irrecoverable failure on the server process,  cluster “exit” event is triggered and we simply start new process again.

 

 

Leave a Reply

Your email address will not be published.