Skip to content
Visual explainer 2h to learn 3 steps

Load balancers & reverse proxies

Choose L4 vs L7 load balancing and an algorithm for a workload.

By Invicly Tech, , in System Design Deep Dive. About 11 minutes to read.

Topic 6 of 33

In short

A load balancer spreads traffic across healthy servers so no single machine is overwhelmed. Layer 4 balancers route by IP and port; Layer 7 balancers read HTTP and can route by path, header or cookie.

Think of it like this: A restaurant host seating guests at whichever table has a free waiter.

Explained simply

A load balancer stands in front of a group of servers and decides which one handles each request. Users only ever see one address. Behind it there might be two servers or two thousand, and users never need to know.

Think of a supermarket worker who points each shopper to a checkout lane. They send people to the shortest line, and if a cashier goes home sick, they stop sending anyone to that lane. Shoppers just see a store that keeps moving.

That second job, noticing broken servers, is just as important as spreading load. The load balancer keeps checking each server. If one crashes or is being updated, traffic quietly flows to the others. This is how big sites stay up during failures and deployments.

You will also hear the term reverse proxy: a server that sits in front of your app and talks on its behalf. NGINX, HAProxy, Envoy and AWS Application Load Balancer can all act as both a reverse proxy and a load balancer.

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

FlowRequest through a load balancer
  1. Step 1
    Client

    Resolves DNS to the load balancer address

  2. Step 2
    Load balancer

    Terminates TLS, picks a healthy backend

  3. Step 3
    Health checks

    Unhealthy servers removed from rotation

  4. Step 4
    App server

    Handles the request and responds

CompareL4 vs L7 load balancing
Layer 4 (transport)
  • Routes by IP and port
  • Does not read HTTP
  • Very fast, low overhead
  • Good for raw TCP or UDP
Layer 7 (application)
  • Reads URLs, headers, cookies
  • Path-based routing, TLS termination
  • Can cache, compress, rewrite
  • More CPU per request
LayersLoad balancing happens at several levels
  1. 1
    DNS or anycast

    Picks the nearest healthy region

  2. 2
    Edge / CDN

    Serves cached content, absorbs floods

  3. 3
    Regional L4 balancer

    Spreads TCP connections, very fast

  4. 4
    L7 proxies

    Route by path or header, terminate TLS

  5. 5
    Service instances

    Spread across availability zones

SequenceDraining a server during a deploy
Deploy tool
Load balancer
Server A
  1. 1Start draining Server A
    Deploy tool to Load balancer: Start draining Server A
  2. 2No new requests; in-flight ones continue
    Load balancer to Server A: No new requests; in-flight ones continue
  3. 3Last in-flight response sent
    Server A to Load balancer: Last in-flight response sent
  4. 4A drained (or 30 s limit reached)
    Load balancer to Deploy tool: A drained (or 30 s limit reached)
  5. 5Stop and start new version
    Deploy tool to Server A: Stop and start new version
  6. 6Readiness check passes
    Server A to Load balancer: Readiness check passes
  7. 7Send traffic again, ramping up slowly
    Load balancer to Server A: Send traffic again, ramping up slowly

In depth

Choosing an algorithm

Round robin is fine when servers are identical and requests cost about the same. Real fleets are messier. Weighted round robin sends more traffic to bigger machines. Least connections and least response time follow actual load, which helps when some requests take seconds.

A clever, cheap option is "power of two choices": pick two servers at random and send the request to the less busy one. It performs almost as well as checking every server, and it avoids herding, where every balancer piles onto the same "least busy" server at once. Hash-based routing is for cases where the same key should land on the same server, such as caches.

  • Equal servers, similar requests: round robin
  • Mixed machine sizes: weighted round robin
  • Uneven request times: least connections
  • Many balancers, big fleet: power of two choices
  • Cache or session affinity: consistent hashing

Health checks done right

A typical setup probes each server every 5 to 10 seconds, marks it unhealthy after 2 or 3 failures in a row, and healthy again after 2 or 3 successes. The thresholds stop one slow reply from flapping a server in and out.

Be careful with deep checks that also test the database. If the database has a hiccup, every server fails its check at the same moment and the balancer has nowhere to send traffic. Keep the health check shallow ("is this process able to serve?") and handle dependency problems in the app. Many balancers also fail open: if every target looks unhealthy, they send traffic to all of them anyway.

CycleA server's health check states
  1. 1
    Healthy

    Probed every 5 to 10 seconds

  2. 2
    Failing

    2 or 3 failed probes in a row

  3. 3
    Out of rotation

    Gets no new traffic

  4. 4
    Recovering

    2 or 3 successes in a row: back in

  5. Back to step 1

Connection draining and safe deploys

Pulling a server out abruptly cuts off requests that are halfway done. Instead, the balancer drains it: it stops sending new requests but lets in-flight ones finish, usually with a limit of about 30 seconds. AWS calls this the deregistration delay.

The reverse matters too. A fresh server should only get traffic once its readiness check passes, meaning it has loaded config, opened database connections and warmed its caches. Some balancers add a slow start, ramping new servers up gradually instead of hitting them with a full share at once.

Balancing across the globe

Inside one region a load balancer picks a server. Across regions, something has to pick the region first. GeoDNS or latency-based DNS, such as Amazon Route 53, answers each user with the address of a nearby region and stops returning a region that fails its health checks. The catch is caching: clients and resolvers may keep an old DNS answer for the TTL or longer, so failover can take minutes.

Anycast is the other approach. The same IP address is announced from many locations, and internet routing carries each user to the nearest one. Cloudflare and Google's global load balancer use anycast, which reacts faster than DNS changes.

Who balances the balancer?

A single load balancer is a single point of failure. Managed ones, such as AWS ALB and NLB or Google Cloud Load Balancing, are built from many machines across zones, so you get redundancy without thinking about it.

If you run your own, the classic setup is two HAProxy or NGINX machines and a tool called keepalived. They share one virtual IP address using a protocol called VRRP. The active machine holds the address, and if it stops responding, the standby claims it within a few seconds. Large systems often stack layers: a fast L4 balancer in front of a fleet of L7 proxies.

Sequencekeepalived failover with a virtual IP
Active balancer
Standby balancer
Clients
  1. 1VRRP adverts: I hold the virtual IP
    Active balancer to Standby balancer: VRRP adverts: I hold the virtual IP
  2. 2Traffic to the virtual IP
    Clients to Active balancer: Traffic to the virtual IP
  3. 3Adverts stop (active fails)
    Active balancer to Standby balancer: Adverts stop (active fails)
  4. 4Standby claims the IP within seconds
    Standby balancer to Clients: Standby claims the IP within seconds
  5. 5Same virtual IP, new machine
    Clients to Standby balancer: Same virtual IP, new machine

Learn it in 3 short steps

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

  1. 1
    Compare L4 and L7 load balancing~40m
  2. 2
    Choose round robin, least connections or hashing~40m
  3. 3
    Explain health checks and reverse proxies~40m

Key points

  • Round robin suits similar requests; least connections suits uneven request durations.
  • Hash-based routing keeps a client or key on the same backend.
  • Health checks remove failed servers automatically.
  • Run load balancers in redundant pairs so they are not a single point of failure.
  • A reverse proxy also adds TLS termination, caching and compression.

Key terms

Tap a card to flip it. 0/5 known

Examples

How round robin piles slow work on one server

Three servers sit behind round robin. A client sends requests in a repeating pattern: fast, fast, export, where an export takes 10 seconds and the others take 10 ms. Round robin sends request 1 to server A, 2 to B, 3 to C, then 4 to A again. Every third request is an export, so every export lands on server C. Within a minute C has dozens of exports running and is overloaded while A and B sit idle. Least connections fixes this: C has many open requests, so new work goes elsewhere.

A small NGINX load balancer

This config terminates HTTPS and spreads requests across three app servers using least connections. The third server is bigger, so it gets double weight. max_fails and fail_timeout give passive health checking: after 3 failed requests within 10 seconds, NGINX skips that server for 10 seconds. Active health probes need NGINX Plus or a different proxy such as HAProxy or Envoy.

nginx
upstream api {
    least_conn;
    server 10.0.1.11:8080 max_fails=3 fail_timeout=10s;
    server 10.0.1.12:8080 max_fails=3 fail_timeout=10s;
    server 10.0.1.13:8080 weight=2;   # bigger machine
}

server {
    listen 443 ssl;
    server_name api.example.com;
    ssl_certificate     /etc/nginx/tls/api.crt;
    ssl_certificate_key /etc/nginx/tls/api.key;
    location / { proxy_pass http://api; }
}

Quick reference

  • Round robin for equal servers and requests; least connections for uneven request times
  • Power of two choices: pick 2 random servers, send to the less busy one
  • Health check every 5–10 s; remove after 2–3 failures, re-add after 2–3 passes
  • Keep health checks shallow so one database blip does not remove every server
  • Drain for ~30 s before stopping a server; only send traffic once it is ready
  • DNS failover is slowed by cached answers; keep health-checked records at low TTLs
  • Self-hosted HA: two HAProxy nodes with keepalived sharing a virtual IP

Common mistakes

  • Using round robin when some requests take seconds and others milliseconds.
  • Health checks that only test the port, not real dependencies.
  • A single load balancer instance becoming the new single point of failure.

Quick quiz

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

Question 1

1What problem does "power of two choices" solve?

Question 2

2Why can a health check that queries the database be dangerous?

Question 3

3What does connection draining do?

Question 4

4Why can DNS-based regional failover be slow?

0/4 answered

Practice exercises

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

  1. Exercise 1easy

    Pick a balancing algorithm for each case: (a) identical API servers with similar requests; (b) servers that mix 5 ms reads with 5 s report exports; (c) cache servers where the same key should hit the same node.

  2. Exercise 2medium

    Design the health check for a web service that depends on PostgreSQL and Redis. Say what the endpoint checks, the probe interval and thresholds, and how you handle a database outage.

  3. Exercise 3hard

    Design load balancing for an app running in three regions so that users go to the nearest region and survive the loss of a whole region.

Check yourself

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

Feel confident about this topic?

Frequently asked questions

Is a load balancer the same as a reverse proxy?
They overlap. A reverse proxy sits in front of servers and forwards requests; a load balancer spreads those requests across several servers. Most modern tools such as NGINX and Envoy do both.
Does a load balancer slow down requests?
Very little. A load balancer in the same data centre usually adds well under a millisecond, which is tiny compared with the time the app itself takes.
Do I need a load balancer if I use Kubernetes?
Kubernetes Services already spread traffic across pods inside the cluster. You still need an Ingress or a cloud load balancer to bring outside traffic into the cluster.
ShareXLinkedInWhatsApp