# Load Balancers from first principles

# Why talk about load balancers in 2026?

Recently I saw an 8-year-old video by Hussein Nasser sharing his experience playing with nginx on Layer 4 and explaining how it works, this got me curious to dig deeper as before I had just used them as simple reverse proxy for some of my applications to route to correct domains and distribute **traffic** (Which I never got :( ) some of them you might already know (Nginx, Caddy, Traefik) etc ..

The point here isn't to know what they are, which we already know, the point is what happens under the hood and how it works on large scale how it uses round robin, what layers it can work on, Methods to improve its performance for distributing and lowering the chance of failure and to actually build one! more on Here's what this post covers ->

- Getting curious
- L4 vs L7 load balancers
- Round robin, IP hash and least connections
- Building one: health checks, failover and a status endpoint
- Testing it with 486k requests while servers keep dying

## So, let's get curious :)

here is the video I am talking about

[Just Layers](https://www.youtube.com/watch?v=rYqmshzB8rc)

![](https://cdn.hashnode.com/uploads/covers/6690247935c9cc1ced4a7812/b57bac4a-e1fa-4c63-98d4-7eb2075ee2a0.png align="center")

[Watch Full](https://www.youtube.com/watch?v=WC2-hNNBWII)

So, let's get straight to the differences

Layer 7 "the Application layer" is the one which http operates on, now to understand from here you will need an understanding of OSI layers.

So, if a reverse proxy sits onto an http it would redirect you to other http domains you have added to the list of servers you to distribute load to

in simpler words if a room is full put the next half in the another room which you decide or let your load balancer decide using something called as round robin so it's an algo which we all have heard of and it goes like:

let's say I have sever a , b , c and the client request will reach first:

![](https://cdn.hashnode.com/uploads/covers/6690247935c9cc1ced4a7812/2cf78119-bbb5-4509-90d1-9d9711af66ed.png align="center")

a small illustration Claude created for me

```plaintext
Request 1  -> Server A  (A: 1/10)
Request 2  -> Server B  (B: 1/10)
Request 3  -> Server C  (C: 1/10)
Request 4  -> Server A  (A: 2/10)
...
Request 30 -> Server C  (C: 10/10)
Request 31 -> REJECTED  (503, all servers full)
```

But we don't always rely on round robin to work in our favor here is why:

For example:

- Server A might be processing 100 expensive database queries.
- Server B might be completely idle.
- Server C might be processing a simple health-check request. Round Robin doesn't inherently care about any of that.

It simply distributes requests in rotation.

And to solve this problem we use least connections where we distribute traffic depending on the no of connections a server holds called as least connections.

## **Now the cool part**

If I use Layer 4 "Transport Layer"

It primarily works with IP addresses and ports, and it routes whole TCP connections without looking inside them.

In simple words it looks at the IP and port and forwards the real bytes over the TCP to the associated destination, on the other hand we have Layer 7 in which in most cases we add our domains would operate on 2 connections one it initiates with Backend and vice versa. and why it does that ?

has a solid reason which is as being mentioned on TCP layer it doesn't need to look inside the attached content with it but HTTP needs to, it understands your header, body, cookies etc, creates the handshake

Client -> LB7 (reads the HTTP request) -> Backend

Client -> LB4 -> Backend

**So the question why use the layer 4 here if 7 can do the job ?**

- Fast
- Secure and pass the data onto wire as is : doesn't need to terminate TLS
- some eg : databases (MySQL, Postgres), Redis, SSH, game servers, MQTT
- Whereas Layer 7 needs to decrypt it before it sends it

So here is a practical difference between both the Nginx files working on both 7 and 4:

**Seven**

![](https://cdn.hashnode.com/uploads/covers/6690247935c9cc1ced4a7812/a14f774b-c44b-4d84-ba73-affb40369b8d.png align="left")

here I've just got the ip addresses in my upstream list instead of domain names which is normal and I also have routes specific upstreams here which we can understand quickly ->

- **Ip Hash** the sticky session, hashes derived from the client ip address which sticks to a server ip address to stop hopping to different servers useful for caching and memory.
- **Decision routing** uses the route names you saw in the config: `/app1/` routes to ports 2222 and 3333, and `/app2/` routes to 4444 and 5555. This is only an example. In production you'd use it to split services, for instance `/api` and `/web` going to different backends. If you want to balance by load instead, use `least_conn`, which sends each new request to the server with the fewest active connections.

**Four**

![](https://cdn.hashnode.com/uploads/covers/6690247935c9cc1ced4a7812/70f89955-d828-446e-9950-3750c5e0900f.png align="left")

Here you get rid of all the locations because it can't see your URLs and the load balancer picks the backend on its own and it also doesn't have the concept of the ip hash, so the hash remote addr is a consistent replacement here. (Best suited during autoscaling).

# Some hands on now 👐

This is the Challenge I used to understand the dev requirements before coding:\
<https://codingchallenges.fyi/challenges/challenge-load-balancer/>

Here we can split it in 4 main:

- What we need to store and retrieve
- Using Round Robin
- Improving performance and decrease failure chances during higher load of requests and ensure correct routing
- Live testing with 400k+ requests in 30 seconds

You can see the full code on [GitHub](https://github.com/dodaa08/Challenge_load_balancer)

**1\. What we store and how we retrieve it**

A load balancer needs very little state (So it's gonna be a statefull backend). I keep three things:

- The list of backends: ports 9000 to 9049. (you can also hardcode some in start as mentioned in the challenge)
- A map of each backend's status (`true` = healthy, `false` = dead).
- One counter that remembers where we are in the rotation.

```ts
const BACKENDS = Array.from({ length: 50 }, (_, i) => String(9000 + i));
const StatusColl = new Map<string, boolean>();
let current_Index = 0;

BACKENDS.forEach((port) => StatusColl.set(port, true));
```

Also we might add a last_checked map to keep a track of servers which are due with an interval so we know if a dead server's is waiting and is up now we can instantly update it!

Before writing any real code, I needed a way to know which backends are alive. I went through two versions.

**Version 1: the quick, adhoc way**

1. Start a small server.
2. Keep a list of ports (9000 to 9049) and a `Map` of port → healthy (`true` or `false`).
3. Loop over the ports and send a GET request to each one with Axios.
4. Update the map with what comes back.

**Version 2: a proper health check function**

Once the basics worked, I wrote one function whose only job is to check backends and record which are healthy and which are down. I kept 2 things in memory:

```ts
const StatusColl = new Map<string, boolean>();   // port → healthy?
const last_checked = new Map<string, number>();  // port → time of last check

const HEALTHY_EVERY = 10000;  // check healthy servers every 10s
const DEAD_CHECK_MS = 2000;   // check dead servers every 2s
```

How they work together:

1. Every server starts as healthy in `StatusColl`.
2. A timer runs every 2 seconds.
3. For each port, the function looks at `last_checked`. If enough time has passed since the last check, the port is *due*.
4. "Enough time" depends on status: 10s for healthy servers, 2s for dead ones.
5. Only the due ports get a request (with a 2s timeout), and the results update `StatusColl`.

Now till here we have stored our servers correct way on basis of interval and their status so now is the time to retrieve em

#### Round robin: picking the next healthy server

1. We keep a counter, `current_Index`, that remembers where we stopped last time.
2. We start at that position and walk forward through the list of 50 backends, using `% total` to wrap back to the start.
3. At each position we check the map: is this server healthy?
4. At the first healthy one, we move the counter to the position *after* it and return that server. The next request starts from there, so requests take turns.
5. Dead servers are skipped, and if we go through all 50 without finding a healthy one, we return `null` (the caller turns that into a 502).

Checkout the implementation here : <https://github.com/dodaa08/Challenge_load_balancer/blob/main/src/lb.ts> (getNextHealthyServer function).

**Now an interesting fact**

A request body is a stream, so it can only be read once. If the first backend fails, the body is already used up and the retry would send nothing. So I read it once into an `arrayBuffer` and reuse it on every retry.

```ts
const body = req.body ? await req.arrayBuffer() : undefined;
```

`arrayBuffer()` is plain data, so you can send it as many times as you need. Every retry now carries the full body.

![](https://cdn.hashnode.com/uploads/covers/6690247935c9cc1ced4a7812/a4489158-33a3-40af-be9b-0c05aff22789.png align="center")

#### the above code shows how you'd hook the helpers and a retry attempt loop till all healthy servers are present

### **Now About status check and some automated tests for our code** 👾

**Starting from the status endpoint**

A load balancer makes decisions you can't see from the outside. So I added one small endpoint that shows its current view of the backends.

`GET /__lb/status`

bash

```bash
curl http://localhost:3000/__lb/status
```

It returns two lists:

json

```json
{
  "healthy": ["9000", "9001", "9003"],
  "dead": ["9002"]
}
```

`healthy` holds the ports that are in rotation right now. `dead` holds the ports that are marked down and being skipped.

Repo Link : <https://github.com/dodaa08/Challenge_load_balancer>

## **Automated Tests**

## `server.ts`**: the fake backends**

1. Starts 50 small servers on ports 9000–9049.
2. A GET returns `Hello from port X`. A POST echoes the body back as `port X got: <body>`.
3. Every 3 seconds it **kills a random backend**, then revives it 5 seconds later.
4. Result: there are always a couple of dead servers while the test runs, just like real failures.

And

`loadtest.ts`**: the traffic**

1. Runs for 30 seconds with 70 workers going as fast as they can.
2. 50 workers send GET requests and count successes, failures, and which backend answered (`hits`).
3. 20 workers send POSTs, each with a unique payload like `w3-17`.
4. For each POST, it checks that the echoed response ends with the same payload. If not, the body was lost (`bodyLost`).
5. At the end it prints `{ sent, ok, fail, postOk, postFail, bodyLost }`.

```plaintext
loadtest.ts  →  load balancer (3000)  →  50 backends from server.ts
                                          (one dies every 3s)
```

And yes Admit I am using AI here to skim through these implementation details and also any agent can write that for you so lets talk about real outcomes now!

![](https://cdn.hashnode.com/uploads/covers/6690247935c9cc1ced4a7812/bab9c1f8-33b6-420d-82bd-ed642b407483.png align="center")

I ran a 30-second load test while backends were being killed and revived every few seconds. It sent 486,327 requests, about 16,000 per second, mixing GET and POST.

What the numbers mean:

- `fail: 0` and `postFail: 0`: no request failed, even though a backend was being killed every 3 seconds. Failover picked another server each time.
- `bodyLost: 0`: every POST body came back unchanged, including requests that were retried on another server.

and using : bunx autocannon <http://localhost:3000>

![](https://cdn.hashnode.com/uploads/covers/6690247935c9cc1ced4a7812/bfebfdf6-b71d-45a1-b38a-7db4212224a1.png align="center")

Under 10 concurrent connections, the load balancer handled about 23,000 requests per second with a median latency of around 1 ms, while backends were being killed and revived in the background.

Also added 7 correctness tests: round-robin spread, failover, skipping dead servers, recovery, status accuracy, POST body integrity, and a 502 when everything is down. (To test out LB's routing)

**Limitations**: 5xx responses aren't retried, and everything ran on one machine.

**What's** next: weighted round robin or least connections.

**Happy Friday :)**
