Load balancing explained: algorithms, health checks and L4 vs L7 load balancers

A load balancer spreads requests across many servers so no single one gets crushed, and quietly steps around the ones that break. Learn how load balancers work, round robin vs least connections, health checks, sticky sessions, Layer 4 vs Layer 7, and how load balancing fails.

A restaurant host stands at the door with a clipboard, sending a queue of customers to four tables, each with its own waiter. Three waiters are serving calmly. The fourth table has a 'closed' sign and the host sends no one there. A banner reads 'Who takes the next request?'
Fig. 1 — A load balancer is the host at the door: it spreads the customers out, and stops seating people at a table whose waiter has gone home.

Picture a restaurant with five waiters, and 100 hungry customers walk in at once. If every customer heads to the same waiter, that waiter collapses while the other four stand around. Nothing is wrong with the kitchen. The problem is who serves whom.

Software has the same problem. One server can only handle so much: so many requests per second, so much memory, so much network. And if it’s your only server, it’s a single point of failure. When it slows down, every user feels it. When it dies, everything is down.

The fix is to run several servers and put a load balancer in front of them. This article opens the Load, traffic & protection thread: how to spread work fairly, and how to protect a system from being overwhelmed.

What a load balancer does

A load balancer sits between users and your servers. Every request goes to the load balancer first. It picks a healthy server, forwards the request, and passes the response back. Users only ever see one address. They never know there are ten servers behind it.

Users send requests to one address, the load balancer. The load balancer forwards them to three servers. Server 1 and server 2 have green ticks. Server 3 has a red cross because it failed its health check, and the load balancer sends it no traffic. Every few seconds the load balancer calls GET /health on each server to check it's alive.
One address in front, many servers behind. Health checks tell the load balancer which servers to skip.

That simple idea fixes four problems at once:

  • More capacity. If one server handles 1,000 requests a second, ten servers behind a load balancer handle about 10,000. This is horizontal scaling.
  • Higher availability. If one server crashes, the others keep serving. Users don’t notice.
  • No-downtime deploys. Take servers out one at a time, update them, and put them back.
  • Lower latency worldwide. A global load balancer can send a user in India to a data centre in Mumbai instead of Virginia.

Load balancing algorithms

The load balancer’s one real decision is: which server gets the next request? The rule it uses is its load balancing algorithm.

Round robin

Take turns: server 1, server 2, server 3, then back to server 1. It’s simple, fair and predictable, and it’s the default in most load balancers.

It works well when all servers are the same and all requests cost about the same. It goes wrong when they don’t.

Weighted round robin

Same idea, but stronger servers get more turns. Give a big server weight 3 and a small one weight 1, and the big one gets three requests for every one the small one gets. Useful when you have mixed server sizes, or when you’re slowly moving traffic to a new version.

Least connections

Send the request to the server with the fewest requests in progress right now. A server stuck on a slow request has more open connections, so new work flows to the servers that are free.

Two panels with the same three servers. Some requests are quick (1 ms) and some are slow (1 second). Left, round robin: requests take turns, so server 2 keeps getting slow requests on top of slow requests, and its queue grows to 5 while servers 1 and 3 sit almost idle. Right, least connections: each new request goes to the server with the fewest active requests, so the slow ones spread out and every server has 2 in progress.
Round robin counts requests. Least connections looks at how busy each server actually is.

This is the better choice when request times vary a lot, and for long-lived connections like WebSockets and streaming. A close cousin, least response time, picks the server that has been answering fastest lately.

IP hash and consistent hashing

Hash something about the client, like its IP address or user ID, to pick the server. The same user always lands on the same server, which is useful for keeping a user’s cache warm on one machine.

Two catches. With a simple hash % number_of_servers, adding or removing one server reshuffles almost every user. Consistent hashing fixes that, so only a small slice moves (we covered it in sharding strategies). And many users behind one office or mobile network can share one IP, which turns one server into a hot spot.

Random, and the “power of two choices”

Pick a server at random. With many servers it evens out surprisingly well. A smart twist: pick two servers at random and send the request to the less busy of the two. This tiny change gets you close to least connections, with very little tracking.

Which algorithm to use

Algorithm Picks the server that… Best for Watch out for
Round robin is next in turn identical servers, similar requests ignores how busy servers are
Weighted round robin is next, with more turns for big servers mixed server sizes, gradual rollouts weights must be kept up to date
Least connections has the fewest active requests uneven request times, WebSockets needs connection tracking
Least response time is answering fastest servers that slow down unevenly more tracking work
IP / consistent hash the client’s hash maps to keeping a user on one server hot spots, uneven spread
Power of two choices is less busy of two random picks large fleets none major; a great default at scale

If you don’t know where to start: round robin for simple stateless services, least connections once request times vary.

Health checks: stepping around broken servers

A load balancer is only useful if it stops sending traffic to broken servers. It finds them with health checks.

  • Active health checks: every few seconds, the load balancer calls something like GET /health on each server. Fail 2–3 checks in a row, and the server is taken out. Pass again, and it comes back.
  • Passive health checks: the load balancer watches real traffic. If a server starts returning errors or timing out, it’s pulled out, even if /health still says “fine”. (Envoy calls this outlier detection.)

A good health check answers “can this server do real work?”, not just “is the process running?”. Check what the server truly needs, like its database connection. But be careful about checking every downstream service: if a shared dependency blips, every server fails its check at once, and the load balancer takes them all out.

In Spring Boot, Actuator gives you this for free: /actuator/health reports UP only if the app and its database connection are healthy. Point the load balancer’s health check at it.

Layer 4 vs Layer 7 load balancers

Load balancers come in two kinds, named after the network layer they work at.

Two panels. Left, a Layer 4 load balancer sees only an envelope: source IP and port, destination IP and port. It forwards the whole connection without opening it. Fast, works for any protocol, but can't route by URL. Example: AWS Network Load Balancer. Right, a Layer 7 load balancer opens the envelope and reads the HTTP request: GET /api/orders, the Host header and a cookie. It can send /api to the API servers and /images to the static servers. Smarter, but more work per request. Examples: Nginx, AWS Application Load Balancer.
Layer 4 reads the envelope. Layer 7 reads the letter, so it can route by what's inside.

Layer 4 (transport layer) load balancers work with TCP and UDP connections. They see IP addresses and ports, nothing more. They forward the connection without reading the request.

  • Good: very fast, very cheap per request, and work with any protocol: HTTP, gRPC, databases, games.
  • Limit: they can’t see the URL, headers or cookies, so they can’t route by them.
  • Examples: AWS Network Load Balancer (NLB), HAProxy in TCP mode.

Layer 7 (application layer) load balancers understand HTTP. They read the URL, headers and cookies.

  • Good: smart routing (/api to one group of servers, /images to another), SSL/TLS termination (decrypt HTTPS once, at the edge), cookie-based sticky sessions, and rich logs.
  • Limit: reading every request costs more CPU and adds a little latency.
  • Examples: Nginx, HAProxy in HTTP mode, Envoy, AWS Application Load Balancer (ALB).

Here’s path-based routing in Nginx, something only a Layer 7 load balancer can do:

# nginx.conf
upstream api_servers    { least_conn; server api1:8080; server api2:8080; }
upstream static_servers { server static1:8080; server static2:8080; }

server {
    listen 80;
    location /api/    { proxy_pass http://api_servers; }
    location /static/ { proxy_pass http://static_servers; }
}

Rule of thumb: for web apps and microservices, use Layer 7. Reach for Layer 4 when you need raw speed, huge numbers of connections, or a protocol that isn’t HTTP.

What breaks, and how to fix it

What breaks What you see The fix
The load balancer itself dies Everything is down, even though every server is fine Run load balancers in pairs (one takes over with a shared floating IP), or use a managed one like AWS ALB that runs across several availability zones
A slow server still gets traffic A server that hangs for 30 s still gets its share, so a slice of users waits Use passive health checks on errors and latency, plus short timeouts; use least connections so busy servers get less
Every server marked unhealthy A shared dependency blips, all health checks fail, and the load balancer has nowhere to send anything Keep health checks focused on the server itself. Many load balancers fail open: if all servers look unhealthy, send to all of them rather than none
DNS points at a dead load balancer Clients keep using an old cached IP after a failover Low DNS TTLs (seconds to minutes), and clients that re-resolve DNS on connection errors. The JVM’s networkaddress.cache.ttl setting controls this in Java
A sudden traffic spike A TV ad or viral post sends 10x traffic, and every server maxes out Auto-scaling (for example a Kubernetes HorizontalPodAutoscaler), plus rate limiting and a queue to absorb bursts

Puzzle 1: equal requests, unequal load

Requests are not equal in cost. Suppose server 2 happens to get the report downloads, and the others get quick page views:

  • Server 1: 1,000 requests × 10 ms = 10 seconds of work
  • Server 2: 1,000 requests × 500 ms = 500 seconds of work
  • Server 3: 1,000 requests × 10 ms = 10 seconds of work

Round robin balances the number of requests, not the work. Switch to least connections or least response time, so busy servers naturally get less. And monitor CPU and active requests per server, not just request counts.

Puzzle 2: the vanishing shopping cart

The cart lives in one server’s memory. Request 1 goes to server 1, which stores the cart. Request 2 goes to server 2, which has never heard of it.

Two fixes:

  1. Sticky sessions: the load balancer sends each user back to the same server, usually using a cookie. Quick to set up, but load gets uneven, and if that server dies, its users lose their carts.
  2. A shared session store (better): keep sessions in Redis or the database, so any server can serve any user. In Spring, @EnableRedisHttpSession does this with almost no code. Your servers become stateless, which is what makes load balancing easy.

Puzzle 3: one crash becomes three

The system had no headroom. With three servers it was at 97% of capacity. With two, the same 2,900 requests a second hit just 2,000 of capacity, 145% load. Both remaining servers overload and fall over. This is a cascading failure, and the load balancer did nothing wrong.

The fix is capacity planning:

  • Leave headroom. Size the fleet so it survives losing a server. With three servers, stay under about 60% each, so losing one puts the others at about 90%, not over 100%.
  • Auto-scale to replace lost capacity quickly.
  • Shed load when you’re over capacity: reject some requests quickly with 503 instead of letting everything slow down and die. More on that in the next article.

Key takeaways

  1. A load balancer spreads requests across many servers behind one address. You get capacity, availability, zero-downtime deploys and lower latency.
  2. Round robin is simple and fine for equal servers and equal requests. Least connections is better when request times vary.
  3. Hashing keeps a user on one server; use consistent hashing so adding a server doesn’t reshuffle everyone.
  4. Health checks decide which servers get traffic. Use active and passive checks, and don’t let one shared dependency fail them all.
  5. Layer 4 is fast and works for any protocol. Layer 7 reads HTTP, so it can route by URL and terminate TLS.
  6. Keep servers stateless (sessions in Redis), make the load balancer itself redundant, and leave headroom so losing one server doesn’t take the rest down.

This opens the Load, traffic & protection thread. Spreading traffic is the first half. Next, we’ll look at traffic control: rate limiting, throttling and load shedding, the tools that protect a system when there’s simply too much traffic to serve.

Comments

LEAVE A COMMENT
No sign-up. Comments appear after a quick review.