Module 2 · Intermediate · Scaling and load balancing

Load balancers explained, with examples

Load balancers explained for beginners: how they spread traffic, round robin and least connections, health checks, layer 4 vs layer 7, and sticky sessions.

By theprogrammers team · · 7 min read

Once you have more than one server, something has to decide which server handles each request. That's the job of a load balancer. It sits between users and your servers, spreads the requests out so no server is overwhelmed, and quietly stops sending traffic to any server that breaks.

This lesson explains what a load balancer does, the common ways it picks a server, health checks, the difference between layer 4 and layer 7 balancing, sticky sessions, and how to avoid the load balancer itself becoming a weak point.

What a load balancer does

Think of the person at a bank who directs each customer to a free counter. Customers only see one entrance; behind it, several counters do the work.

Users send requests to a load balancer, which spreads them across three stateless app servers. The servers read from a Redis cache, write to a primary database, and read from a read replica that copies the primary's data.

A load balancer:

  1. Has one public address. Users and DNS point at it, not at individual servers.
  2. Spreads requests across a pool of servers, using an algorithm.
  3. Checks server health and skips servers that are down.
  4. Lets you change the pool freely: add servers for horizontal scaling, or remove one to update it, without users noticing.

Many also handle HTTPS for the servers behind them (called TLS termination), compress responses, and block some attacks.

How it chooses a server

Round robin

Send requests to each server in turn: A, B, C, A, B, C… Simple and fair when all servers are equal and requests take similar time.

from itertools import cycle

servers = cycle(["A", "B", "C"])
for request in range(7):
    print(f"request {request} -> server {next(servers)}")
request 0 -> server A
request 1 -> server B
request 2 -> server C
request 3 -> server A
request 4 -> server B
request 5 -> server C
request 6 -> server A

Weighted round robin

Some servers are bigger. Give each a weight: a server with weight 2 gets twice as many requests as one with weight 1. Also useful for sending a small share of traffic to a new version during a canary release.

Least connections

Send each request to the server currently handling the fewest active requests. Better than round robin when some requests are slow (a big report) and others are fast (a page view), because it avoids piling more work onto a server that's already busy.

active = {"A": 12, "B": 3, "C": 7}
target = min(active, key=active.get)
print(target)    # B

Least response time

Like least connections, but also considers how quickly each server has been responding.

Hashing (IP hash or key hash)

Compute a hash of something about the request, such as the user's IP or ID, and use it to pick a server. The same user always reaches the same server, which helps when servers cache per-user data. The catch: when servers are added or removed, ordinary hashing reshuffles almost everyone. Consistent hashing reduces that reshuffling, and is widely used in caches and databases.

AlgorithmBest when
Round robinIdentical servers, similar requests
Weighted round robinServers of different sizes, gradual rollouts
Least connectionsRequest durations vary a lot
HashingThe same user should hit the same server

Health checks

Every few seconds, the load balancer asks each server something like GET /health. If a server fails several checks in a row, it's taken out of the pool and gets no traffic. When it passes again, it's added back.

A good health endpoint is cheap and honest: it confirms the app is running and can reach things it can't work without, such as the database, but doesn't do heavy work, because it's called constantly.

This is how a load balancer turns "a server crashed" from an outage into a non-event.

Layer 4 vs layer 7

The "layers" come from the networking model.

Layer 4 (transport)Layer 7 (application)
Looks atIP addresses and ports onlyThe full HTTP request: URL, headers, cookies
Can route byConnectionPath, host name, header, cookie
SpeedVery fast, simpleA little more work per request
Example useDatabases, games, any TCP trafficWeb apps and APIs

A layer 7 load balancer can do clever routing: send /api/* to API servers and /images/* to image servers, or admin.example.com to a separate pool. Most web apps use layer 7.

Sticky sessions

If a server keeps a user's login session in its memory, the user must always return to that server, or they'll appear logged out. Load balancers can do this with sticky sessions, usually using a cookie.

It works, but it's a workaround with real downsides: load becomes uneven, and if that server dies, its users lose their sessions anyway. The better fix is to make servers stateless by keeping sessions in a shared store, explained in stateless servers and session storage.

Isn't the load balancer a single point of failure?

It would be, so it's made redundant too:

  • Run two load balancers, one active and one on standby, sharing a floating IP address that moves to the standby if the active one fails.
  • Use a managed load balancer from a cloud provider (such as AWS Elastic Load Balancing), which is already spread across machines and data centres.
  • At the largest scale, use DNS to spread users across several load balancers in different regions.

A small example with Nginx

Nginx is a popular web server that can also act as a layer 7 load balancer. This configuration spreads traffic across three app servers using least connections:

upstream app_servers {
    least_conn;
    server 10.0.0.11:8000;
    server 10.0.0.12:8000;
    server 10.0.0.13:8000 weight=2;    # a bigger machine
}

server {
    listen 80;
    location / {
        proxy_pass http://app_servers;
    }
}

Open-source Nginx removes a server from rotation for a while when requests to it fail; active health checks like GET /health need extra modules or other tools such as HAProxy. Managed cloud load balancers include them.

Practice

  1. Your servers handle a mix of 50 ms page views and 20-second PDF exports. Round robin or least connections?
Show the answer

Least connections. Round robin would keep sending requests to a server busy with several long exports; least connections sends new work to the least busy server.

  1. A user keeps getting logged out at random after you added a second server. What's happening, and what are two fixes?
Show the answer

Sessions are stored in each server's memory, and the load balancer sends the user to different servers. Quick fix: sticky sessions. Proper fix: store sessions in a shared store (like Redis) or use signed tokens, so any server can serve any user.

  1. How would you send all /api/ requests to one group of servers and everything else to another?
Show the answer

Use a layer 7 load balancer with path-based routing: two server pools, with a rule that requests whose path starts with /api/ go to the API pool.

Interview questions

What is a load balancer and why use one?

A component that distributes incoming requests across multiple servers. It enables horizontal scaling, removes single server failures through health checks, allows zero-downtime deploys, and can handle TLS and routing.

Compare round robin and least connections.

Round robin rotates through servers in order, which is simple and fair for uniform requests. Least connections picks the server with the fewest active requests, which adapts better when request durations vary.

What is the difference between layer 4 and layer 7 load balancing?

Layer 4 routes using network information (IP and port) without reading the request content; it's fast and protocol-agnostic. Layer 7 understands HTTP and can route by URL path, host, headers or cookies.

What are sticky sessions and what are their drawbacks?

Routing a client consistently to the same server, often with a cookie. Drawbacks: uneven load, harder scaling and deploys, and lost sessions when that server fails. Stateless servers with shared session storage avoid them.

What to learn next

  1. Remove the need for sticky sessions in stateless servers and session storage.
  2. Serve files from near your users with a CDN.