SYSTEMS LAB / SCALABILITY

Load Balancing

Distribute demand across healthy capacity without asking clients to understand the server pool.

AvailabilityHorizontal scaleHealth checks
Live trafficUsers
1,000 users840 req/s
Edge CDN68% cache hit
Load balancerRound robin
S1
62%
S2
58%
S3
65%
Server pool
Redis2.4 ms
PostgresPrimary + 2
Throughput840 rps
P95 latency82 ms
Error rate0.04%
Cache hit68%
01

Fundamental principle

A load balancer is a routing decision point. It spreads work and removes unhealthy destinations from rotation.

02

Trade-off

Round robin is predictable, but least-connections can respond better when request costs vary significantly.

03

Failure mode

Slow or inaccurate health checks can continue routing traffic to a failed server or cause unnecessary failover.

01

Overview

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.

A restaurant host

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.

02

Why you need it

  • One server cannot handle peak traffic, and vertical scaling is too expensive or has reached its limit.
  • You need zero-downtime deployments: drain a server, update it, and put it back.
  • You want the service to survive the loss of a server or an availability zone.
  • You need one place to terminate TLS, enforce limits, or route by path or host.
03

Where it shows up in interviews

Scaling a stateless tier

Recognize it when: traffic outgrows one server.

  • Scale a web app from 1 to 1M users
  • Design a URL shortener
  • Design an API gateway
High availability

Recognize it when: a server or zone may fail at any time.

  • Design a multi-AZ web application
  • Design a global service with failover
04

Where it is used in real software

AWS Elastic Load Balancing

ALB routes HTTP by host and path; NLB handles millions of TCP connections per second with static IPs.

Nginx, HAProxy, Envoy

Software load balancers used at the edge and inside service meshes for L4/L7 balancing, health checks, and retries.

Global load balancing

Google Cloud Load Balancing and Cloudflare route users to the nearest healthy region using anycast.

05

Key terms

Backend pool
The set of servers that can serve a request.
Health check
A periodic probe (for example GET /health) that marks servers healthy or unhealthy.
L4 balancing
Routes by IP and port (TCP/UDP) without reading request content. Very fast.
L7 balancing
Reads HTTP data such as path, headers, and cookies to make routing decisions.
Sticky session
Sending the same client to the same server, usually via a cookie.
Connection draining
Letting in-flight requests finish before removing a server.
06

How a request flows

  1. 1
    DNS resolves to the balancer

    The client resolves api.example.com to the balancer's IP, never to an individual server.

  2. 2
    Balancer accepts the connection

    It may terminate TLS here so backends receive plain HTTP inside the private network.

  3. 3
    Filter to healthy servers

    Servers failing recent health checks are excluded from the candidate list.

  4. 4
    Pick a server with the algorithm

    Round robin, least connections, weighted, or hashing chooses one healthy backend.

  5. 5
    Forward and relay

    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.

07

Choosing an algorithm

Three servers. Requests vary from 5 ms reads to 2 s report exports.

Step 1 / 6
AlgorithmHow it choosesBest forWeakness
Round robinNext server in orderUniform, short requestsIgnores current load
Weighted round robinProportional to weightsMixed server sizesWeights are static
Least connectionsFewest open connectionsVariable request durationNeeds connection tracking
Least response timeFastest recent latencyLatency-sensitive APIsCan oscillate under noise
IP / consistent hashhash(key) maps to serverCache affinity, sessionsHot keys create imbalance
Power of two choicesPick 2 at random, use less loadedLarge distributed poolsSlightly 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).

08

Implementation

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;    }}
09

Complexity and performance

Added latency< 1 ms

Typical in-region overhead for a software L7 balancer.

Round robinO(1)

Per-request selection cost.

Least connectionsO(log n)

With a heap; O(n) with a simple scan.

Failover timeinterval x threshold

5 s checks x 3 failures means up to 15 s of errors without passive checks.

10

Trade-offs

L4 vs L7

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.

Sticky sessions

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.

The balancer is a single point of failure

Run balancers in pairs (active-passive with a floating IP) or use managed, multi-zone balancers such as AWS ALB/NLB.

Retries amplify load

Automatic retries help with transient failures but can multiply traffic during an outage. Limit retries and only retry idempotent requests.

11

Variants and related techniques

DNS load balancing

Return multiple IPs or geographically close IPs. Cheap and global, but DNS caching makes failover slow.

Global server load balancing

Routes users to the nearest healthy region using anycast or latency-based DNS.

Client-side balancing

Clients fetch the server list from service discovery and choose themselves, common with gRPC and service meshes.

Service mesh

A sidecar proxy such as Envoy balances every service-to-service call with retries, timeouts, and mTLS.

12

Common mistakes

  • Health checks that only confirm the process is alive.

    Fix: Check critical dependencies carefully, but avoid failing every server at once because a shared database is slow.

  • Storing sessions in server memory.

    Fix: Externalize state so any server can handle any request.

  • No connection draining during deploys.

    Fix: Stop sending new requests, wait for in-flight ones, then shut down.

  • Ignoring slow servers.

    Fix: Use passive health checks (outlier detection) that eject servers with high error rates or latency.

13

Interview questions

How do you avoid the load balancer becoming a single point of failure?

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 or least connections?

Round robin for uniform, short requests. Least connections when request durations vary, because it considers current work rather than turn order.

How do you handle user sessions behind a load balancer?

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.

What happens when a server fails mid-request?

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.

14

Practice problems

ProblemDifficultyWhat it trains
Scale a single-server web app to 10x trafficEasyStateless servers behind a balancer.
Zero-downtime deploymentMediumDraining, rolling updates, health checks.
Multi-region active-active APIHardGlobal balancing and failover.