AlgoViz

Load balancing

medium 25 min

A load balancer gives many servers one address, sends each request to a healthy one and hides failures and upgrades.

Video lesson · Chapter 1 of 5

Four ticket windows take turns

0:00 / 3:57

Load balancer

1:16Reel

Load balancing in one picture
Load balancing in one picture

Theory

Read or listen first. About 1 min.

What it is

A load balancer stands in front of a group of servers and passes each request to one of them. To the outside it looks like a single address. Behind it there can be two servers or two thousand.

It also watches the servers. When one stops answering its health check, the balancer stops sending it work.

Why it exists

One server can only do so much, and any server can fail. With several identical servers, work can be shared and a failure hurts less. Something has to do the sharing.

Because every request passes through it, the balancer is also a convenient place for encryption, routing by path, and draining a server before an upgrade. It must itself be redundant, or it becomes the weak point.

A short history

  1. 1995

    RFC 1794 describes using DNS to spread requests over several addresses.

  2. 1997

    F5 introduces BIG-IP, an early dedicated load-balancing product.

  3. 2001

    HAProxy 1.0 is released in December: free software that does the same job on ordinary machines.

  4. 2004

    The first public release of nginx, version 0.1.0, widely used as a web server and reverse proxy.

  5. 2009

    Amazon launches Elastic Load Balancing in May: a balancer as a service.

  6. 2016

    Google publishes Maglev, its software network load balancer that runs on a cluster of machines.

Words to know

Pool
The servers that can receive work. Also called a backend, upstream or target group.
Virtual IP
The address clients use. It belongs to the balancer, not to one server.
Health check
A regular test that a server can serve.
Layer 4
Balancing by address and port, without reading the request.
Layer 7
Balancing by what the request says, such as its path.
Sticky session
Sending one user to the same server each time.
Draining
Finishing current work before removing a server.

How it works

Step through the idea, or press Play.

Step 1 of 3

Receive. A client opens a connection to the balancer's virtual IP

Understand it

Start here

The host at the picnic

Imagine a picnic with three tables and nobody in charge. Every family walks to the first table they see. Now a host stands at the entrance and says: you go to table 1, you to table 2, you to table 3. That host is a load balancer.

Seating families
Nobody decides123

The families never needed to know which tables exist. They only had to find the host.

The path

From client to a healthy server

One address, several servers

Clients reach a load balancer that terminates TLS, runs health checks and picks a server by round robin, least connections or a hash. Servers 1 and 2 receive requests; server 3 fails its health check and is skipped.
The client resolves our domain to the balancer. It ends TLS, drops unhealthy servers, picks one by round robin, least connections or hash, and forwards.
  • Scalability

    Add servers as traffic grows. Clients notice nothing.

  • Availability

    A failed server is skipped. A redundant balancer removes the last single point.

  • Performance

    Work goes where there is room, so queues stay short.

  • Flexibility

    Upgrade one server at a time without downtime.

  • Security

    Servers stay in a private network, and one place ends TLS and filters.

  • Cost

    Several ordinary machines instead of one huge one.

Layers

Layer 4 and layer 7 in short

Layer 4Layer 7
Decides byAddress and portPath, host, headers, cookies
Reads the requestNoYes, so it must end TLS
Cost per requestLowHigher
Good forAny TCP or UDP protocol, very high ratesRouting to services, retries, sticky cookies
ExamplesAWS Network Load Balancer, Linux IPVSnginx, HAProxy, AWS Application Load Balancer
HAProxy and nginx can do both. The details are in layer 4 and layer 7 load balancers.

Algorithms 1

Round robin, plain and weighted

Round robin takes turns: 1, 2, 3, 1, 2, 3. It is simple and fair in the number of requests. It is unfair in the amount of work when requests differ, when servers differ or when connections stay open for hours.

Weighted round robin gives each server a share that matches its size. A server with weight 3 gets three requests for every one sent to a server with weight 1. Somebody has to keep the weights up to date.

Shares from weights

sharei=wi∑jwj3, 2, 1:36=50%,26≈33%,16≈17%share_i = \frac{w_i}{\sum_j w_j} \qquad 3,\,2,\,1:\quad \tfrac{3}{6}=50\%,\quad \tfrac{2}{6}\approx 33\%,\quad \tfrac{1}{6}\approx 17\%
For weights 3, 2, 2 and 1 the shares are 37.5%, 25%, 25% and 12.5%.

Six turns with weights 3, 2 and 1

Smooth weighted round robin mixes the turns, so that A does not get three in a row.

Algorithms 2

Least connections and two choices

Least connections sends the next request to the server with the fewest open ones. Suppose three servers have 5, 2 and 8 open connections: the second one is next. A slow server keeps its connections longer and so gets fewer new ones, without anyone setting a weight.

Two random choices picks two servers at random and takes the less busy one. It is nearly as good as looking at all of them, and it avoids a herd: several balancers that all see the same quietest server and all send there at once.

Why two choices are so much better than one

n balls into n bins:max⁡1 choice≈ln⁡nln⁡ln⁡nmax⁡2 choices≈ln⁡ln⁡nln⁡2\text{n balls into n bins:}\quad \max_{1\ choice} \approx \frac{\ln n}{\ln\ln n} \qquad \max_{2\ choices} \approx \frac{\ln\ln n}{\ln 2}
Leading terms for large n (Mitzenmacher). For n = 1,000,000 that is about 5.3 against 3.8 plus small constants, and the gap grows with n.

Algorithms 3

Hashing: the same client, the same server

IP hash computes a number from the client's address and uses it to choose the server. The same client lands on the same server as long as the pool stays the same. The price: an office behind one shared address is a single "client", so its thousands of users all hit one server.

With hash % n, adding or removing one server moves most clients. Consistent hashing moves only about 1 in n. Other ways to keep a user on one server, such as cookies, are in session persistence.

Choosing an algorithm

AlgorithmBest forWeak point
Round robinEqual servers, short similar requestsIgnores size and load
Weighted round robinServers of different sizeWeights must be maintained
Least connectionsRequests of unequal length, WebSocketsMust count; a fast-failing server attracts traffic
Two random choicesMany balancers, large poolsSlightly less even than a full scan
IP hashKeeping a client with one serverUneven behind shared addresses
Consistent hashCaches, pools that changeNeeds virtual nodes to be even

Which algorithm?

Health

Health checks

A balancer learns about trouble in two ways. Active checks send a probe every few seconds. Passive checks watch real requests and notice failures.

Kinds of probe

ProbeAsksMisses
TCPCan I connect to port 3000?A process that accepts but cannot answer
HTTPDoes GET /health return 200?Wrong content with status 200
ContentDoes the reply contain "healthy"?Trouble that the endpoint does not test

One server's state

Probe, wait for the reply or the timeout, evaluate, update the state. Two thresholds stop a server from flapping in and out.

Settings to choose (an example)

SettingExampleMeaning
Interval10 sHow often each server is probed
Timeout5 sHow long to wait for one reply
Unhealthy threshold3 failuresFailures in a row before it is taken out
Healthy threshold2 successesSuccesses in a row before it returns
AWS Application Load Balancers default to an interval of 30 s and a timeout of 5 s for instances and addresses.

How long until a dead server is skipped?

tdetect≤I⋅F+T=10×3+5=35 st_{detect} \le I \cdot F + T = 10 \times 3 + 5 = 35\ \text{s}
I is the interval, F the failures needed, T the timeout. A crash just after a passed probe waits almost one interval, then needs F probes. Passive checks react sooner.
nginx
upstream backend_api {    least_conn;    server 10.0.1.10:8080 max_fails=3 fail_timeout=10s;    server 10.0.1.11:8080 max_fails=3 fail_timeout=10s;    server 10.0.1.12:8080 backup;}server {    listen 80;    location / {        proxy_pass http://backend_api;        proxy_connect_timeout 2s;        proxy_read_timeout 5s;    }}
nginx with least connections, passive checks and a backup server. After 3 failed attempts within 10 s a server is skipped for 10 s. Active probes (health_check) are part of nginx's commercial subscription.

Life cycle

Adding and removing servers

  1. 1

    Add

    A new server passes its checks first, then receives traffic. With slow start its share grows over some seconds, while caches warm up.

  2. 2

    Drain

    Stop sending new requests to the server, but let current ones finish. AWS waits 300 seconds by default.

  3. 3

    Remove

    Close what is left after the time limit, then stop the machine.

Draining during a deploy

Four places

Where balancers sit

1. A web application

Traffic from the Internet passes a firewall, then a load balancer, then one of three web servers, which all use one database.
The classic picture: firewall or WAF, balancer, web servers, database.

2. Microservices

Each service has its own pool. In a mesh, a small proxy next to each instance does this job.

3. Several regions

First the region, then the server: see global and local load balancing.

4. Database read replicas

An application sends writes to the primary database and reads to a read balancer, which spreads them over three replicas.
Only reads may be spread. Replicas can lag behind the primary.

Kinds

Hardware, software, cloud, DNS

KindExamplesFor and against
HardwareF5 BIG-IP, Citrix NetScalerDedicated and fast; expensive, fixed capacity
SoftwareHAProxy, nginx, EnvoyFlexible, runs anywhere; you operate it
CloudAWS ALB and NLB, Google, AzureManaged and elastic; pay as you go
DNSRoute 53, CloudflareGlobal and simple; coarse, slowed by caches

The balancer itself

Do not create a new single point of failure

Two balancers, one address

Users send traffic to one virtual address that balancer A owns. Balancer A forwards to servers 1 and 2. Balancer B is a standby that takes over the address after a failure and forwards to the same servers.
With VRRP the standby takes the address when the owner stops announcing itself.

Good practice

  • Pair balancers with VRRP (for example Keepalived), or announce one address from several with anycast
  • End TLS at the balancer to take that work off the servers
  • A cheap health endpoint of its own
  • Connection draining for every deploy
  • Sensible timeouts, balancer metrics and a load test before launch

Common traps

  • A single balancer without a standby
  • Health checks with heavy database queries
  • Round robin for long-lived WebSockets
  • Sticky sessions without a reason
  • Weights nobody updates, and failed checks nobody reads

Availability with and without spare parts is worked out in high availability. Plan one more server than the load needs: with 4 servers at 70%, losing one leaves 3 at about 93%.

Summary

The whole topic in one minute.

A load balancer gives many servers one address, shares the work and skips the ones that fail.

Round robin suits similar, short requests. Weights suit unequal servers. Least connections suits work of unequal length. Hashing keeps a client with one server, at the price of evenness.

Pick layer 4 for speed and layer 7 for decisions based on the request. Keep servers stateless where you can, check health honestly, and run more than one balancer.

  • A load balancer gives many servers one address, shares the work and skips the ones that fail.
  • Round robin for similar requests, weights for unequal servers, least connections for unequal work, hashing for stickiness.
  • Layer 4 routes by address and port; layer 7 reads the request.
  • Detection time is interval times failures, plus a timeout.
  • Health checks must be light, and deploys must drain.
  • Run at least two balancers.

Sources