What Is a Load Balancer? Traffic Lanes for Apps
Your shop's app runs on one server, and on sale day pages crawl, then time out: the queue from lesson 4. You start two more copies, but customers still type one address, so something must pick a copy for each request. This lesson answers what is a load balancer: how it shares requests, spots broken servers, copes with logins and where it sits.
One address in front of many servers
A load balancer is a server, or a managed cloud service, that receives requests at one address and passes each to one of several servers behind it, its backends or targets. The reply usually comes back through it. Users only ever see its address.
It solves two problems. The first is capacity: three servers carry roughly three times the traffic of one, if what they share, such as the database, keeps up. That is scaling out from lesson 4.
The second is failure: if one server crashes, the others keep answering. You can also update servers one at a time by draining each: the load balancer sends it no new requests and lets current ones finish.
In the flowchart, notice step 2: the load balancer chooses only among servers that passed their recent health checks, which run in the background. An HTTP load balancer can choose again for every request.
How it picks a server
The load balancer's rule for choosing is its algorithm. Three cover most setups:
- Round robin gives each server the next request in turn: 1, 2, 3, then 1 again. It suits alike servers and similar requests.
- Least connections picks the server with the fewest connections open right now, so one stuck on slow requests gets fewer new ones.
- Weighted versions of either give each server a weight: weight 2 gets twice the share of weight 1. Use it for a bigger machine, or to give a new version a small share first, a canary release.
In the table, notice the trap in least connections: a broken server that answers with instant errors always has few connections open, so it attracts more traffic.
Health checks: no traffic to broken servers
A health check is a small test request the load balancer sends to every server on a schedule, such as GET /health every few seconds. A server passes if it returns a success code, such as 200, within a timeout, a time limit.
One failure may be a blip, so load balancers count. After a set number of failures in a row, the unhealthy threshold, the server gets no new requests; after a set number of passes, the healthy threshold, it rejoins. In the diagram, notice that app-3 is still checked while out: that is how it returns.
Here is the backend section of a configuration for HAProxy, a widely used open-source load balancer; a full file also needs a frontend section to receive traffic. The addresses are illustrative.
backend app
balance roundrobin
option httpchk GET /health
server app-1 10.0.1.11:8080 check
server app-2 10.0.1.12:8080 check
server app-3 10.0.1.13:8080 check weight 2
balance roundrobin sets the algorithm; leastconn would mean least connections. check turns on health checks, every 2 seconds by default, and option httpchk makes each an HTTP request for /health that passes on any 2xx or 3xx status. By default, 3 failures take a server out and 2 passes bring it back. Weights default to 1, so app-3 gets two requests in every four.
A check is only as good as what it tests. If /health skips the app, a server with a broken app still passes. If every server's check tests the shared database, one database blip fails them all at once.
Sticky sessions and stateless apps
Logging in creates a session, a record on the server saying who you are (lesson 9). If each app server keeps sessions in its own memory, your next request may reach another server, which has no record of you, so you appear logged out.
Sticky sessions, or session affinity, make the load balancer send each user back to the same server, usually with a cookie of its own that records which server you got. Some load balancers instead hash the client's IP address into a number that always picks the same server, which piles users onto one server when many share an address behind NAT (lesson 12).
Stickiness has costs: a busy server keeps its users while a new one gets only newcomers, and when a server dies, its users lose their sessions anyway.
The lasting fix is a stateless app server, one that keeps nothing about a user that another server would need. Sessions go in a shared store, such as the database or Redis, an in-memory data store, or in a signed token the client sends. Then any server can answer any request, as The Twelve-Factor App recommends.
Where it sits, and what else it does
The site's DNS name points at the load balancer (lesson 3). As in lesson 13's three tiers, it is the only part facing the internet; app servers stay in private subnets.
It usually terminates TLS: it holds the certificate and private key, ends the HTTPS connection from lesson 8 and reads the request as plain HTTP, which cookie-based stickiness needs. It forwards over the private network, unencrypted or encrypted again if your rules require. Because it opens its own connection, the server sees the load balancer's address, not the user's; lesson 16 shows how the user's address is passed along.
On AWS, an Application Load Balancer handles HTTP and HTTPS. A listener on port 443 holds the certificate, often from AWS Certificate Manager, and forwards to a target group, its list of servers. It offers round robin by default, least outstanding requests, which counts requests in progress, and weighted random.
Its default health check asks for / every 30 seconds, expects 200 within 5 seconds, takes a target out after 2 failures and readmits it after 5 passes, so a crashed server can get requests for about a minute. Stickiness is off by default; when on, the load balancer's own cookie is named AWSALB.
A load balancer could itself be a single point of failure, one part whose loss stops everything. So AWS runs it in every availability zone you enable, each a separate group of data centres, and self-run ones usually run as two or more copies.
Check yourself
After you add a second app server, users are logged out at random. Sessions live in each server's memory. Why, and what is the lasting fix?
Requests reach either server, and only one holds your session. Sticky sessions hide this until that server dies; a shared session store, such as Redis, lets any server answer.
Every real request to app-2 fails with a 500 error, yet it keeps getting users. Its health check fetches a static page the web server returns without running the app. Why?
The static page proves only that the web server answers, not that the app works, so the check passes. A check that runs the app would fail and remove app-2.
Under least connections, one server answers real requests with an error in 2 ms but passes its health check; healthy ones take 200 ms. Which gets the most requests, and why?
The broken one: it finishes requests almost at once, so it nearly always has the fewest open connections and keeps winning the choice.
Go deeper
- Monitoring NGINX Ingress Controller using Open-source tools: the NGINX Ingress Controller is a load balancer in front of apps on Kubernetes, the container platform; the post graphs its request metrics in Grafana.