Load Balancing

L4 vs L7 load balancers, balancing algorithms, health checks, session affinity, global load balancing, and avoiding the load balancer as a single point of failure.

Intermediate 3 min readLesson 5 of 20

A load balancer distributes incoming requests across a pool of servers. It lets you scale horizontally, take unhealthy servers out of rotation, and deploy without downtime.

removedClientsLoad balancerhealth checksServer 1Server 2Server 3 ✗

Layer 4 vs layer 7

Layer 4 (transport)Layer 7 (application)
SeesIPs and ports (TCP/UDP)HTTP: URLs, headers, cookies, gRPC methods
RoutingPer connectionPer request: path-based, host-based, header-based
SpeedVery fast, minimal processingMore CPU (parses HTTP, often terminates TLS)
FeaturesSimple balancing, TLS passthroughTLS termination, compression, caching, retries, auth, rate limiting, canary routing
ExamplesAWS NLB, IPVS, Maglevnginx, HAProxy, Envoy, AWS ALB, Cloudflare

L7 balancers are effectively reverse proxies, and in microservices they become API gateways and service-mesh sidecars.

Algorithms

AlgorithmHowGood for
Round robinEach server in turnIdentical servers, similar requests
Weighted round robinProportionally to capacity weightsMixed server sizes, canary (5% weight)
Least connectionsServer with fewest active connectionsLong or variable-length requests (WebSockets)
Least response timeFastest recent responsesHeterogeneous performance
Power of two choicesPick 2 random servers, use the less loadedNear-optimal and cheap at scale; avoids herding
IP / consistent hashHash of client IP or a key → serverAffinity, cache locality
RandomUniformly randomSurprisingly fine with many servers

Health checks

  • Active: the balancer polls GET /health every few seconds; after N failures the server is removed, after M successes it returns.
  • Passive: watch real traffic; eject servers that return errors or time out (outlier detection).

Design health endpoints carefully:

  • Liveness — "is the process alive?" Keep it cheap. (Kubernetes restarts the container if it fails.)
  • Readiness — "can I serve traffic right now?" Checks critical dependencies; fails during startup and warm-up.
  • Don't make every instance fail its health check when a shared dependency (the database) is down — the balancer would remove all servers and turn a partial outage into a total one.

Session affinity

Sticky sessions route a user to the same server (cookie or IP hash). They help when servers hold local state, but cause uneven load and lose sessions on failures. Prefer stateless servers with shared session storage (Scalability basics).

Graceful operations

  • Connection draining: when removing a server (deploy, scale-in), stop sending new requests but let in-flight ones finish.
  • Slow start: ramp traffic up gradually to new instances so cold caches and JITs aren't overwhelmed.
  • Retries at the balancer for idempotent requests, with budgets to avoid retry storms.

The load balancer itself must not fail

  1. Redundant pairs: active–passive with a floating virtual IP (keepalived/VRRP), or active–active.
  2. DNS returns several balancer IPs.
  3. Anycast: many balancers announce the same IP; BGP spreads traffic (Google's Maglev, Cloudflare).
  4. Managed cloud load balancers are already distributed and highly available.

Global load balancing

To route users to the nearest healthy region: GeoDNS / latency-based DNS (Route 53), anycast networks, or global L7 balancers (Cloudflare, Google Cloud's global LB). Combine with health checks for regional failover.

Client-side load balancing

In service-to-service traffic, clients can balance themselves using a service registry (gRPC with xDS, Netflix Ribbon, Kubernetes headless services). That removes a network hop and a central bottleneck, at the cost of logic in every client — which is what service-mesh sidecars (Envoy) take over.

Key takeaways
  • Load balancers spread traffic, remove unhealthy servers and enable zero-downtime deploys.
  • L4 balances connections fast; L7 understands HTTP for smart routing and TLS termination.
  • Algorithms: round robin, least connections, power of two choices, consistent hashing.
  • Separate liveness and readiness; drain connections on removal.
  • Make the balancer redundant (pairs, DNS, anycast); use global LB for multi-region.