Building a Load Balancer using Node JS + Express

In this article, we will see what is a load balancer, why we should use it, and when we should use a load balancer.

First of all, let’s see when one should use a load balancer

you don’t need a load balancer if your application or website doesn’t get a lot of traffic or requests, but if it does and become more popular, your underlying server might not be able to manage the increased demand, because a single Node JS server is not flexible enough to handle very large amount of traffic.

This problem can be fixed by adding more machines. but a load balancer is required to split traffic among all of your application servers.

What is a Load Balancer?

A load balancer is a software component that sits between the client and server and distributes incoming requests across multiple servers. It monitors the health of each server and routes the incoming requests to the most available and healthy server.

Load balancers can be implemented in different ways, such as hardware appliances, software appliances, or cloud-based services. In this post, we will focus on how to implement a software load balancer in Node.js and build a balancer using Node js.

Building a Load Balancer

First off, let’s install express and request npm packages by running the below command.

npm install express request

Now, in the next step will create two files server.js for the application server and lb.js for the load balancer server.

server.js:

Explanation: To simplify things, we have created a server.js file to launch two Express application servers, one on port 3000 and the other on port 3001. Sending one request to port 3000, the next to port 3001, and the next back to port 3000.

The separate load balancer process should go back and forth between these two. so let’s create a load balancer file.

lb.js:

We have built a load balancer in this lb.js file that runs on port 8080. It includes a list of the application servers that we have set up on the server.js file. All incoming requests will be routed one by one to the application servers using our load balancer.

Finally, our servers are ready, our load balancer is ready to route our traffic, so let’s test our application.

Open a command prompt on your project folder, execute node lb.jsto start the load balancer server, and then in a separate terminal execute node server.jsto start the application server.

Now, open a browser and go to http://localhost:8080/ and make a few requests, you will see the following output in the console:

That's it for this topic. Thank you for reading.

Enjoyed this article?

Share it with your network to help others discover it

Continue Learning

Discover more articles on similar topics