Load balancers

Topic 3 of 8 in Week 2: Scaling, traffic and estimation11 min readBeginnerFree course

Overview

Once you have more than one server, something must decide which server handles each request. That’s the load balancer. It is the first component you add when scaling out, and it appears in nearly every design diagram. This lesson covers what it does, how it chooses servers and the two main kinds.

What a load balancer does

  • One front door. Clients connect to a single address (a DNS name or IP), not to individual servers.
  • Spreads the work. Each request or connection goes to one of the servers behind it, often called the pool or target group.
  • Health checks. Every few seconds it calls each server (for example GET /health). Servers that fail a few checks in a row stop receiving traffic until they recover.
  • Hides changes. You can add, remove or replace servers without clients noticing.

Many balancers also terminate TLS, retry failed requests, enforce timeouts and collect metrics.

How it picks a server

Three load-balancing strategies. Round robin sends each request to the next server in turn, which is good for equal servers and short requests. Least connections sends each request to the server with the fewest active requests, here Server 2 with 2 active against 5 and 7, which is good for uneven or long requests. Hashing on a key such as the user ID sends the same key to the same server, which is good for affinity and local caches. All three skip servers that fail health checks; week 3 shows how consistent hashing limits reshuffling.

Round robin

Servers take turns: 1, 2, 3, 1, 2, 3… It’s simple and works well when servers are identical and requests are short and similar. Weighted round robin gives bigger servers a larger share.

Least connections

Each new request goes to the server with the fewest active requests. This adapts when some requests are slow (a report export next to a quick profile lookup), so one server doesn’t pile up long jobs while others sit idle. A close cousin, least response time, also considers how fast each server has been answering.

Hashing on a key

The balancer hashes something from the request (the client IP, the user ID or a cache key) and maps it to a server, so the same key always lands in the same place. This is useful when servers keep per-key state, such as a cache shard or a chat connection.

Plain hash(key) % N has a problem: when N changes, almost every key moves to a different server. Consistent hashing fixes that and is covered in week 3.

Random and “power of two choices”

Picking a random server is surprisingly decent at scale. Picking two random servers and sending the request to the less busy one performs close to least connections, without the balancer tracking every server precisely. Large distributed balancers use this trick.

Layer 4 vs layer 7

Layer 4 versus layer 7 load balancing. A layer 4 balancer sees only the source and destination IP addresses and ports, with encrypted bytes it cannot read: it is very fast and works for any protocol but can’t route by URL or header. A layer 7 balancer reads the HTTP request, such as the path /api/videos/42, the host and cookies: it can route /api and /images to different services, terminate TLS, retry and cache. A typical setup puts an L4 balancer or cloud network load balancer at the edge with L7 balancers or an API gateway behind it. Examples: AWS NLB and HAProxy in TCP mode for L4; AWS ALB, NGINX and Envoy for L7.

The “layers” come from the networking model in week 1:

  • Layer 4 (transport): works with TCP or UDP connections. It sees IP addresses and ports, picks a server and forwards the bytes without reading them. It’s extremely fast, handles any protocol (databases, game traffic, raw TCP) and can serve millions of connections.
  • Layer 7 (application): understands HTTP. It can route /api/* to one service and /images/* to another, send traffic by host name, read cookies for sticky sessions, rewrite headers, retry a failed request on another server and cache responses. It does more work per request, so it costs more CPU.

In interviews, “a load balancer” usually means an L7 HTTP balancer. Mention L4 when the traffic isn’t HTTP or when raw throughput is the concern.

Deploys and connection draining

When you remove a server, for a deploy or a scale-in, requests may still be running on it. Connection draining (or deregistration delay) tells the balancer to stop sending new requests to the server while letting in-flight requests finish, typically within 30–300 seconds. Combined with health checks, this enables rolling deploys: replace servers one at a time with no failed requests.

Don’t let the balancer be the weak spot

Every request passes through the load balancer, so it must be highly available and able to scale:

  • Managed cloud balancers (AWS ALB/NLB, Google Cloud Load Balancing, Azure Load Balancer) run across several availability zones and scale automatically.
  • Self-managed balancers (NGINX, HAProxy, Envoy) are run as at least two instances, with a floating IP or DNS pointing at both.
  • Global traffic: DNS-based or anycast routing sends users to the nearest region, where a regional balancer takes over.

Load balancers in interviews

Draw the balancer between clients and your stateless app servers, and say three things:

  1. how it picks servers (“least connections, since request times vary”),
  2. how it handles failures (“health checks every 10 seconds; unhealthy servers are removed”),
  3. why it isn’t a single point of failure (“managed, multi-zone balancer”).

Inside the system, balancing also happens between services, either through internal balancers or through client-side balancing in a service mesh (week 5).

Recap

A load balancer gives clients one address, spreads requests across healthy servers and lets you change the fleet without anyone noticing. Round robin suits identical work, least connections suits uneven work, and hashing gives affinity. Layer 4 balancers are fast and protocol-agnostic; layer 7 balancers understand HTTP and can route by content. Make the balancer itself redundant, and use draining for safe deploys.

Exercise

Choose the balancing strategy

Pick a load-balancing strategy (round robin, least connections, or hashing on a key) and a layer (L4 or L7) for each case, with one reason: (a) a fleet of identical stateless API servers handling short JSON requests, (b) a video-transcoding service where some jobs take 2 seconds and others 10 minutes, (c) a cache tier where each server holds part of the data and requests for the same key should hit the same server, (d) one public address that must send /api/* to the API service and /static/* to a file service.

Text
(a)
(b)
(c)
(d)

Summary

  • A load balancer gives clients one address, spreads requests across healthy servers and removes failed servers using health checks.
  • Round robin suits identical servers and short requests; least connections suits uneven request lengths; hashing gives key affinity.
  • Layer 4 balancers see only IPs and ports and are very fast; layer 7 balancers read HTTP and can route by path, header or cookie.
  • Connection draining lets a server finish in-flight requests before it is removed, enabling safe deploys.
  • The load balancer must not become a single point of failure: run it redundantly or use a managed, multi-zone service.