System Design · 02. Scaling · 10 min · Beginner
Load Balancing
One address for the users, many servers behind it.
In short
Users reach one address; the balancer spreads requests over the servers. Round robin takes turns, least connections picks the least busy, and weights favour bigger machines.
Health checks remove a dead server within seconds. Keep servers stateless so any of them can answer any request.
Key ideas
- Users see one address. Behind it you can add, remove or replace servers without telling anyone. (step 2)
- Round robin looks at the order. Least connections looks at the servers. (step 5)
- Keep enough spare capacity: two servers must now carry the load of three. (step 8)
Good to know
- Round robin is a fine default when every request costs about the same. (step 3)
- Weights also help a careful roll-out: give a new server weight 1 of 10 first, and raise it if all is well. (step 6)
- Many sites use both: an L4 balancer spreads connections over a few L7 balancers, which route by URL. (step 10)
Watch out
- Adding servers does nothing until something spreads the requests over them. (step 1)
- One slow request can cost as much as a hundred fast ones. (step 4)
- A good health check tests what the server needs (its database connection), but stays cheap: it runs every few seconds. (step 7)
- Sticky sessions make the load uneven, and when that server dies its users lose their session. The better fix is the next lesson: stateless servers. (step 9)
Key numbers
- Busiest server
- 33%
- Healthy servers
- 3/3
- Failed requests
- 0
Terms
- Load balancer
- A server in front of the others that takes the public address and passes each request on to one of them.
- Round robin
- Send requests to the servers in turn: S1, S2, S3, then S1 again.
- Least connections
- Send each new request to the server with the fewest requests in progress.
- Weighted balancing
- Give bigger servers a higher weight so they receive a bigger share of the requests.
- Health check
- A small request the balancer sends every few seconds to see whether a server is alive.
- Failover
- Taking a failed server out and sending its traffic to the healthy ones.
- Sticky sessions
- Sending each user back to the same server, usually with a cookie.
- L4 vs L7 load balancer
- Layer 4 balances TCP connections; layer 7 reads the HTTP request and can route by path.