
Node.js clusters and multithreading
Any Node.js instance runs in a single thread. If any error occurs, the thread breaks, the server stops, and you need to restart the server. To take advantage of all the cores available in a system, Node.js provides an option to launch a cluster of Node.js processes so that the load is evenly distributed. There are many tools available that do the same thing. We will look at a basic example and then learn about automated tools such as PM2. Let's get started:
- The first step is to create an express server. We will need express, debug, body-parser, and cookie-parser. Open up a Terminal and hit the following:
npm install body-parser cookie-parser debug express typescript --save
- Next, we download the types for these modules:
npm install @types/debug @types/node @types/body-parser @types/express
- Then, we create our app.ts and www.ts files. Construct your app.ts file as follows:

Express the TypeScript way
- For www.ts, we will use the cluster module and create workers available as a number of cores. Our logic would be pided as follows:
import * as cluster from "cluster";
import { cpus } from "os";
if (cluster.isMaster) {
/* create multiple workers here cpus().length will give me number of cores available
*/
cluster.on("online", (worker) => { /*logic when worker becomes online*/ });
cluster.on("exit", (worker) => { /*logic when worker becomes online*/ });
} else {
//our app intialization logic
}
- Now when we transpile the source and run www.js, we will see multiple workers online.
Complete files can be found at node-clusters/src/bin/www.ts. Go and run the application. You should see multiple workers online now.
An alternative approach is to use PM2 (https://www.npmjs.com/package/pm2). PM2 has various options for livereload, reload with zero downtime, and starting mode in clusters. Some sample commands available in PM2 are as follows:
