Skip to main content

Load Balancing

Learning objectives
  • Explain what an L4 and an L7 load balancer can and cannot see, and pick one for a given traffic type (HTTP APIs, gRPC, raw TCP to a payment switch)
  • Compare balancing algorithms (round robin, weighted, least connections, least response time, consistent hash, power of two choices) and predict how each behaves under uneven load
  • Design health checks that remove bad instances without causing cascading outages
  • Design global traffic steering (GeoDNS, GSLB, anycast) and a highly available load-balancing tier for a bank or marketplace

TL;DR​

  • A load balancer spreads requests across a pool, hides failures (via health checks) and is a control point for TLS, routing, retries and rate limits.
  • L4 balances TCP/UDP connections by address and port — fast, protocol-agnostic, blind to HTTP. L7 terminates the connection and understands HTTP/gRPC — it can route by path or header, retry, and balance per request.
  • Power of two choices (P2C) with least-outstanding-requests is the modern default for service-to-service traffic: nearly as good as global least-connections, without global state.
  • Health checks should be shallow for liveness, scoped for readiness, combined with passive outlier detection; a "deep" check that fails when the shared database blips can eject every instance at once.
  • Never let the load balancer blindly retry non-idempotent requests such as POST /payments.
  • Global load balancing is DNS-based (GeoDNS, latency/failover routing) or anycast-based; DNS failover is bounded by TTLs and resolver caching.
  • The load balancer must not be a single point of failure: VRRP pairs, ECMP across L4 nodes, or a managed multi-AZ service.

Why it matters​

Every request to a checkout API or an internet-banking login goes through at least one load balancer, usually several (edge, API gateway, service mesh sidecar). Design decisions here show up directly in incidents:

  • A payment POST times out at the LB, the LB retries on another instance, and the customer is charged twice.
  • A gRPC fraud-scoring service is scaled from 4 to 12 pods before a sale, but the new pods get no traffic because clients hold long-lived HTTP/2 connections balanced at L4.
  • A health check that pings the database fails during a 5-second failover, the LB marks every instance unhealthy, and a 5-second blip becomes a 3-minute outage.

Banks add constraints: TLS termination points define PCI DSS scope, mutual TLS with partners (card schemes, national switches) needs end-to-end control, and on-premises hardware appliances (F5, Citrix) are common alongside cloud load balancers.

Core concepts​

Where load balancers sit​

  • Edge: public entry; TLS, DDoS and WAF, routing to gateways or services.
  • Internal: between services, either a central internal LB, a sidecar proxy (service mesh), or a client-side library (gRPC's built-in balancers).
  • Database proxies: PgBouncer, ProxySQL, or cloud proxies that balance and pool connections to primaries and replicas.

L4 vs L7​

L4 (transport)L7 (application)
SeesIPs, ports, TCP/UDPHTTP method, path, headers, cookies, gRPC service/method
Unit balancedConnection (or flow)Request
TLSUsually passthrough (can terminate in some products)Terminates TLS, may re-encrypt to backends
FeaturesVery high throughput, low latency, any protocolPath/host routing, retries, timeouts, header rewriting, auth, compression, canary splits
CostCheap per connectionCPU for TLS and parsing, holds certificates and keys
ExamplesLinux IPVS, AWS NLB, Google Maglev, F5 in L4 modeNGINX, HAProxy, Envoy, AWS ALB, API gateways

Key consequences:

  • Long-lived multiplexed connections (HTTP/2, gRPC, WebSockets) are poorly balanced by L4: one connection carries thousands of requests, and new backends receive nothing until clients reconnect. Use L7 or client-side balancing for gRPC (see RPC & gRPC).
  • End-to-end mTLS to a partner bank or card network often requires L4 passthrough so the backend presents and verifies certificates itself.
  • L4 balancers can use direct server return (DSR): requests go through the LB, responses go straight from backend to client, so the LB handles only inbound bytes. Useful when responses are much larger than requests.

More on proxy types and gateways in Proxies, Load Balancers & API Gateways.

Balancing algorithms​

AlgorithmHow it worksGood forWeak when
Round robinNext backend in orderHomogeneous backends, uniform requestsRequests vary in cost; backends differ in size
Weighted round robinRound robin with weightsMixed instance sizes, canary at 5%Weights are static; ignore live load
RandomPick uniformly at randomSimple, stateless, many LB nodesSame as round robin, plus variance
Least connectionsBackend with fewest open connectionsLong or variable request durationsNeeds accurate shared state; misleading with HTTP/2 multiplexing
Least outstanding requestsFewest in-flight requests (L7)Variable-cost API callsSame state problem across many LB nodes
Least response time / EWMAScore by smoothed latency (often × in-flight)Heterogeneous or degrading backendsA fast-failing backend looks attractive unless errors are penalised
Power of two choices (P2C)Pick 2 random backends, send to the less loadedLarge fleets, many independent LB nodes, sidecarsTiny pools (2–3 backends) gain little
Source IP hashHash client IP to a backendCrude affinity without cookiesNAT gateways put thousands of users behind one IP
Consistent hash (ring, Maglev)Hash a key (user id, cart id, URL) onto a ring/tableCache locality, session affinity, sharded stateful backendsHot keys overload one backend

Why P2C works. Picking the least-loaded of all backends requires a global, up-to-date view; with many LB nodes, they all see the same "least loaded" backend and stampede it (herd behaviour). Picking one random backend ignores load. Picking the better of two random backends gives an exponential improvement in maximum load over pure random (Mitzenmacher's "power of two choices" result) while each LB node needs only local counts. Envoy's least-request balancer and Linkerd's EWMA-based balancer use this idea.

Hash-based balancing is what you use when the backend holds state worth reusing: a cache shard, a WebSocket session server, or a per-cart actor. Consistent hashing keeps most keys on the same backend when the pool changes (see Consistent Hashing).

Health checks​

  • Active checks: the LB polls /healthz every few seconds; an instance is removed after N consecutive failures and re-added after M passes. Thresholds prevent flapping.
  • Passive checks (outlier detection): the LB watches real traffic and ejects an instance after, say, 5 consecutive 5xx or a latency outlier, for a growing ejection period. Catches failures between active checks.
  • Liveness vs readiness: liveness answers "should this process be restarted?" and must not depend on downstreams. Readiness answers "should this instance get traffic now?" and may check local prerequisites (warm caches, config loaded).
  • Deep checks are dangerous. If every instance's readiness check queries the shared database, a DB failover marks the whole fleet unhealthy simultaneously. Check only what is instance-specific; let circuit breakers handle shared dependencies.
  • Panic mode: some proxies (Envoy, for example) stop honouring health status when too large a fraction of the pool is unhealthy and spread traffic over all hosts, on the theory that the health signal is probably wrong.
  • Slow start: new instances (cold JIT, empty caches, no DB connections yet) receive a ramp of traffic instead of a full share immediately.
  • Connection draining: on deregistration the LB stops sending new requests but lets in-flight ones finish within a timeout. Pair with graceful shutdown in the service (see Scaling from Zero to Millions).

Sticky sessions​

Session affinity routes a client to the same backend each time:

  • LB-inserted cookie: the LB adds a cookie naming the backend.
  • Application cookie: the LB hashes an existing session cookie.
  • Source IP hash: no cookie needed, but broken by NAT and mobile networks changing IPs.

Costs: uneven load (a few heavy users pin one instance), sessions lost when an instance dies, scale-out does not help existing users, and draining takes longer. Use stickiness only when there is real per-instance state you cannot externalise yet — legacy servlet apps, WebSocket servers, or in-process caches where hit rate matters. For new services, externalise state and stay stateless.

Global load balancing​

  • DNS-based GSLB: the authoritative DNS returns different IPs based on resolver location (GeoDNS), measured latency, weights, or health (failover routing). Simple and works with any protocol. Weakness: clients and resolvers cache answers; some ignore low TTLs, so failover takes from tens of seconds to minutes for most users and longer for a tail. See DNS.
  • Anycast: the same IP is announced via BGP from many locations; the internet routes each client to the topologically nearest site. Failover is as fast as BGP withdrawal, no DNS caching problem. Used by CDNs, public DNS resolvers and some cloud global load balancers. Requires owning address space and network expertise, so most teams get it through a provider.
  • Global L7 proxies: a provider terminates TLS at the nearest edge (via anycast) and forwards over its backbone to the healthiest region.

For banks, global steering is usually about DR failover between two in-country datacenters (data-residency rules often keep customer data in-country), not about latency across continents.

High availability of the load balancer itself​

  • Active-passive pair with a floating VIP: two nodes run VRRP (for example via keepalived); the standby takes over the virtual IP when heartbeats stop. Simple, common on-premises; capacity is limited to one node and failover drops in-flight connections unless connection state is synchronised.
  • Active-active with ECMP: routers spread flows across several L4 nodes announcing the same VIP via BGP. Each L4 node uses consistent hashing (Maglev-style) to pick an L7 proxy, so a flow lands on the same proxy even if it passes through a different L4 node after a change. This is how large internet companies build the tier.
  • Managed cloud LBs are multi-AZ by design; your job is to spread targets across AZs and test AZ failure.

Trade-offs​

OptionStrengthsWeaknessesChoose when
L4 LBFast, cheap, any protocol, TLS passthroughNo per-request balancing, no HTTP featuresRaw TCP (ISO 8583 to a card switch), mTLS passthrough, front of an L7 tier
L7 LB / reverse proxyPath routing, retries, canaries, per-request balancingCPU cost, sees plaintext, more config surfaceHTTP/gRPC APIs, most web traffic
Client-side LB (gRPC, library)No extra hop, per-request, rich algorithmsLogic in every client language, needs service discoveryInternal gRPC in a homogeneous stack
Sidecar / service meshUniform policy, mTLS, telemetry without codeOperational complexity, extra latency per hopMany services, many languages, zero-trust goals
Round robinSimple and predictableIgnores loadUniform, cheap requests
P2C least-requestRobust, no global stateSlightly more logicDefault for service-to-service
Consistent hashLocality, affinityHot keys, uneven loadCaches, stateful shards
DNS GSLBSimple, protocol-agnosticTTL and resolver caching slow failoverRegional DR, coarse geo-routing
AnycastFast failover, nearest PoPNeeds BGP and IP space, or a providerGlobal edge, DDoS absorption

In practice​

  • Timeouts must line up. The backend's keep-alive idle timeout should be longer than the LB's idle timeout; otherwise the backend closes a connection the LB just chose to reuse and you see sporadic 502s that no one can reproduce.
  • Retries at the LB only for safe requests. Retry GET and idempotent PUTs on connect errors; never retry a POST /payments after the request was sent unless the API uses idempotency keys (see Idempotency & Exactly-Once). NGINX, for example, does not pass non-idempotent methods to the next upstream once the request was sent unless you opt in — know your proxy's default.
  • Retry budgets. Cap retries to a fraction of traffic (for example 10–20%) so a partial outage does not double total load.
  • Preserve client identity. Use X-Forwarded-For or the PROXY protocol and only trust it from your own LB addresses; fraud and rate-limit systems depend on the real client IP.
  • gRPC: use L7 (Envoy, a mesh) or the gRPC client's round_robin / custom balancer with DNS or xDS discovery; set MaxConnectionAge on servers so clients periodically reconnect and rebalance.
  • A P2C picker in Go shows how little state the algorithm needs:
package lb

import (
"context"
"errors"
"math/rand/v2"
"sync/atomic"
)

type Backend struct {
Addr string
inflight atomic.Int64
}

type P2C struct {
backends []*Backend // healthy set; in real code swap it via atomic.Pointer when health changes
}

var ErrNoBackends = errors.New("lb: no healthy backends")

// pick returns the less loaded of two distinct random backends.
func (p *P2C) pick() (*Backend, error) {
n := len(p.backends)
switch n {
case 0:
return nil, ErrNoBackends
case 1:
return p.backends[0], nil
}
i := rand.IntN(n)
j := rand.IntN(n - 1)
if j >= i {
j++
}
a, b := p.backends[i], p.backends[j]
if b.inflight.Load() < a.inflight.Load() {
return b, nil
}
return a, nil
}

// Do runs call against a chosen backend while tracking in-flight requests.
func (p *P2C) Do(ctx context.Context, call func(ctx context.Context, addr string) error) error {
b, err := p.pick()
if err != nil {
return err
}
b.inflight.Add(1)
defer b.inflight.Add(-1)
return call(ctx, b.Addr)
}
  • Rough numbers: a modern L7 proxy instance handles tens of thousands of requests per second per few cores, dominated by TLS handshakes and request size; L4 balancers in the kernel or with XDP handle millions of packets per second per node. Measure with your payload sizes and TLS settings.

Common pitfalls​

  • LB retries a timed-out payment. Symptom: duplicate charges correlated with backend latency spikes.
  • Health check depends on the database. Symptom: brief DB failover causes all instances to go unhealthy and a full outage.
  • gRPC behind an L4 balancer. Symptom: after scaling out, new pods sit idle while old ones are at 90% CPU.
  • Idle timeout mismatch. Symptom: rare, random 502s on reused connections, especially after quiet periods.
  • Sticky sessions plus autoscaling. Symptom: scaling out does not lower load on hot instances; a node failure logs out thousands of users.
  • Low DNS TTL assumed to mean fast failover. Symptom: after a regional failover, a long tail of clients keeps hitting the dead region for minutes.
  • Trusting X-Forwarded-For from anyone. Symptom: attackers bypass IP-based rate limits by spoofing the header.
  • Single LB instance or VIP in one AZ. Symptom: an AZ outage takes the whole service down even though app instances survive elsewhere.

Interview angle​

  • Where it appears: every design has a load balancer box; the strong candidate explains what it does. Bank interviews often probe TLS termination, mTLS and DR failover; e-commerce interviews probe scaling for sales and gRPC between services.
  • Strong answer covers: L4 vs L7 choice with a reason, the algorithm and why (P2C or least-request for APIs, consistent hash for caches), health-check design, retry safety, how the LB itself is HA, and how global failover works and how long it takes.
  • Follow-ups: "How does the LB know a server is unhealthy?", "Why did new pods get no traffic?", "How do you do a canary at 1%?", "What happens to in-flight requests during a deploy?", "How fast is your DNS failover really?"
  • Red flags: "the load balancer handles it" without specifics, sticky sessions as the default, LB-level retries on payments, no answer for LB failure.

Self-check​

1. What can an L7 load balancer do that an L4 one cannot, and what does it cost?

L7 parses HTTP/gRPC, so it can route by host/path/header, balance individual requests over multiplexed connections, retry, apply timeouts, rewrite headers, do canary splits and authentication. The cost is CPU for TLS and parsing, extra latency, more configuration risk, and the LB sees plaintext — it holds certificates and becomes part of your security (and PCI) scope.

2. Why does picking the "least loaded" backend globally perform badly with many load balancer nodes, and how does P2C fix it?

Each LB node's view of load is slightly stale, so all nodes pick the same apparently idle backend at once and overload it — herd behaviour. P2C picks two random backends and sends to the better one: randomness spreads decisions across nodes, while the comparison avoids clearly overloaded backends. Theory and practice show maximum load drops dramatically compared with one random choice.

3. Design readiness and liveness checks for a payment service that depends on PostgreSQL and a fraud service.

Liveness: process responds, event loop not stuck — no downstream checks, so the orchestrator restarts only truly broken processes. Readiness: config loaded, local connection pool initialised, not draining. Do not fail readiness just because PostgreSQL or fraud is down — every instance would fail together. Handle shared dependencies with timeouts, circuit breakers and graceful degradation (for example, queue for later or decline with a clear error), and alert on them separately.

4. Scenario: you scale a gRPC fraud-scoring service from 4 to 12 pods before a sale, but CPU stays high on the original 4. Why, and what do you change?

Clients hold long-lived HTTP/2 connections opened when there were 4 pods; an L4 balancer (or Kubernetes ClusterIP) balances connections, not requests, so new pods receive nothing until clients reconnect. Fix with L7 balancing (Envoy or a mesh) or gRPC client-side balancing with service discovery, plus server-side MaxConnectionAge so connections recycle and rebalance.

5. How do you make the load-balancing tier itself highly available on-premises and in the cloud?

On-premises: an active-passive pair with VRRP and a floating VIP, or active-active L4 nodes behind routers using ECMP and BGP, with consistent hashing to L7 proxies. In the cloud: a managed LB spanning multiple AZs, with targets in every AZ. In both cases test failover, and consider a second region with GSLB for regional failure.

6. When are sticky sessions justified, and what do you lose?

When an instance holds state that cannot be externalised yet: legacy stateful apps, WebSocket servers holding connections, or in-process caches where locality matters. You lose even load distribution, resilience (sessions die with the instance), effective scale-out for existing users, and fast draining.

7. Why is DNS-based failover slower than its TTL suggests?

Resolvers and clients cache records, some ignore or clamp low TTLs, applications and JVMs may cache DNS indefinitely, and existing connections stay open to the old IP. Most traffic moves within a few TTLs, but a long tail lingers, so the failed site must keep rejecting or redirecting for a while.

🧠 Flashcards0/9 learned · 0 retries

Exercise​

  1. Run three instances of a small Go HTTP service locally; make one of them slow (add a random 200–800 ms sleep).
  2. Put them behind HAProxy or Envoy and load-test with vegeta or hey under round robin, least connections, and (Envoy) least request. Record p50/p99 latency for each.
  3. Implement the P2C picker above as a client-side balancer in a Go load generator and compare.
  4. Add an active health check and outlier detection; kill one instance mid-test and measure how many requests fail before it is ejected.

Done looks like: a short table of algorithm vs p99 latency and error count, and a two-sentence explanation of why the results differ.

Further reading​

  • Michael Mitzenmacher, "The Power of Two Choices in Randomized Load Balancing" (PhD thesis / IEEE TPDS 2001).
  • Eisenbud et al., "Maglev: A Fast and Reliable Software Network Load Balancer" (NSDI 2016).
  • Site Reliability Engineering (Google), chapters "Load Balancing at the Frontend" and "Load Balancing in the Datacenter".
  • Envoy proxy documentation: load balancing, outlier detection, health checking (envoyproxy.io).
  • HAProxy and NGINX official documentation on upstream balancing and health checks.
Finished this page?

Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).