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#
| Layer | Examples | Decides | Notes |
|---|---|---|---|
| Global (DNS, anycast) | Route 53, Cloud DNS, Cloudflare, NS1 | Which region or PoP | DNS TTLs and client caching make it slow to change |
| L4 | AWS NLB, Google Network LB, Maglev, IPVS, MetalLB | Which backend for a connection | Consistent hashing keeps connections sticky |
| L7 | Envoy, NGINX, HAProxy, AWS ALB, Kubernetes Gateway API implementations | Which backend for each request | Can retry, rate limit, route by header |
| Client-side | gRPC client load balancing, service-mesh sidecars | Client picks a backend itself | No 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#
| Algorithm | How | Weakness |
|---|---|---|
| Round robin | Next backend in turn | Ignores load; a slow backend gets the same share |
| Weighted round robin | In turn, by weight | Weights go stale |
| Random | Uniform random | Same as round robin, plus random clumping |
| Least connections / requests | Backend with fewest in flight | Needs 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 loaded | Small overhead; works with slightly stale data |
| Consistent hashing (ring, Maglev) | Hash a key (user ID) to a backend | Uneven load for hot keys; needed for cache affinity |
| Latency-aware (EWMA) | Prefer backends with low recent latency | Can 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#
// 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#
- Run
lb.go. Make two backends slow. How do the algorithms compare now? - Raise the load to 850 requests per second. Which algorithm breaks first, and why?
- Find out which algorithm your load balancer or mesh uses by default.
Check yourself#
- Why does round robin hurt the p99 when one backend is slow but healthy?
- Why do long-lived gRPC connections defeat L4 load balancing?
- What problem does P2C have less of than “least requests across all backends” with many balancers?
- When do you need consistent hashing?