Sub topic 2
What a load balancer does
This chapter explains the working model of a load balancer: what sits between the client and the servers, what it decides on each request, and what it leaves alone. It assumes you know basic HTTP client-server communication, TCP, IP addresses and ports, and how to edit a configuration file. Later chapters cover Layer 4 and Layer 7 modes, algorithms and health checks in detail. Here you build the overall picture they fit into.
The core job
A load balancer is a network component that accepts client connections on one address and forwards the traffic to one of several backend servers. The group of backends is called a pool (NGINX calls it an upstream, HAProxy a backend). Clients only know the load balancer's address, so you can add, remove or replace servers without telling anyone.
The load balancer does four things:
- Presents one entry point. Clients connect to a single virtual IP address or DNS name. That name stays stable while the pool behind it changes.
- Selects a backend. For each connection or request, it applies a rule (the balancing algorithm) to choose a server.
- Forwards traffic both ways. It passes the request to the chosen server and returns the response to the client.
- Avoids unhealthy servers. It stops sending traffic to backends that fail or stop responding.
The first two give you horizontal scaling, which means handling more load by adding servers. The fourth gives you availability, which means the service keeps working when a server fails.
The building blocks
Every load balancer product uses different names, but the same parts appear in all of them.
| Part | What it is | NGINX term | HAProxy term |
|---|---|---|---|
| Listener | The address and port that accepts client connections | `listen` in a `server` block | `bind` in a `frontend` |
| Pool | The set of backend servers | `upstream` | `backend` |
| Algorithm | The rule that picks a server | `least_conn`, default round robin | `balance` |
| Health check | A test that decides whether a server can take traffic | `max_fails`, `fail_timeout` | `check`, `option httpchk` |
| Rules | Conditions that choose a pool, such as by path or host | `location` | ACLs, `use_backend` |
Keep these separate in your head. When a problem appears, it nearly always lives in one of them: the listener (wrong port or certificate), the pool (wrong addresses), the algorithm (uneven load) or the health check (servers wrongly marked down).
A request, step by step
Consider a plain HTTP request that passes through a Layer 7 (HTTP-aware) proxy.
- The client resolves
shop.example.comthrough DNS and gets the load balancer's IP address. - The client opens a TCP connection to the load balancer and sends the request.
- The load balancer reads the request and picks a healthy backend using its algorithm.
- The load balancer opens (or reuses) a separate TCP connection to that backend and sends the request.
- The backend replies to the load balancer, which relays the reply to the client.
Two details matter here. First, there are two TCP connections, one on each side. The backend never talks to the client directly. Second, the load balancer sits in the return path, so every response also passes through it. This design is called a reverse proxy.
Some Layer 4 products work differently. In direct server return (DSR), the backend sends the response straight to the client and skips the load balancer. This reduces load on the balancer for large responses. It also means the backend must be configured to accept traffic for the virtual IP, and the balancer cannot inspect or modify responses.
A minimal configuration
This NGINX configuration shows the listener, the pool and the forwarding rule in one place. The default algorithm is round robin.
upstream app {
server 10.0.0.11:8080;
server 10.0.0.12:8080;
}
server {
listen 80;
location / {
proxy_pass http://app;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}Place the upstream and server blocks inside the http block of nginx.conf (or in a file included from it). Reload with nginx -t && nginx -s reload. The -t flag checks the syntax first, so a typo does not take down a running balancer.
The two proxy_set_header lines are needed because of the two-connection model. Without them, the backend sees a request that came from the load balancer, with a Host value of app, which is the upstream name. The next section explains why this matters.
What the backend sees
Because the load balancer opens its own connection, the backend sees the load balancer's IP address as the client address. This causes several problems:
- Access logs on the backends all show the same source IP.
- Rate limiting and IP allow lists on the backend act on the balancer, not the user.
- Geolocation and fraud checks give wrong results.
The usual fix at Layer 7 is the X-Forwarded-For header. The proxy adds the client's address to this header, and the application reads it. $proxy_add_x_forwarded_for in NGINX appends the client address to any value that already exists.
At Layer 4 there are no HTTP headers to modify. Some balancers use the PROXY protocol, which prepends a short line with the original client address and port to the TCP stream. Both sides must be configured for it. If only one side expects it, connections fail with garbled requests. Other Layer 4 setups preserve the client address by acting as a router, as DSR does.
The decision in code
The algorithm is a function from the current state of the pool to one server. This Python sketch shows two of them. Round robin needs no information about the servers. Least connections needs a live count of active connections for each server.
import itertools
servers = ["a", "b", "c"]
round_robin = itertools.cycle(servers)
def pick_round_robin():
return next(round_robin)
def pick_least_connections(active):
return min(active, key=active.get)
print([pick_round_robin() for _ in range(5)])
print(pick_least_connections({"a": 2, "b": 0, "c": 5}))Running it prints ['a', 'b', 'c', 'a', 'b'] and then b. Round robin cycles in order. Least connections picks b because it has the fewest active connections. A real balancer must also keep that connection count accurate as connections open and close, and skip servers that are marked unhealthy. The Balancing algorithms chapter covers the trade-offs.
What a load balancer does not do
Knowing the limits prevents wrong expectations.
- It does not make the application stateless. If each backend keeps user sessions in local memory, a user sent to a different server loses the session. Fix this by storing sessions in a shared store, or use session persistence as a fallback.
- It does not fix a slow backend. It can steer new requests away from a busy server, but if every server is saturated, adding a balancer changes nothing. You need more capacity.
- It does not scale the database. A pool of stateless web servers that all depend on one database still has one bottleneck.
- It is not automatically redundant. A single balancer is itself a single point of failure. Making the balancer tier redundant is covered in a later chapter.
- It adds a hop. Each request gains a small amount of latency and one more component that can fail or be misconfigured.
Common errors
Most first-time problems come from the proxy model above. These are the ones you will see most often.
| Symptom | Likely cause | What to check |
|---|---|---|
| 502 Bad Gateway | The balancer could not get a valid response from the backend, often because the connection was refused or reset | Is the backend running? Is it listening on the address and port in the pool? A service bound to `127.0.0.1` cannot be reached from another host |
| 503 Service Unavailable | No backend is available, for example every server has failed its health check | Health check path and expected status code; the server list |
| 504 Gateway Timeout | The backend accepted the request but did not answer within the proxy's timeout | Slow queries; proxy read timeout settings |
| All backend logs show the same client IP | Backends see the balancer as the client | `X-Forwarded-For` or PROXY protocol, and log format |
| Redirects point to the wrong host or scheme | The backend does not see the original Host header or the original HTTPS scheme | `Host` and `X-Forwarded-Proto` headers |
| One server is overloaded while others idle | Long-lived connections or a poor algorithm choice | Algorithm, weights, connection reuse |
| Users randomly log out | Sessions stored in one backend's memory | Shared session store or persistence |
The exact status code for "all backends down" differs between products. NGINX typically returns 502, while HAProxy returns 503. Check your product's documentation when you build alerts around these codes.
Where this fits
This chapter set out the parts and the request flow. The next chapters take each part further: Layer 4 and Layer 7 modes change what the balancer can see and decide, algorithms define how the pool is used, and health checks keep traffic away from failed servers. Later chapters add session persistence, TLS handling and redundancy for the balancer itself.
Exercise
A team puts an NGINX load balancer in front of three web servers. After the change, the web servers' access logs show every request coming from the balancer's IP address, and a per-IP rate limit on the backends now blocks all users together once one user is busy. Why does this happen, and what is the fix at Layer 7? What risk comes with the fix?
Show answer
The balancer is a reverse proxy, so it opens its own TCP connection to each backend, and the backend sees the balancer's address as the client. The rate limit therefore counts all users as one source. The fix is to have the balancer pass the original client address in the X-Forwarded-For header (proxysetheader X-Forwarded-For $proxyaddxforwardedfor in NGINX) and to configure the backend or application to read the client address from that header for logging and rate limiting. The risk is that a client can send a forged X-Forwarded-For header, so the backend must trust the header only when the request comes from the balancer, and ignore or overwrite values that arrive from elsewhere.
Exercise
Using the Python sketch in this chapter, what does pickleastconnections return for {"a": 4, "b": 4, "c": 1}, and why would a real balancer need more than this function to be correct?
Show answer
It returns "c", the server with the fewest active connections. A real balancer must also keep the connection counts up to date as connections open and close, and exclude servers that are marked unhealthy, otherwise it could keep choosing a failed server because its count is low.