Building a Simple Load Balancer Part 2

submited by
Style Pass
2024-04-28 10:00:04

I am quite late on the second part. I had implemented it just after writing the first part but forgot to write the second part. So, here we are.

Checkout the first part, if you haven’t already. It’s nothing fancy, very basic and simple Go. The third iteration of this post (if I get to it) would probably be implementing other algorithms, apart from round robin.

So, we will be running a load balancer (remember, load balancer is also just a server) and forward requests to the servers in the slice or array one by one. Simple right? Let’s dive in.

All that’s left to do is configure the route to redirect or so to say act as a proxy (just like nginx) for the underlying servers.

For selecting the server, we can use modulo (%) operator. The purpose of using the modulo operator (%) here is to ensure that the index variable always falls within the range of valid server indices (0 to len(servers)-1).

We got the address, now we will redirect the request to the desired server. For that, we can use NewSingleHostReverseProxy function from httputil package.

Leave a Comment