Fundamental principle
A load balancer is a routing decision point. It spreads work and removes unhealthy destinations from rotation.
SYSTEMS LAB / SCALABILITY
Distribute demand across healthy capacity without asking clients to understand the server pool.
A load balancer is a routing decision point. It spreads work and removes unhealthy destinations from rotation.
Round robin is predictable, but least-connections can respond better when request costs vary significantly.
Slow or inaccurate health checks can continue routing traffic to a failed server or cause unnecessary failover.
A load balancer sits between clients and a pool of servers and decides which server handles each request. Clients talk to one stable address; the balancer spreads the work, detects failed servers, and removes them from rotation.
Load balancing is what makes horizontal scaling possible. Instead of buying one bigger machine, you add more identical machines behind the balancer. It also improves availability because a single server failure no longer takes the service down.
Guests do not pick a waiter; the host at the door seats each party at a section that has capacity. If a waiter goes home sick, the host stops seating guests in that section. Diners never need to know how many waiters are working.
Recognize it when: traffic outgrows one server.
Recognize it when: a server or zone may fail at any time.
ALB routes HTTP by host and path; NLB handles millions of TCP connections per second with static IPs.
Software load balancers used at the edge and inside service meshes for L4/L7 balancing, health checks, and retries.
Google Cloud Load Balancing and Cloudflare route users to the nearest healthy region using anycast.
The client resolves api.example.com to the balancer's IP, never to an individual server.
It may terminate TLS here so backends receive plain HTTP inside the private network.
Servers failing recent health checks are excluded from the candidate list.
Round robin, least connections, weighted, or hashing chooses one healthy backend.
The request goes to the chosen server, and the response is returned to the client. Headers such as X-Forwarded-For preserve the client's IP.
Three servers. Requests vary from 5 ms reads to 2 s report exports.
| Algorithm | How it chooses | Best for | Weakness |
|---|---|---|---|
| Round robin | Next server in order | Uniform, short requests | Ignores current load |
| Weighted round robin | Proportional to weights | Mixed server sizes | Weights are static |
| Least connections | Fewest open connections | Variable request duration | Needs connection tracking |
| Least response time | Fastest recent latency | Latency-sensitive APIs | Can oscillate under noise |
| IP / consistent hash | hash(key) maps to server | Cache affinity, sessions | Hot keys create imbalance |
| Power of two choices | Pick 2 at random, use less loaded | Large distributed pools | Slightly less exact |
NOWAlgorithm: Round robin | How it chooses: Next server in order | Best for: Uniform, short requests | Weakness: Ignores current load
With slow report exports mixed in, round robin keeps sending new requests to a server stuck on exports. Least connections steers traffic away from busy servers, which improves tail latency (P99).
upstream api_servers { least_conn; # algorithm server 10.0.1.10:8080 weight=2; # larger machine server 10.0.1.11:8080; server 10.0.1.12:8080 max_fails=3 fail_timeout=30s; keepalive 64; # reuse upstream connections} server { listen 443 ssl; server_name api.example.com; location / { proxy_pass http://api_servers; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_next_upstream error timeout http_502 http_503; proxy_connect_timeout 2s; proxy_read_timeout 10s; }}Typical in-region overhead for a software L7 balancer.
Per-request selection cost.
With a heap; O(n) with a simple scan.
5 s checks x 3 failures means up to 15 s of errors without passive checks.
L4 is faster and protocol-agnostic but cannot route by URL or inspect headers. L7 enables path routing, header rewrites, and retries at the cost of more CPU.
They make stateful servers work but cause uneven load and lose sessions when a server dies. Prefer stateless servers with sessions in Redis or signed tokens.
Run balancers in pairs (active-passive with a floating IP) or use managed, multi-zone balancers such as AWS ALB/NLB.
Automatic retries help with transient failures but can multiply traffic during an outage. Limit retries and only retry idempotent requests.
Return multiple IPs or geographically close IPs. Cheap and global, but DNS caching makes failover slow.
Routes users to the nearest healthy region using anycast or latency-based DNS.
Clients fetch the server list from service discovery and choose themselves, common with gRPC and service meshes.
A sidecar proxy such as Envoy balances every service-to-service call with retries, timeouts, and mTLS.
Fix: Check critical dependencies carefully, but avoid failing every server at once because a shared database is slow.
Fix: Externalize state so any server can handle any request.
Fix: Stop sending new requests, wait for in-flight ones, then shut down.
Fix: Use passive health checks (outlier detection) that eject servers with high error rates or latency.
Run multiple balancer instances across zones with a floating IP or anycast, or use a managed balancer. DNS can list several balancer IPs as a further layer.
Round robin for uniform, short requests. Least connections when request durations vary, because it considers current work rather than turn order.
Make servers stateless: keep sessions in a shared store such as Redis, or use signed tokens. Sticky sessions are a fallback with availability and balance costs.
The client gets an error or the balancer retries on another server if the request is idempotent. Health checks then remove the server from rotation.
| Problem | Difficulty | What it trains |
|---|---|---|
| Scale a single-server web app to 10x traffic | Easy | Stateless servers behind a balancer. |
| Zero-downtime deployment | Medium | Draining, rolling updates, health checks. |
| Multi-region active-active API | Hard | Global balancing and failover. |