Pidoku

Archive

This learning material is in the archive. It is not currently maintained and has not been updated with the latest information, so tool versions, prices and dates may be out of date.

Load Balancing

Module 7 Lesson 7.b 45 min Difficulty 3/5

Prerequisites 7.a, 3.a

The idea in one minute#

A load balancer spreads requests across healthy backends. Layer 4 (TCP/UDP) balancers move connections without looking inside them; layer 7 (HTTP/gRPC) balancers see each request, so they can route by path or header, retry, and balance per request rather than per connection.

The algorithm matters more than people expect. Round robin and random ignore how busy a backend is, so a slow or overloaded backend keeps getting its full share. Least requests sends to the least busy one, but needs fresh information. Power of two choices — pick two backends at random, send to the less busy — gets most of the benefit of least-requests with little coordination, and is the default in Envoy.

An analogy#

Supermarket checkouts. Assigning shoppers to tills in strict rotation (round robin) ignores that one till has a trainee and a queue of ten. Joining the shortest queue is better. Glancing at just two queues and picking the shorter is almost as good, and much faster than surveying every till.

A picture#

flowchart LR
  U[":i-users: Clients"] --> DNS[":i-globe: DNS / anycast<br/><small>global: which region</small>"]
  DNS --> L4[":i-network: <b>L4 load balancer</b><br/><small>connections, very fast</small>"]
  L4 --> L7[":envoyproxy: <b>L7 proxy</b><br/><small>per request: route, retry, P2C</small>"]
  L7 --> B1[":go: backend 1"]
  L7 --> B2[":go: backend 2<br/><small>slow today</small>"]
  L7 --> B3[":go: backend 3"]
  class U neutral
  class DNS,L4 io
  class L7 queue
  class B1,B3 compute
  class B2 warn

How it really works#

Layers of load balancing#

LayerExamplesDecidesNotes
Global (DNS, anycast)Route 53, Cloud DNS, Cloudflare, NS1Which region or PoPDNS TTLs and client caching make it slow to change
L4AWS NLB, Google Network LB, Maglev, IPVS, MetalLBWhich backend for a connectionConsistent hashing keeps connections sticky
L7Envoy, NGINX, HAProxy, AWS ALB, Kubernetes Gateway API implementationsWhich backend for each requestCan retry, rate limit, route by header
Client-sidegRPC client load balancing, service-mesh sidecarsClient picks a backend itselfNo extra hop; every client needs the endpoint list

Long-lived connections (HTTP/2, gRPC) defeat L4 balancing: one connection carries thousands of requests to one backend. Use L7 balancing or client-side balancing for gRPC, and set a maximum connection age so connections rebalance over time.

Algorithms#

AlgorithmHowWeakness
Round robinNext backend in turnIgnores load; a slow backend gets the same share
Weighted round robinIn turn, by weightWeights go stale
RandomUniform randomSame as round robin, plus random clumping
Least connections / requestsBackend with fewest in flightNeeds accurate counts; herd effect when many balancers see the same “least” backend
Power of two choices (P2C)Pick 2 at random, send to the less loadedSmall overhead; works with slightly stale data
Consistent hashing (ring, Maglev)Hash a key (user ID) to a backendUneven load for hot keys; needed for cache affinity
Latency-aware (EWMA)Prefer backends with low recent latencyCan oscillate; P2C + EWMA is a good combination

Why does P2C work? With purely random choice, the most loaded of N backends has about log N / log log N times the average queue; with the best of two random choices it drops to about log log N — an exponential improvement from looking at one extra backend.

The slow-backend problem#

The most common load-balancing incident: one backend becomes slow (noisy neighbour, bad disk, GC trouble) but still passes health checks. Round robin keeps sending it a full share, so its queue grows and a slice of all requests becomes very slow — the p99 for the whole service degrades. Least-requests and P2C route around it automatically, because its in-flight count rises. Outlier detection (6.c) removes it entirely.

Other load balancer duties#

  • Connection draining on deregistration (6.f).
  • Slow start for new backends.
  • Zone-aware routing: prefer backends in the same zone to cut latency and cross-zone cost, but spill to other zones when local capacity is short.
  • Panic threshold: if too many backends are unhealthy, ignore health (7.a).

A worked example#

A service has 10 backends; one has a disk problem and serves requests in 400 ms instead of 40 ms.

  • Round robin: the slow backend still receives a tenth of the traffic — 60 requests per second when it can serve 10. Its queue fills, and about 8% of all requests time out at 2 s, while the fleet as a whole is only two-thirds busy.
  • Least requests / P2C: the slow backend’s in-flight count climbs, so it loses most comparisons and ends up with under 2% of the traffic — about what it can actually do. No timeouts; p99 around half a second.

The program simulates this with 10 backends and four algorithms.

Code#

Go
// lb.go — round robin, random, least-requests and power-of-two-choices with one slow backend.
package main

import (
	"fmt"
	"math/rand"
	"sort"
)

const timeoutMs = 2000 // clients give up after 2 s

type backend struct {
	serviceMs   float64
	slots       [4]float64 // when each of the 4 workers is next free
	outstanding []float64  // completion times of accepted requests
}

func (b *backend) inFlight(now float64) int {
	kept := b.outstanding[:0]
	for _, t := range b.outstanding {
		if t > now {
			kept = append(kept, t)
		}
	}
	b.outstanding = kept
	return len(kept)
}

// submit returns the request's latency (queueing + service), or -1 if it would time out.
func (b *backend) submit(now float64) float64 {
	i := 0
	for j := range b.slots {
		if b.slots[j] < b.slots[i] {
			i = j
		}
	}
	start := now
	if b.slots[i] > now {
		start = b.slots[i]
	}
	if start-now+b.serviceMs > timeoutMs {
		return -1
	}
	done := start + b.serviceMs
	b.slots[i] = done
	b.outstanding = append(b.outstanding, done)
	return done - now
}

func run(name string, pick func(r *rand.Rand, bs []*backend, now float64, rr *int) int) {
	r := rand.New(rand.NewSource(1))
	bs := make([]*backend, 10)
	for i := range bs {
		bs[i] = &backend{serviceMs: 40}
	}
	bs[3].serviceMs = 400 // the slow one: 10 req/s instead of 100
	var lat []float64
	share := make([]int, len(bs))
	timeouts := 0
	rr := 0
	now := 0.0
	const n = 200_000
	for i := 0; i < n; i++ {
		now += r.ExpFloat64() * 1000 / 600 // 600 requests per second, Poisson arrivals
		k := pick(r, bs, now, &rr)
		share[k]++
		if l := bs[k].submit(now); l < 0 {
			timeouts++
		} else {
			lat = append(lat, l)
		}
	}
	sort.Float64s(lat)
	q := func(p float64) float64 { return lat[int(p*float64(len(lat)-1))] }
	fmt.Printf("%-22s p50 %4.0f ms  p99 %5.0f ms  p99.9 %5.0f ms  timeouts %5.2f%%  slow backend share %4.1f%%\n",
		name, q(0.5), q(0.99), q(0.999), 100*float64(timeouts)/n, 100*float64(share[3])/n)
}

func main() {
	fmt.Println("10 backends × 4 workers, 40 ms per request; backend 3 takes 400 ms; 600 req/s (66% of capacity)")
	run("round robin", func(_ *rand.Rand, bs []*backend, _ float64, rr *int) int {
		*rr = (*rr + 1) % len(bs)
		return *rr
	})
	run("random", func(r *rand.Rand, bs []*backend, _ float64, _ *int) int { return r.Intn(len(bs)) })
	run("least requests (all)", func(_ *rand.Rand, bs []*backend, now float64, _ *int) int {
		best := 0
		for i := range bs {
			if bs[i].inFlight(now) < bs[best].inFlight(now) {
				best = i
			}
		}
		return best
	})
	run("power of two choices", func(r *rand.Rand, bs []*backend, now float64, _ *int) int {
		a, b := r.Intn(len(bs)), r.Intn(len(bs))
		if bs[b].inFlight(now) < bs[a].inFlight(now) {
			return b
		}
		return a
	})
}

Remember this#

  • L4 balances connections, L7 balances requests; HTTP/2 and gRPC need L7 or client-side balancing.
  • Round robin and random ignore load; a slow backend drags the tail.
  • Least-requests is good with fresh data; power of two choices is nearly as good and robust.
  • Combine with outlier detection, slow start, draining, zone-aware routing and a panic threshold.

Try it#

  1. Run lb.go. Make two backends slow. How do the algorithms compare now?
  2. Raise the load to 850 requests per second. Which algorithm breaks first, and why?
  3. Find out which algorithm your load balancer or mesh uses by default.

Check yourself#

  1. Why does round robin hurt the p99 when one backend is slow but healthy?
  2. Why do long-lived gRPC connections defeat L4 load balancing?
  3. What problem does P2C have less of than “least requests across all backends” with many balancers?
  4. When do you need consistent hashing?

Sources#

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in