Software Engineeringunpacked

What is a load balancer? Load balancing algorithms, health checks, and layer 4 vs layer 7

A load balancer is a server that sits in front of a group of servers and spreads incoming requests across them. Clients only ever talk to the load balancer; for each request or connection, it picks one healthy server using an algorithm such as round robin (take turns) or least connections (pick the least busy). It also runs health checks and stops sending traffic to a server that fails them. That lets you add servers as traffic grows and keeps your app up when one of them breaks.

Video · What is a load balancer? Explained with a supermarket, under a minute · 0:39

What is a load balancer, in one paragraph

Prefer to watch? The one-minute Short shows the core idea with diagrams; this guide goes further.

A load balancer is a server that receives all incoming traffic for your app and spreads it across a group of servers behind it. Amazon's documentation describes it as the single point of contact for clients, which routes requests to registered targets, watches their health, and sends traffic only to healthy ones (AWS docs).

Think of a supermarket with many checkouts and one person at the front pointing each shopper to the shortest line. Shoppers never pick a checkout themselves; they follow the pointer. If a till breaks, the pointer stops sending people there. The pointer is the load balancer, the checkouts are your servers, and the shoppers are requests.

Why you need load balancing

One server has limits: CPU, memory, and how many connections it can hold. When traffic grows past them, you have two choices. You can buy a bigger server (scaling up), or run several ordinary servers side by side (scaling out). Scaling out only works if something spreads the traffic, and that something is the load balancer.

It solves two problems at once:

  1. Capacity. Ten servers can handle roughly ten times the requests of one, and you can add or remove servers without your users noticing.
  2. Availability. If one server crashes or is being updated, the load balancer routes around it. One broken server no longer means a broken app.

How a load balancer works, step by step

  1. A client looks up your domain name and gets the load balancer's address. (If DNS and routing are new to you, start with how the internet works.)
  2. The client connects to the load balancer, never directly to a server.
  3. The load balancer picks one healthy server from its pool, using its algorithm.
  4. It forwards the request (or the whole connection) to that server and passes the response back.

The servers behind it usually have private addresses only. AWS notes that both internet facing and internal load balancers reach their targets on private IP addresses, so your servers do not need to be exposed to the internet at all.

Because the server sees the load balancer as the sender, HTTP load balancers add headers such as X-Forwarded-For with the client's real address. Read that header, not the connection address, when you log or rate limit by IP.

Load balancing algorithms

The algorithm decides which server gets the next request. These are the common ones, with the NGINX directive where it has one (NGINX docs).

Algorithm How it picks Good for
Round robin each server in turn servers of equal size, short requests
Weighted round robin in turn, but more often for servers with a higher weight servers of different sizes
Least connections (least_conn) the server with the fewest active connections requests of uneven length
IP hash (ip_hash) a hash of the client's IP address, so the same client lands on the same server simple session stickiness
Least time / least outstanding requests the server answering fastest or with the fewest requests in flight mixed or slow backends

Round robin is the default almost everywhere: NGINX uses it when you configure nothing else, and so does AWS's Application Load Balancer. It is simple and fair when every request costs about the same.

Weights fix the case where servers differ. In NGINX's own example, a server with weight=3 gets three of every five new requests while two others get one each.

Least connections shines when some requests take much longer than others, like report exports next to quick page loads. Round robin would keep handing work to a server stuck on long jobs; least connections notices it is busy.

Health checks: how a load balancer avoids broken servers

A load balancer is only useful if it stops sending traffic to servers that cannot answer. It finds out in two ways.

Active health checks probe each server on a schedule. AWS's Application Load Balancer, for example, sends an HTTP GET to a path you choose (by default /) every 30 seconds. After 2 failures in a row it takes the server out of service, and after 5 successes in a row it puts it back (AWS docs).

Passive health checks watch real traffic instead. In open source NGINX, if requests to a server fail max_fails times within fail_timeout, the server is marked unavailable for that period, then tried again with live requests.

Two details matter in practice:

  1. Make the health check endpoint honest. A /health route that returns 200 even when the database is unreachable keeps a broken server in rotation.
  2. Know what happens when everything fails. AWS's Application Load Balancer "fails open": if every target is unhealthy, it sends traffic to all of them anyway, rather than to none.

Sticky sessions

Some apps keep a user's session in the memory of one server. If the next request lands on a different server, the user looks logged out. Sticky sessions (session persistence) send a client back to the same server each time, using a cookie or a hash of the client's IP, like NGINX's ip_hash.

Stickiness works, but it weakens the load balancer: traffic spreads less evenly, and when that server dies, its sessions die with it. The cleaner fix is to keep session data in a shared store, such as a database or a cache, so any server can handle any request.

Layer 4 vs layer 7 load balancers

The "layer" refers to how much of the traffic the load balancer reads, using the OSI model's numbering.

Layer 4 (transport) Layer 7 (application)
What it sees IP addresses, ports, TCP or UDP the full HTTP request: path, host, headers, cookies
Unit it balances a connection a request
Can route by URL or host? no yes
Can terminate TLS? sometimes yes, usually
Example AWS Network Load Balancer AWS Application Load Balancer, NGINX as an HTTP proxy

A layer 4 load balancer is fast and protocol agnostic. AWS's Network Load Balancer picks a target with a hash of the protocol, addresses, ports and TCP sequence number, and keeps each TCP connection on one server for its whole life (AWS docs).

A layer 7 load balancer reads each HTTP request, so it can make smarter choices: send /api to one group of servers and /images to another, or route by host name so one load balancer serves several domains (AWS docs). It can also hold your TLS certificate and decrypt traffic once, at the edge of your system.

Long lived connections deserve a note. A WebSocket stays open on one server for minutes or hours, so the balancer can only choose a server when the connection opens. Least connections usually spreads those better than round robin.

Software, hardware and cloud load balancers

Load balancers come in three forms:

  1. Software you run yourself, such as NGINX or HAProxy, on a normal server or container.
  2. Hardware appliances in a data center, common in older and on premises setups.
  3. Managed cloud services, such as AWS Elastic Load Balancing, which run and scale the load balancer for you across several zones.

A single load balancer is itself one machine that can fail, so production setups run several nodes. Managed services do this for you: AWS creates a load balancer node in each zone you enable and lets DNS spread clients across them.

How to test your load balancer setup

Load balancing bugs hide until the day a server dies, so test them on purpose. Stop one server and check that requests keep succeeding. Make the health check fail and watch the server leave the pool, then recover and watch it return. Run a load test to see the traffic actually spread. These checks fit naturally into the non-functional tests described in our guide to types of software testing. More guides like this one are in the article library.

Key takeaways

  1. A load balancer receives all traffic and spreads it across several servers.
  2. Round robin takes turns; least connections picks the least busy server; weights and hashing handle special cases.
  3. Health checks take failing servers out of rotation and bring them back when they recover.
  4. Prefer shared session storage over sticky sessions.
  5. Layer 4 balances connections; layer 7 reads HTTP requests and can route by path or host.

Sources: NGINX, using nginx as HTTP load balancer · How Elastic Load Balancing works · What is an Application Load Balancer? · Health checks for Application Load Balancer target groups · What is a Network Load Balancer?

FAQ

What is a load balancer in simple terms?

A load balancer is a traffic director for servers. Every request reaches it first, and it forwards each one to one of several servers, so no single server gets overloaded and a broken server can be skipped.

What are the main load balancing algorithms?

Round robin sends requests to each server in turn. Weighted round robin sends more to stronger servers. Least connections picks the server with the fewest active connections. IP hash maps each client to the same server every time. Many load balancers also offer a least response time or least outstanding requests method.

What is the difference between a layer 4 and a layer 7 load balancer?

A layer 4 load balancer works with TCP and UDP connections: it picks a server per connection from addresses and ports, without reading the request. A layer 7 load balancer reads the HTTP request, so it can route by path, host name or header, for example sending /api to one group of servers and /images to another.

What happens when a server behind a load balancer fails?

The load balancer notices through health checks, either by probing each server on a schedule or by seeing real requests fail, and stops sending it traffic. When the server passes its checks again, it is put back into rotation.

Is a load balancer the same as a reverse proxy?

They overlap. A reverse proxy is any server that receives requests on behalf of backend servers; a load balancer is a reverse proxy whose main job is spreading those requests across several backends. Software like NGINX can do both.