Scaling your Nodejs application with Zero Downtime deployment

What do you do when your customers faces a bad experience whenever you deploy a fix or features in production server?

Well, your server may take few seconds to restart. but, it can badly impact your business and chances of losing your potential customers. As a developer, it is our responsibility to make sure that the application has high availability.

This article is going to explain about how you can scale your Nodejs application with Zero downtime deployment.

Let's look into a scenario where the application faces the downtime whenever we deploy a change in the server.

Before Zero downtime

Here we have a simple nodejs application server with pm2 configuration to deploy it in the digital ocean.

1module.exports = {
2 apps: [
3 {
4 name: "app",
5 script: "./app.js",
6 env: {
7 NODE_ENV: "development",
8 },
9 env_production: {
10 NODE_ENV: "production",
11 },
12 },
13 ],

We can deploy the application using the command,

1pm2 start pm2.config.js

Problem with this approach is, whenever we restart the pm2 process manager. it will shut down the entire application and restart it. It can cause the downtime for our application.


To address this problem, we need to use PM2 Cluster mode. PM2 will use fork mode by default. we need to specify in PM2 configuration to deploy them in a cluster mode.

Let's change the pm2 config to use cluster mode,

1module.exports = {
2 apps : [{
3 name: "app",
4 script: "./app.js",
5 instances : 4,
6 exec_mode : "cluster",
7 env: {
8 NODE_ENV: "development",
9 },
10 env_production: {
11 NODE_ENV: "production",
12 }
13 }]
14 }

Here, we have added instances and exec_mode. exec-mode defines the mode that we want to deploy our application. instanced defines the number of instances that we want to run inside the cluster.

Once we are done with configuration changes, we can deploy our application using the command.

1pm2 start pm2.config.js

An important thing to note here is, we were using pm2 restart whenever we deploy a change or features. but now, we need use pm2 reload < app name | id > to deploy them in the cluster mode.

1pm2 reload < app name | id >

After this small change in the deployment configuration. you can see a change in the application downtime. Here's a working example for it.

After Zero downtime configuration

To Read More

Modern React Redux Toolkit - Login ...

User Authentication is one of the common workflow in web applications. In this t...

Building Nodejs Microservice - A Cl...

This Article explains everything about how to build Nodejs Microservices in clou...

I Accidentally wiped the entire dat...

One of the tragic accident in my job turned out to be good learning for me in re...

Never miss a story from us, subscribe to our newsletter