Load Balancing

How load balancers distribute requests, how layer 4 and layer 7 balancers differ, how health checks work, and what interviewers ask about them.

17 minLesson 2 of 6
On this page
  1. Where a load balancer sits
  2. Layer 4 and layer 7 load balancers
  3. Choosing a server: balancing algorithms
  4. Health checks and removing a failed server
  5. Problems that interviewers probe
  6. In the interview
  7. What to practise next

A load balancer sits in front of a group of identical servers and decides which one handles each connection or request. It lets a service use more than one server, and it keeps the service running when a server fails, because it stops sending traffic to servers that do not respond.

Without one, clients would have to choose among the servers themselves, with no way to tell which are down or busy. A single server would limit capacity and take the whole service down when it fails.

Where a load balancer sits

Clients connect to one address. The active balancer spreads requests over the app servers, and a standby balancer takes over the address if the active one stops sending heartbeats.Clients to Load balancer (active) (virtual IP); Load balancer (active) and Load balancer (standby) (heartbeat); Load balancer (active) to App servers; App servers to Database.ClientsLoad balancer(active)Load balancer(standby)App serversDatabasevirtual IPheartbeat
Clients connect to one address. The active balancer spreads requests over the app servers, and a standby balancer takes over the address if the active one stops sending heartbeats.

Layer 4 and layer 7 load balancers

Layer 4

A layer 4 balancer works with TCP or UDP. It sees source and destination addresses and ports, and nothing inside the stream. When a client opens a connection, the balancer picks a server once and forwards every packet of that connection to it. It is fast and works for any protocol, and it usually passes TLS through to the servers.

The unit of balancing is the connection, not the request, so a client that sends ten thousand requests down one connection keeps all of them on one server. It also cannot route by URL. Pick it for non-HTTP protocols and when traffic must stay encrypted to the server.

Layer 7

A layer 7 balancer terminates the client's connection, reads each HTTP request and forwards it over a connection of its own. Because it reads the request, it can route by hostname, path or header, so that /orders and /users go to different server groups. It can also retry a failed request on another server.

It usually terminates TLS, so the certificates live in one place and the servers receive plain HTTP over the internal network. It costs more CPU than layer 4, and it is the usual choice for web applications and APIs.

HTTP/2, gRPC and long-lived connections

HTTP/2 and gRPC send many requests at once over a single connection. A layer 4 balancer spreads the connections evenly while the requests are spread badly: a heavy client with one gRPC connection sends all its calls to one server while the others sit idle. A layer 7 balancer balances each request separately.

For the same reason, the number of connections is a poor measure of load with HTTP/2: one server can hold two connections that each carry hundreds of requests, while another holds twenty nearly idle ones.

WebSocket connections are long-lived. The balancer chooses a server when the connection opens, and the connection may last for hours, so the load never adjusts. Use least connections, close connections after a maximum lifetime, and make clients reconnect after a random delay.

Choosing a server: balancing algorithms

Round robin

The balancer sends requests to the servers in a fixed rotation and needs no information about them. It works well when requests cost about the same, but a server stuck with slow requests still receives its full share of new ones.

Weighted round robin

Each server has a weight, and a server with weight 3 gets three requests for each one that a server with weight 1 gets. Use it when servers have different sizes, or to send a small share of traffic to a new version in a canary release. The weights are set by hand and do not react to load.

Least connections

The balancer sends the request to the server with the fewest open connections. A busy server accumulates connections and receives fewer new ones, so this adapts to slow requests and suits WebSockets. Its weaknesses are the HTTP/2 problem described above, and that a newly started server has no connections, so it is flooded before it has warmed up. A slow-start setting raises a new server's share gradually.

Least outstanding requests

This is least connections with the right unit. The balancer counts the requests it has sent to each server and not yet seen answered, and chooses the server with the fewest. It counts work instead of connections, so it handles HTTP/2 and gRPC correctly, but it needs a layer 7 balancer.

Least response time

The balancer favours the server that has answered fastest recently, which routes around a server that is slow for a hidden reason such as a failing disk. A server that fails instantly looks fastest, so failed requests must count as slow.

Hashing and consistent hashing

The balancer hashes a key, such as a user id or a cache key, and the hash picks the server. The same key always reaches the same server, which keeps that server's local cache or state useful, so it suits cache shards. Its problems are that a popular key overloads one server, and that hashing by client IP is lopsided because many users share one address. With plain hash % n, adding or removing a server changes the result for almost every key. Consistent hashing places servers and keys on a ring so that only about one key in n moves.

Power of two random choices

The balancer picks two servers at random and sends the request to the one with fewer outstanding requests. It needs no view of every server, which matters when many balancers each see part of the fleet, and it spreads load far more evenly than one random choice. Because different balancers compare different pairs, it avoids the herding described next.

Why sending traffic to the lowest CPU is a poor rule

CPU readings are always old, because servers report them every few seconds. During that time every balancer sees the same server as the least loaded, so all of them send it new traffic and it is overloaded within one interval. This is herding: many deciders act on the same stale information and make the same choice. Counting the requests the balancer itself has sent uses information that is always current.

Health checks and removing a failed server

An active health check is a request that the balancer sends to each server on a timer, for example GET /health every five seconds. A passive check watches real traffic and removes a server that returns errors or times out. A passive check reacts within one request, and an active check finds idle failed servers and brings recovered ones back, so balancers normally use both.

Detection takes time. The worst case is the check interval multiplied by the number of failures required, plus the timeout, so checks every 5 seconds that need 3 failures take about 15 seconds.

Liveness and readiness

A liveness check asks whether the process is running at all, and a failure means it should be restarted. A readiness check asks whether the server can take traffic right now. A server that is still starting or is shutting down is alive but not ready. The balancer should route by readiness, because routing by liveness sends traffic to servers that cannot serve it, and restarts should use liveness, because restarting on readiness kills servers that are only briefly busy.

A health check that removes every server at once

If the health endpoint also queries the database and the database becomes slow, every server fails its check in the same interval and the balancer removes all of them. The endpoint should test only whether this server can do its own work. A panic threshold also helps: when too many servers are unhealthy, the balancer ignores the checks and sends traffic to all of them, which is better than sending it to none.

Problems that interviewers probe

Sticky sessions or stateless servers

If a server keeps a user's session in its own memory, every request from that user must reach that server. A balancer can do this with a sticky session, for example a cookie that names the server. The load then becomes uneven, and the session is lost when the server dies or is replaced in a deploy. The better design is stateless servers, with the session in a shared store or in a signed token that the client sends. Any server can then handle any request, and a crash loses nothing.

The load balancer itself fails

One balancer is a single point of failure. The common fix is an active and a standby balancer that share a virtual IP address and exchange heartbeats, as in the diagram above; when the standby stops hearing heartbeats, it takes over the address. At larger scale, several balancers sit behind DNS that returns more than one address, or share one address announced from several locations (anycast).

Deploying without dropping requests

To replace a server, the balancer first stops sending it new requests and waits for the requests in progress to finish. This is connection draining. Without draining, every deploy cuts off the requests running on the server being replaced.

Retries and retry storms

A balancer can retry a failed request on another server, which hides most single-server failures. Retries are safe when the request never reached a server, such as a refused connection, or when the operation is idempotent, because retrying a payment that timed out can charge the customer twice. Retries can also cause an outage, because overloaded servers receive each failed request again. If a client, a gateway and a service each retry three times, one request becomes 27. Limit retries to a small share of traffic, use exponential backoff with jitter, and retry at only one layer.

Capacity for the failure case

Servers must be sized for the load that remains after a failure, not for the normal load. If four servers each run at 80 percent and one fails, the other three must carry 107 percent of their capacity, so they overload and fail too. If the servers are spread over three zones and one zone may fail, each zone can run at no more than about two thirds of its capacity, because the other two must carry everything.

Load balancer, reverse proxy and API gateway

A reverse proxy accepts requests on behalf of servers and can terminate TLS, compress responses and cache them. A layer 7 load balancer is a reverse proxy that also spreads requests. An API gateway is a layer 7 proxy that adds API concerns: authentication, rate limiting and routing each path to a different service.

Load balancing and autoscaling

The balancer spreads traffic across the servers that exist now and reacts to a failure in seconds. Autoscaling changes how many servers exist and reacts in minutes, because a new server has to start, warm up and pass its health checks. A sudden spike reaches the existing servers before new ones arrive, so spare capacity is still needed.

In the interview

Draw a load balancer as soon as there is more than one server, and give your choices with reasons: "A layer 7 balancer, least outstanding requests, health checks that test only the server itself, and stateless app servers, so that I can add and remove servers freely."

Questions to expect:

  • "What is the difference between layer 4 and layer 7?" Layer 4 forwards connections using only addresses and ports, so it is fast but cannot route by URL and balances connections, not requests. Layer 7 reads each HTTP request, so it can route by path, terminate TLS, retry and balance each request separately, at a higher CPU cost.
  • "Which algorithm would you use?" Round robin when requests are short and alike, and least outstanding requests when their cost varies. Use consistent hashing when a key must reach the same server.
  • "Why not send traffic to the server with the lowest CPU?" The reading is stale by the time it is used, so every balancer picks the same server and overloads it. Count the requests the balancer has sent and not yet seen answered instead.
  • "What if every server fails its health check at once?" The check probably tests a shared dependency. Make it test only the server itself, and set a threshold above which the balancer stops removing servers.
  • "Retries made the outage worse. Why?" Every failed request is sent again, so overloaded servers receive extra load. Retry only idempotent requests, with backoff and jitter, within a retry budget, and at one layer only.
  • "How do you keep the load balancer from being a single point of failure?" Run a standby that shares a virtual IP address with the active balancer and takes it over when heartbeats stop. At larger scale, run several active balancers behind DNS that returns more than one address, or behind an anycast address.
Errors after every deployStrong answer
Interviewer

After each deploy a few users get errors, and then it stops. What would you check?

You

I would check whether the balancer drains connections. If a server is stopped while requests are running on it, those requests fail. I would remove the server from the pool, wait for in-flight requests to finish, and only then restart it.

Interviewer

That works, but now new servers are overloaded right after they join.

You

That fits least connections, because an empty server looks like the least loaded one and is flooded. I would turn on slow start so its share rises over a minute.

Quick check

Three clients each keep one long-lived gRPC connection to a service behind a layer 4 balancer, and one client sends far more calls than the others. What happens?

A health endpoint queries the database, and the database slows down for a minute. What can happen?

What to practise next

Read Caching next, and Design a URL Shortener to see a balancer in a full design.