A load balancer sits in front of a pool of servers and decides which one handles each request. It is what turns "one server" into "a fleet": it spreads load so no machine is overwhelmed, removes failed servers from rotation automatically, and lets you add capacity or deploy new versions without users noticing. Nearly every architecture diagram has one, and interviewers expect you to know how it chooses, what layer it works at, and how it avoids becoming a single point of failure itself.
Think of it like
The supermarket checkout manager
A manager stands at the end of the aisles and points each shopper to a till. Sending shoppers to each till in turn is round robin; sending them to the shortest queue is least connections; giving the fastest cashier more shoppers is weighting. When a till's light goes off (a failed health check), nobody is sent there, and when the store gets busy, the manager opens more tills.
Why load balance
- Horizontal scaling: add servers to add capacity, instead of buying an ever-bigger machine. See Scalability.
- Availability: health checks take failed or overloaded servers out of rotation in seconds.
- Zero-downtime deploys: drain a server, upgrade it, put it back; or shift traffic gradually between versions (blue/green, canary).
- One stable entry point: clients see a single address while servers come and go behind it.
- A place for cross-cutting work: TLS termination, request logging, connection limits and basic DDoS protection.
The simulation above lets you switch algorithms and kill servers to see how load shifts. The diagram below shows the moving parts; press play to follow a request and a failure.
Layer 4 vs layer 7
Load balancers are classified by the OSI layer they make decisions at. A layer 4 balancer sees only IP addresses, ports and TCP/UDP packets. A layer 7 balancer terminates the connection, parses HTTP (or gRPC), and can route on anything in the request. See Networking Essentials for the layers themselves.
Layer 4 (transport)
- Routes TCP/UDP flows by IP and port; never reads the payload
- Extremely fast, millions of connections, low CPU per packet
- Can pass TLS through untouched (end-to-end encryption)
- Cannot route by URL, header or cookie, or retry a failed HTTP request
- Examples: AWS NLB, Linux IPVS, HAProxy
mode tcp, Google Maglev
Layer 7 (application)
- Terminates the client connection and parses each HTTP request
- Routes by host, path, header, cookie or method (
/apivs/static) - Can retry, rewrite, compress, cache, rate-limit and authenticate
- More CPU and memory per request; must hold TLS keys to see inside HTTPS
- Examples: AWS ALB, NGINX, HAProxy
mode http, Envoy, Traefik
Load-balancing algorithms
| Algorithm | How it picks | Best for | Watch out for |
|---|---|---|---|
| Round robin | Next server in a fixed rotation | Identical servers, similar request costs | Ignores load: slow requests pile up on one server |
| Weighted round robin | Rotation in proportion to weights | Mixed instance sizes, canaries (weight 5 vs 95) | Weights are static guesses |
| Least connections | Server with the fewest open connections | Long-lived or variable requests: WebSockets, uploads | Connection count is only a proxy for real load |
| Least response time | Lowest recent latency (often combined with active requests) | Servers with uneven performance | Needs measurement; a newly fast server can get stampeded |
| IP hash | hash(client IP) mod N | Simple affinity without cookies | NAT skews load; changing N reshuffles almost everyone |
| Consistent hashing | Hash servers and keys onto a ring; key goes to the next server clockwise | Cache affinity: the same key always hits the same node | Hot keys; needs virtual nodes to balance |
| Power of two random choices | Sample 2 servers at random, send to the less loaded | Large fleets and many independent load balancers | Needs a cheap load signal (active requests) |
Why "power of two choices" is so effective
Picking a server uniformly at random is simple but lumpy: with n requests over n servers, the busiest server ends up with about log n / log log n of them. Checking just two random servers and taking the less loaded one collapses that to about log log n, an exponential improvement for almost no cost.
It also avoids the herd effect of pure least-loaded routing. When ten load balancers share a slightly stale view of the fleet, they all pick the same "least loaded" server at once and overload it. Random sampling breaks the tie. Envoy's least-request balancer, NGINX's random two least_conn and HAProxy's balance random(2) all use this idea.
Smooth weighted round robin
Naive weighting with weights a=5, b=1, c=1 produces a a a a a b c, a burst of five requests to one server. NGINX's smooth algorithm interleaves them as a a b a c a a: every pick, each server's running score grows by its weight, the highest score wins, and the winner's score drops by the total weight.
Health checks
Active checks
- The balancer probes each server (
GET /healthz) on a timer - Thresholds avoid flapping: e.g. 2 failures to eject, 3 successes to restore
- Detects dead servers even when they get no traffic
- Adds probe traffic; interval bounds detection time
Passive checks (outlier detection)
- Watch real responses: eject a server after 5 consecutive 5xx or timeouts
- No extra traffic and reacts to what users actually experience
- Needs traffic to notice anything
- Envoy outlier detection; NGINX
max_fails/fail_timeout
frontend web
bind :443 ssl crt /etc/haproxy/certs/site.pem
mode http
default_backend app
backend app
mode http
balance leastconn
option httpchk GET /healthz
http-check expect status 200
default-server inter 5s fall 2 rise 3
server app1 10.0.1.11:8080 check weight 100
server app2 10.0.1.12:8080 check weight 100
server app3 10.0.1.13:8080 check weight 50 # smaller instanceSticky sessions
Session affinity sends a given user to the same server every time, usually via a cookie the balancer inserts (such as AWSALB) or by hashing the client IP. It exists because some applications keep session state in server memory.
Why people use it
- Legacy apps with in-memory sessions keep working
- Per-server caches stay warm for each user
- Some protocols need it (long-polling fallbacks, stateful game servers)
Why it hurts
- Load becomes uneven: heavy users pin one server
- A server crash logs out everyone stuck to it
- New servers only receive new users, so scaling out helps slowly
- Draining for deploys takes as long as the longest session
TLS termination
| Mode | How it works | Trade-off |
|---|---|---|
| Termination | The balancer decrypts HTTPS and forwards plain HTTP inside the private network | Offloads crypto, central certificate management, enables L7 routing; traffic is unencrypted on the internal hop |
| Re-encryption | Decrypt at the balancer, then open a new TLS (often mTLS) connection to the backend | L7 features plus encryption everywhere (zero trust); extra CPU and certificate management |
| Passthrough | An L4 balancer forwards encrypted bytes untouched; backends hold the certificates | True end-to-end encryption; no L7 routing, and certificate rotation touches every server |
Making the load balancer itself redundant
A single load balancer is a single point of failure. The classic fix is an active-passive pair sharing a floating virtual IP. The two nodes run VRRP (for example with keepalived): the active node owns the VIP and sends advertisements every second; if they stop, the standby claims the VIP by broadcasting a gratuitous ARP so the network sends packets to its MAC address instead.
Active-active setups run several balancers at once and spread traffic across them with DNS (multiple A records), ECMP routing or anycast. Cloud balancers such as ALB and NLB are already distributed fleets spread across availability zones, which is a big part of why teams use them.
Global server load balancing
Load balancing happens at several tiers. Global server load balancing (GSLB) picks a region using health-aware DNS (see Domain Name System (DNS)) or anycast, then regional balancers pick a server.
| Tier | Chooses | Mechanism | Examples |
|---|---|---|---|
| Global | Region or data center | GeoDNS, latency-based DNS, anycast | Route 53, Cloudflare Load Balancing, AWS Global Accelerator, Google Cloud global LB |
| Regional L4 | Load balancer node | ECMP, anycast, consistent hashing of flows | AWS NLB, Maglev, Katran |
| Regional L7 | Service instance | HTTP routing and algorithms above | AWS ALB, Envoy, NGINX, HAProxy |
| Client-side | Instance, from inside the caller | Library plus service discovery | gRPC client-side balancing, service mesh sidecars |
Software vs cloud load balancers
| Option | Layer | Strengths | Notes |
|---|---|---|---|
| NGINX | L7 (and L4 via stream) | Web server, reverse proxy and balancer in one; ubiquitous | Active health checks are an NGINX Plus feature; open source uses passive checks |
| HAProxy | L4 and L7 | Very fast, rich algorithms, detailed stats, runtime API | Configuration-file driven |
| Envoy | L4 and L7 | Dynamic configuration via xDS APIs, first-class gRPC, deep observability | The data plane of most service meshes; more complex to run |
| AWS ALB | L7 | Managed, host/path routing, WAF and auth integration, Lambda targets | Scales automatically; billed per hour plus capacity units |
| AWS NLB | L4 | Millions of requests per second, static IP per zone, preserves client IP | Optional TLS termination; no HTTP-level routing |
| Google Cloud / Azure | L4 and L7 | Global anycast front ends (Google), Front Door and Application Gateway (Azure) | Similar trade-offs: managed, regional or global |
Implementation
Round robin, least connections, power of two choices and NGINX-style smooth weighted round robin.
import itertools
import random
from dataclasses import dataclass
@dataclass
class Backend:
name: str
weight: int = 1
active: int = 0 # in-flight requests
healthy: bool = True
def healthy(pool: list[Backend]) -> list[Backend]:
return [b for b in pool if b.healthy]
class RoundRobin:
def __init__(self) -> None:
self._counter = itertools.count()
def pick(self, pool: list[Backend]) -> Backend:
up = healthy(pool)
return up[next(self._counter) % len(up)]
def least_connections(pool: list[Backend]) -> Backend:
return min(healthy(pool), key=lambda b: b.active)
def power_of_two(pool: list[Backend]) -> Backend:
up = healthy(pool)
a, b = random.choice(up), random.choice(up)
return a if a.active <= b.active else b
class SmoothWeighted:
"""NGINX smooth weighted round robin: weights 5,1,1 -> a a b a c a a."""
def __init__(self) -> None:
self.current: dict[str, int] = {}
def pick(self, pool: list[Backend]) -> Backend:
up = healthy(pool)
total = 0
best = None
for b in up:
self.current[b.name] = self.current.get(b.name, 0) + b.weight
total += b.weight
if best is None or self.current[b.name] > self.current[best.name]:
best = b
self.current[best.name] -= total
return bestKey takeaways
- Load balancers provide scaling, availability (via health checks) and a stable entry point that hides servers coming and going.
- L4 balancers route connections by IP and port at very high speed; L7 balancers understand HTTP and can route, retry and transform requests.
- Pick the algorithm for the workload: round robin for uniform requests, least connections for long-lived ones, consistent hashing for cache affinity, power of two choices at scale.
- Keep health checks shallow and use thresholds plus connection draining for smooth deploys.
- Stateless servers beat sticky sessions; move state to shared stores or tokens.
- The balancer must be redundant too: active-passive with a floating VIP, active-active, or a managed cloud balancer.
Common pitfalls
- Using round robin when request costs vary wildly, so slow requests pile up on unlucky servers.
- Health checks that test downstream dependencies, so one database blip ejects the whole fleet.
- Relying on sticky sessions and losing every pinned user's session when a server dies.
- Drawing a single load balancer with no redundancy and calling the design highly available.
- Forgetting that L7 balancers terminate TLS, so they need certificates and add a decrypt/re-encrypt hop.
Interview tips
- Name the algorithm and justify it from the traffic pattern; mention power of two choices for large fleets.
- Explain L4 vs L7 and say which you would use where (often both: L4 at the edge, L7 in front of services).
- Cover health checks, draining and LB redundancy without being asked; it signals production experience.
Real-world applications
- Fronting stateless web and API tiers.
- Spreading WebSocket connections with least connections.
- Canary releases via weighted target groups.
- Cache clusters routed with consistent hashing.
- Multi-region traffic management with GSLB.
Test yourself
Your servers hold long-lived WebSocket connections of very different durations. Which algorithm spreads load best?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.