Skip to content
Visual explainer 2h to learn 4 steps

Load balancers

Choose between layer 4 and layer 7 load balancing and configure health checks.

By Invicly Tech, , in Computer Networking. About 11 minutes to read.

Topic 45 of 51

In short

A load balancer spreads incoming connections across a pool of healthy servers, adding capacity and resilience. Layer 4 balancers forward TCP or UDP connections by address and port, while layer 7 balancers understand HTTP and can route by host, path or header. Health checks remove failing servers automatically.

Explained simply

One server can only handle so many users. A load balancer sits in front of a group of servers and shares incoming requests between them. Users see one address; behind it, two, ten or a hundred servers do the work.

It also makes the service more reliable. The load balancer keeps checking each server with health checks. If a server stops answering, it is taken out of the rotation, and users keep being served by the others, often without noticing.

Load balancers work at different layers. A layer 4 balancer only looks at IP addresses and ports and forwards the connection. A layer 7 balancer understands HTTP, so it can send /api requests to one group of servers and /images to another.

Many load balancers also handle HTTPS for you. They decrypt the traffic (TLS termination), so certificates live in one place, and they can keep a user on the same server if the app needs it (sticky sessions).

Press Play on a diagram to walk through it one step at a time.

CompareLayer 4 versus layer 7
Layer 4
  • Sees IPs and ports only
  • Very fast, protocol-agnostic
  • Can pass TLS through untouched
  • Example: AWS NLB
Layer 7
  • Understands HTTP
  • Route by host, path, header
  • Terminates TLS
  • Example: AWS ALB, NGINX
CompareThree ways to handle TLS at the balancer
Termination
  • Balancer decrypts
  • HTTP routing possible
  • Backend gets plain HTTP
  • Certs managed in one place
Re-encryption
  • Balancer decrypts and re-encrypts
  • HTTP routing possible
  • Encrypted on both legs
  • Backends need certificates too
Passthrough
  • Balancer never decrypts
  • Layer 4 routing only
  • End-to-end encryption
  • Can route by SNI at most

In depth

Layer 4 versus layer 7 in detail

A layer 4 balancer picks a backend when a TCP connection or UDP flow starts and then moves packets without reading them. Some designs (like AWS NLB) pass the client's IP through; others open a second connection to the backend, so the server sees the balancer's IP unless the PROXY protocol is used to pass the original address. Layer 4 is fast, handles any protocol (databases, game servers, MQTT) and can pass TLS through untouched.

A layer 7 balancer is a reverse proxy: it ends the client's connection, reads the HTTP request, then opens or reuses its own connection to a chosen backend. It can route by host name, path, header or method, rewrite URLs, add headers like X-Forwarded-For (the client IP) and X-Forwarded-Proto, retry failed requests, compress responses and speak HTTP/2 to clients while using HTTP/1.1 to servers. The cost is more CPU per request and the need to hold TLS keys.

SequenceA layer 7 balancer is a proxy with two connections
Client
Load balancer
Backend
  1. 1TCP and TLS handshake with the balancer
    Client to Load balancer: TCP and TLS handshake with the balancer
  2. 2GET /api/orders, Host: shop.example.com
    Client to Load balancer: GET /api/orders, Host: shop.example.com
  3. 3Pick backend by path; add X-Forwarded-For
    Load balancer to Backend: Pick backend by path; add X-Forwarded-For
  4. 4200 OK with JSON
    Backend to Load balancer: 200 OK with JSON
  5. 5Response sent back over the client's TLS
    Load balancer to Client: Response sent back over the client's TLS

Choosing a balancing algorithm

Round robin sends each new request or connection to the next server in turn. It is simple and fair when requests are similar and servers are equal. Weighted round robin gives bigger servers a larger share. Least connections sends new work to the server with the fewest active connections, which is better when request times vary a lot or connections are long-lived, such as WebSockets.

Hash-based methods send the same key to the same server: source IP hash, or a hash of a URL or header. Consistent hashing keeps most keys on the same server when one is added or removed, which matters for caches. Some balancers also offer least response time or "power of two random choices", which picks two servers at random and uses the less busy one, giving good results with little coordination. Whatever you choose, a slow-starting new server should not be hit with a full share at once; many balancers ramp traffic up gradually.

  • Round robin: equal servers, similar requests
  • Least connections: uneven or long requests
  • Hash or consistent hash: cache locality, affinity
  • Weights: servers of different sizes

Health checks that tell the truth

A health check is a probe the balancer sends to each backend on a schedule. Key settings are the interval (how often), the timeout (how long to wait), the unhealthy threshold (how many failures in a row remove a server) and the healthy threshold (how many successes bring it back). A TCP check only proves the port is open. An HTTP check, such as GET /healthz expecting 200, proves the app answers.

Design the endpoint carefully. It should check what this instance needs to serve traffic, for example that it can reach its database, but it should not fail because a shared dependency is down, or every server fails at once and the balancer has nothing left. Keep it fast and cheap. Passive checks complement active ones: open-source nginx marks a server as failed after max_fails real request errors within fail_timeout. When removing a server for a deploy, use connection draining (AWS calls it deregistration delay) so in-flight requests finish first.

CycleA backend's health check states
  1. 1
    Healthy

    Receives traffic; probes keep running

  2. 2
    Failing

    Probes fail but not yet enough in a row

  3. 3
    Unhealthy

    Unhealthy threshold reached: no new traffic

  4. 4
    Recovering

    Probes succeed; count towards healthy threshold

  5. Back to step 1

TLS termination and sticky sessions

With TLS termination, the balancer holds the certificate and decrypts traffic, so it can read HTTP and route it, and backends are spared the crypto work. Traffic from the balancer to the backend is then plain HTTP, which is acceptable only on a trusted private network; for compliance or zero-trust designs, use re-encryption (the balancer opens a new TLS connection to the backend). TLS passthrough leaves encryption end to end, but then only layer 4 decisions are possible.

Sticky sessions (session affinity) keep a client on the same backend, usually with a cookie the balancer sets, or by hashing the client IP. They help apps that store session data in server memory. The downsides: uneven load, lost sessions when that server dies, and slower scale-in. The better long-term fix is to make servers stateless and keep sessions in a shared store like Redis or a database, so any server can handle any request.

  • Termination: certificates in one place, plain HTTP behind
  • Re-encryption: TLS on both legs
  • Passthrough: end-to-end TLS, layer 4 only
  • Prefer stateless apps over sticky sessions

Learn it in 4 short steps

About 30m each. Track them with a timer in your plan.

  1. 1
    Compare layer 4 and layer 7 balancing~30m
  2. 2
    Compare round robin and least connections~30m
  3. 3
    Configure health checks~30m
  4. 4
    Explain TLS termination and sticky sessions~30m

Key points

  • Algorithms include round robin, least connections and consistent hashing.
  • Health checks should test a real dependency path, not just an open port.
  • TLS termination at the balancer centralises certificates.
  • Sticky sessions pin a client to one server but weaken even distribution.

Key terms

Tap a card to flip it. 0/4 known

Examples

text
# nginx layer 7 load balancing
upstream app {
    least_conn;
    server 10.0.10.11:8080 max_fails=3 fail_timeout=10s;
    server 10.0.10.12:8080 max_fails=3 fail_timeout=10s;
}
server {
    listen 80;
    location / { proxy_pass http://app; }
}

HAProxy with health checks and least connections

Two app servers must share HTTPS traffic for shop.example.com. Step 1: terminate TLS on the frontend with a combined certificate and key file. Step 2: in the backend, use leastconn and an HTTP health check on /healthz that expects 200. Step 3: check every 5 seconds; 3 failures remove a server, 2 successes bring it back. Step 4: validate with haproxy -c -f /etc/haproxy/haproxy.cfg before reloading.

text
frontend web
    mode http
    bind :443 ssl crt /etc/haproxy/certs/shop.pem
    default_backend app

backend app
    mode http
    balance leastconn
    option httpchk
    http-check send meth GET uri /healthz
    http-check expect status 200
    option forwardfor
    server app1 10.0.10.11:8080 check inter 5s fall 3 rise 2
    server app2 10.0.10.12:8080 check inter 5s fall 3 rise 2

Users logged out at random

After adding a third server, users are sometimes logged out. Step 1: the app stores sessions in memory on each server. Step 2: with round robin, a user's next request often lands on a server that has never seen the session. Step 3: short-term fix, enable cookie-based stickiness on the balancer so each user stays on one server. Step 4: long-term fix, move sessions to Redis so every server can read them, then remove stickiness so load spreads evenly and servers can be replaced freely.

text
# HAProxy short-term fix: cookie-based stickiness
backend app
    mode http
    balance roundrobin
    cookie SRV insert indirect nocache
    server app1 10.0.10.11:8080 check cookie a1
    server app2 10.0.10.12:8080 check cookie a2
    server app3 10.0.10.13:8080 check cookie a3

Quick reference

  • Layer 4: IPs and ports, any protocol, can pass TLS through
  • Layer 7: HTTP-aware routing by host, path or header; terminates TLS
  • Round robin for equal requests; least connections for uneven or long ones
  • Health check settings: interval, timeout, unhealthy and healthy thresholds
  • Backends see the client IP via X-Forwarded-For (L7) or PROXY protocol (L4)
  • Use connection draining before removing a server during deploys
  • haproxy -c -f /etc/haproxy/haproxy.cfg and nginx -t check config before reload
  • Sticky sessions are a workaround; shared session storage is the real fix

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Which balancer can send /api to one server pool and /static to another?

Question 2

2Requests vary from 10 ms to 30 s. Which algorithm spreads load best?

Question 3

3Your health check calls the shared database. The database goes down briefly. What happens?

Question 4

4Behind a layer 7 balancer, the app logs show only the balancer's IP. How does it find the client IP?

Question 5

5Which TLS mode keeps traffic encrypted end to end but limits routing to layer 4?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Configure nginx as a round robin balancer for two backends on port 8080 and pass the client IP to them.

  2. Exercise 2medium

    Write a /healthz endpoint in Python (Flask) that returns 200 only if this instance can reach its own local cache, and 503 otherwise, answering within 1 second.

  3. Exercise 3hard

    Plan a zero-downtime deploy for three servers behind a load balancer. List the steps for each server, including draining and health checks.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

What is the difference between ALB and NLB in AWS?
An Application Load Balancer works at layer 7 and routes HTTP and HTTPS by host, path and headers. A Network Load Balancer works at layer 4 for TCP, UDP and TLS, with very high throughput and static IPs per AZ.
Is a reverse proxy the same as a load balancer?
A reverse proxy forwards client requests to backend servers; when it spreads them across several servers it is acting as a layer 7 load balancer. nginx and HAProxy do both.
Is DNS round robin a load balancer?
It spreads clients across several IPs, but it has no health checks, and clients and resolvers cache answers. It is often used in front of real load balancers, not instead of them.
Can a load balancer be a single point of failure?
Yes, if there is only one. Cloud load balancers run redundantly across zones, and self-hosted ones are usually deployed in pairs with a shared virtual IP using VRRP, for example with keepalived.

Go deeper

ShareXLinkedInWhatsApp