Skip to content

Load Balancing: Algorithms, L4 vs L7, DNS & Global, Health Checks, Affinity, TLS Termination ​

"Load balancing across multiple application instances is a commonly used technique for optimizing resource utilization, maximizing throughput, reducing latency, and ensuring fault-tolerant configurations." — NGINX documentation, Using nginx as HTTP load balancer

Summary: A load balancer decides, for every new connection or request, which of several equivalent servers should handle it, and keeps sick or departing servers out of that decision. The interesting part is never "spread the traffic"; it is which unit you balance (DNS answers, flows, requests), what the balancer knows about each server (nothing, connection counts, latency, health), what happens when a server dies mid-request, and how the balancer itself avoids being the single point of failure. Focus: Algorithms (round robin, weighted round robin, least connections, least response time, random, power of two choices, IP hash, URL hash, consistent hashing with ring hash and Maglev), L4 (NAT, DSR, IPVS, AWS NLB, HAProxy mode tcp) vs L7 (AWS ALB, NGINX, HAProxy mode http, Envoy, Traefik), DNS and global load balancing (GSLB, GeoDNS, latency routing, anycast), active and passive health checks, outlier detection, hysteresis, deep vs shallow checks, connection draining and deregistration delay, slow start, session affinity, TLS termination vs passthrough vs re-encryption, load balancer high availability (VRRP/keepalived, ECMP, anycast), timeouts and limits (502 vs 503 vs 504), retries and idempotency, client-side load balancing, hot backends, per-backend observability, Kubernetes Service, Ingress and Gateway API, with a Go load balancer and a Laravel 13 application behind it. Learning goal: Given a service and its traffic, pick the balancing tier and algorithm and justify it in one sentence, configure health checks that remove a dead server in seconds without flapping, deploy without a single 502, explain why a request got 502, 503 or 504, and decide whether session affinity is needed or should be designed away.

This chapter is in the Traffic & Scale group of system design and owns load balancing as a system-level decision: the algorithm, the tier, the knobs and the numbers. Mechanics around it live in siblings, linked rather than re-taught: the proxy itself (forwarding headers, trusted proxies, PROXY protocol, buffering) is in Forward vs Reverse Proxies; authoritative DNS, GeoDNS and anycast as DNS design are in IP, DNS & GeoDNS; the internals of the hash ring (virtual nodes, jump hash, rendezvous hashing) are in Consistent Hashing; sessions and cookies are in Web Sessions, Cookies & CORS; client-side discovery is in Service Discovery; sidecars are in Service Mesh & Sidecar; mTLS is in Mutual TLS; kube-proxy and CNI are in Kubernetes Networking; retry math is in Timeouts, Retries & Jitter; horizontal scaling is in Scaling Strategies. Persian version: /fa/system-design/load-balancing.

Page map ​

If you are looking forGo to
The whole page in four tablesEverything in one minute
Why a balancer exists and the trade it makesWhy it exists
Karger, Mitzenmacher, ECMP, VRRP, Maglev historyWhere it comes from
Pool, upstream, target group vocabularyBackend pool
Round robin and weightsRound robin
Least connections, least outstanding requestsLeast connections
Least response time, least_timeLeast response time
Random and power of two choicesP2C
IP hash, URL hash, ring hash, MaglevHash-based balancing
NAT, DSR, IPVS, NLBL4 load balancing
Host and path routing, ALB, EnvoyL7 load balancing
GSLB, GeoDNS, latency routing, anycastDNS and global
Probes, intervals, thresholdsActive health checks
Outlier detection, ejectionPassive health checks
Deep vs shallow, panic threshold, fail openWhat a health check should test
Deploys without errorsDraining
New servers that fall overSlow start
Sticky sessionsSession affinity
Who holds the certificateTLS at the balancer
The balancer as a single point of failureHigh availability
502 vs 503 vs 504, queues, idle timeoutTimeouts and limits
Safe retriesRetries and idempotency
gRPC, mesh, subsettingClient-side load balancing
One server much hotter than the othersHot backends
What to graph per backendObservability
Service, Ingress, Gateway APIKubernetes
NGINX, HAProxy, Envoy, Traefik, ALB, NLB, CloudflareProducts
Knobs, defaults, status codes, log linesMechanics
CodeGo, Laravel
Production failures and their fixesSolving the classic problems
Which balancer for which jobChoosing
Monolith to distributed systemIn architecture
Something to runLab
Wrong beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

Algorithms. What the balancer knows decides what it can do.

AlgorithmIn plain wordsWins whenWhere you find it
Round robinNext server in turnRequests cost about the same, servers are equalDefault in NGINX, HAProxy roundrobin, AWS ALB, Envoy ROUND_ROBIN
Weighted round robinIn turn, but bigger servers get more turnsMixed instance sizes, canary at 5%NGINX weight=, HAProxy weight, IPVS wrr, Gateway API backendRefs.weight
Least connectionsServer with the fewest open connections or requestsRequest cost varies; long sessionsNGINX least_conn, HAProxy leastconn, ALB least_outstanding_requests, IPVS lc/wlc
Least response timeFastest recent server with few active requestsHeterogeneous latency, one slow zoneNGINX least_time (open source since 1.31.0), Traefik leasttime
RandomAny server, uniformlyMany balancers, no health checks, no shared stateEnvoy RANDOM, NGINX random, ALB weighted_random
Power of two choices (P2C)Pick two at random, keep the less busy oneMany independent balancers; avoid herdingEnvoy LEAST_REQUEST, HAProxy random(2), NGINX random two least_conn, Traefik p2c
IP hash / source hashSame client IP, same serverL4 stickiness without cookiesNGINX ip_hash, HAProxy balance source, IPVS sh, Kubernetes sessionAffinity: ClientIP
URL hashSame URL, same serverCache tiers: maximise hit ratioHAProxy balance uri, NGINX hash $request_uri consistent
Consistent hashing (ring hash)Keys and servers on a circle; key goes clockwiseCaches, shards, sticky keys that must survive resizesEnvoy RING_HASH, NGINX hash ... consistent (ketama), HAProxy hash-type consistent
MaglevConsistent hashing with a fixed lookup tableVery fast L4 balancing with minimal disruptionGoogle Maglev, Envoy MAGLEV, IPVS mh

Layers. The layer decides the unit being balanced.

TierBalancesSeesTypical products
DNS / GSLBAnswers to name lookups (minutes, TTL bound)Resolver address, EDNS client subnet, region healthAWS Route 53, Cloudflare Load Balancing, NS1, GeoDNS
Anycast + ECMPPackets to the nearest site, flows to equal pathsIP routes, 5-tuple hashCloudflare, Google front ends, routers with BGP
L4TCP/UDP flows for their whole lifeIPs, ports, sometimes TLS SNIAWS NLB, Maglev, IPVS with keepalived, HAProxy mode tcp, NGINX stream
L7Individual HTTP/gRPC requestsMethod, host, path, headers, cookies, status codesAWS ALB, NGINX, HAProxy mode http, Envoy, Traefik, GCP external Application LB
Client-sideRequests from inside the callerFull per-backend latency and errorsgRPC round_robin, Envoy sidecars in Istio, Finagle-style libraries

Health, drain and warm-up knobs (defaults from each product's documentation).

ConcernAWS ALBHAProxyEnvoyNGINX
Probe interval30 s (HealthCheckIntervalSeconds, instance/ip targets)2 s (inter)interval (required)5 s (health_check, NGINX Plus)
Down after2 failures (UnhealthyThresholdCount)3 (fall)unhealthy_threshold1 (fails)
Up after5 successes (HealthyThresholdCount)2 (rise)healthy_threshold1 (passes)
Passive ejectionAutomatic Target Weights anomaly mitigation (weighted random)observe layer7, on-erroroutlier_detection: 5 consecutive 5xx, 30 s base ejection, at most 10%max_fails=1 fail_timeout=10s
DrainingDeregistration delay 300 sset server ... state drainDrain via EDS health statusdrain (open source since 1.29.6)
Slow startslow_start.duration_seconds (round robin only)slowstartslow_start_configslow_start= (NGINX Plus)

Who says what when it fails.

StatusProduced byMeansFirst check
502 Bad GatewayThe balancerConnection refused or reset, malformed response, backend closed a kept-alive connection, TLS handshake to the target failedBackend crash or restart, keepalive timeout of the app shorter than the balancer's
503 Service UnavailableThe balancer (or the app shedding)No healthy or registered backend, queue full or queue timeoutHealth check path, empty target group, HAProxy timeout queue
504 Gateway TimeoutThe balancerBackend did not answer within the balancer's timerSlow query, read timeout vs real work time, ALB idle timeout
499 (NGINX log only)Client sideClient gave up before the responseClient timeout shorter than the backend's work

Why it exists ​

One server has a ceiling (CPU, memory, connections, one kernel to patch) and is one failure away from an outage. More servers fix both problems only if something in front of them answers three questions on every connection or request: which server, is it alive, and what to do if it dies now. That something is a load balancer. It can be a DNS server handing out different addresses, a router hashing flows, a proxy reading HTTP, or a library inside the caller.

Simple: one server, or DNS round robin onlyLoad-balanced pool
Capacity of one machineCapacity grows by adding servers, if the app is stateless
A crash is an outageA crash removes one server; the balancer routes around it
A deploy is downtime or a risky restartDrain one server at a time, health-check, re-add
No per-request choiceChoice by load, latency, key, path, header
Nothing new to runA new tier with its own HA, config, certificates, timers and failure modes
Client sees the real serverClient sees a virtual IP or name; the server sees the balancer unless headers or PROXY protocol carry the client

An everyday picture. A supermarket with many checkout lanes. Round robin is a staff member sending each shopper to the next lane in turn, ignoring that lane 3 has a customer with two full trolleys. Least connections is sending the shopper to the shortest queue, which works if the staff member can see every queue. Power of two choices is telling each shopper "look at two random lanes and join the shorter one": nobody needs to see the whole store, and nobody piles into the one lane that looked empty a second ago. A closed lane with its light off is a failed health check; a cashier who says "last customer, please" is draining; a new cashier who is given only a few customers for the first ten minutes is slow start. Mitzenmacher's paper even calls its model "the supermarket model".

One request through the load-balancing tiersClient198.51.100.7GSLB / GeoDNSRoute 53, CloudflareAnycast edgeone IP, many sites1 resolve2 connectL4 tierNLB, Maglev, IPVSECMP spreads flows;5-tuple hash, no HTTPL7 tierEnvoy, NGINX, ALB3 flowTLS ends, route byhost/path, retriesapp-1 healthyapp-2 drainingapp-3 ejectedbackend pool / target groupEach tier balances a different unit: DNS answers (minutes, TTL), flows (connection lifetime), requests (milliseconds).Health travels back up: app checks feed L7, L7 health feeds L4, regional health feeds GSLB.

Three common misunderstandings, up front ​

  1. "The load balancer makes my service highly available." It makes the pool highly available. The balancer is now a component that must itself be redundant (two nodes with VRRP, an anycast fleet, or a managed service spread across zones), and a bad health check on it can take the whole pool out at once.
  2. "Least connections is always better than round robin." Least connections needs an accurate, current view of load. With many independent balancers each seeing only its own connections, or with HTTP/2 multiplexing many requests over one connection, it herds traffic onto whichever server looked idle. Power of two choices was designed for exactly this.
  3. "Sticky sessions are how you scale stateful apps." Stickiness pins users to servers, so a deploy, a crash or a scale-in logs those users out or loses their carts, and a hot user makes a hot server. Move state to a shared store and keep affinity only for what genuinely needs locality (caches, WebSocket rooms, shards).

Where it comes from ​

DateMilestoneSource
1997Consistent hashing proposed by Karger et al.: a mapping that "remains relatively stable even when new backends are added to or removed from the list"Google SRE Book, ch. 19 (cites Kar97)
November 2000RFC 2992 analyses ECMP next-hop selection; "hash-threshold" maps a flow hash to N regions of the key spaceRFC 2992
October 2001Mitzenmacher, The Power of Two Choices in Randomized Load Balancing: two choices give exponential improvement over one; three are only a constant factor betterIEEE TPDS 12(10)
March 2010RFC 5798, VRRP version 3 for IPv4 and IPv6, "designed to eliminate the single point of failure" of a static default routerRFC 5798
2016Google publishes Maglev (NSDI '16): ECMP to a fleet of software L4 balancers, consistent hashing plus connection tracking, DSR for responsesEisenbud et al., NSDI 2016
2016The SRE Book documents Google's DNS + VIP front-end balancing, lame duck state, deterministic subsetting and weighted round robinGoogle SRE Book, ch. 19 and 20
Kubernetes v1.35kube-proxy ipvs mode deprecated; nftables mode recommended; the Ingress API frozen, Gateway API recommendedKubernetes docs
NGINX 1.29.6 / 1.31.0sticky and drain move from NGINX Plus into open source (1.29.6); least_time follows (1.31.0)NGINX upstream module docs

The concept catalogue ​

Backend pool, upstream and target group Must-know ​

In plain words: The pool is the list of interchangeable servers behind one name. Every product has its own word for it, and the same few properties for each member: address, weight, state.

Common misunderstanding: "Members of a pool are just IP addresses." A member is an address plus a state machine (initial, healthy, unhealthy, draining, ejected, in slow start) plus counters (active requests, recent failures, latency). Most production incidents are about that state, not the address.

Definition: A backend pool (NGINX upstream, HAProxy backend, Envoy cluster, AWS target group, Kubernetes Service endpoints / EndpointSlices, Traefik service) is a named set of endpoints with a balancing policy, health-check policy and per-member weight. Membership comes from static config, DNS (NGINX resolve, Envoy STRICT_DNS), an API (AWS registration, Envoy EDS/xDS) or a platform (Kubernetes endpoints).

 1  register   10.0.1.13:8000 -> state: initial (ALB) / unchecked (HAProxy)
 2  probe x2   GET /up 200, 200      -> healthy; slow start window opens
 3  traffic    weight ramps 10% -> 100% over 30 s
 4  deploy     deregister -> draining: no new requests, in-flight finish
 5  drained    active = 0 (or deregistration delay elapsed) -> unused, removed

Real scenario: an ALB target group per microservice with an Auto Scaling group registering instances; an NGINX upstream with three Octane servers and one backup; an Envoy cluster fed by EDS from Istio; a Kubernetes Service whose endpoints change every time a Pod becomes Ready.

ProductPoolMemberMembership source
NGINXupstream blockserverStatic, resolve (DNS, open source since 1.27.3)
HAProxybackendserverStatic, server-template + DNS, Runtime API
Envoyclusterendpoint / hostStatic, DNS, EDS (xDS)
AWS ELBtarget grouptarget (instance, IP, Lambda, ALB)Registration API, Auto Scaling, ECS/EKS controllers
KubernetesServiceEndpointSlice endpointPod readiness
Traefikservice with loadBalancer.serversserverProviders (Docker, Kubernetes, file)

Fix / how to use it: name pools after the service, keep members interchangeable (same build, same config), and make membership dynamic so a deploy is a registration change, not a config edit. The Go lbproxy.Pool keeps the state per member in balancer.Backend.

Round robin and weighted round robin Must-know ​

In plain words: Hand requests to servers in turn. With weights, a server of weight 3 gets three turns for every one of a weight-1 server.

Common misunderstanding: "Round robin gives every server the same load." It gives every server the same number of requests. If requests differ in cost (a report vs a health check) or servers differ in speed, load is uneven. NGINX's documentation is careful to say equal distribution happens "provided there are enough requests, and when the requests are processed in a uniform manner and completed fast enough".

Definition: Plain round robin cycles an index. Weighted round robin repeats servers in proportion to weight; the smooth variant used by NGINX interleaves them: each pick adds every server's weight to its running score, takes the highest score, and subtracts the total weight from the winner. Weights 5, 1, 1 then give a a b a c a a rather than five a in a row (the NGINX upstream docs give this 5:1:1 example over 7 requests). HAProxy's roundrobin is dynamic (weights can change at runtime, which slow start uses) and is "limited by design to 4095 active servers per backend"; static-rr has no such limit but ignores runtime weight changes.

 smooth weighted round robin, weights a=5 b=1 c=1, total 7
 1  scores +w: a=5  b=1  c=1   -> pick a; a=5-7=-2
 2  scores +w: a=3  b=2  c=2   -> pick a; a=-4
 3  scores +w: a=1  b=3  c=3   -> pick b; b=-4
 4  scores +w: a=6  b=-3 c=4   -> pick a; a=-1
 5  scores +w: a=4  b=-2 c=5   -> pick c; c=-2
 6  scores +w: a=9  b=-1 c=-1  -> pick a; a=2
 7  scores +w: a=7  b=0  c=0   -> pick a; a=0  (back to start)

Real scenario: a fleet of identical stateless API pods; mixing m7i.xlarge and m7i.2xlarge instances with weights 1 and 2; a canary taking 5% through Gateway API backendRefs weights 95/5; Google's SRE Book describes Simple Round Robin with "For many years, this was our most common approach".

ProductPlainWeightedNotes
NGINXdefaultserver ... weight=NSmooth WRR; default weight 1
HAProxybalance roundrobinweight 0..256static-rr for unlimited servers
EnvoyROUND_ROBINendpoint load_balancing_weightLocality-weighted variants
AWS ALBround_robin (default)Weighted target groups on the listener rulePer-target weights via ATW only
IPVSrrwrrPer connection, not per request
Kubernetes Gateway API—backendRefs[].weightSplit between Services

Fix / how to use it: default to round robin for homogeneous, short, uniform requests; use weights for capacity differences and traffic splitting; switch to least outstanding requests or P2C as soon as request cost varies. Code: balancer.RoundRobin (smooth, with slow start).

Least connections and least outstanding requests Must-know ​

In plain words: Send the next request to the server that is currently doing the least work, measured by open connections (L4) or in-flight requests (L7).

Common misunderstanding: "Least connections measures load." It measures concurrency as seen by this balancer. Ten balancers each see a tenth of the connections; HTTP/2 puts many requests on one connection; a server that fails fast has few connections and attracts more traffic. The SRE Book calls the last case "sinkholing traffic" and fixes it by counting recent errors as active requests.

Definition: Choose argmin(active_i / weight_i); break ties by round robin (NGINX and HAProxy both do). HAProxy recommends leastconn "where very long sessions are expected, such as LDAP, SQL, TSE" and notes it "is not very well suited for protocols using short sessions such as HTTP"; it also counts queued connections. AWS ALB's least_outstanding_requests counts in-progress requests per target, and its documentation notes that for HTTP/2 to HTTP/1.1 targets each HTTP/2 request may count as several. IPVS has lc and wlc (connections divided by weight), plus sed (shortest expected delay, (C + 1) / U) and nq (never queue).

 1  active: app1=12 app2=3 app3=7 (all weight 1)
 2  new request -> app2 (3 is lowest); app2=4
 3  app2 returns 500 in 1 ms for everything (broken dependency)
 4  app2 always has ~0 active -> least-conn sends it MORE traffic: sinkhole
 5  fix: count recent errors as active, or eject via outlier detection

Real scenario: report endpoints taking 2 to 30 s mixed with 20 ms reads; WebSocket servers where each connection lives for hours (ALB picks the WebSocket target with least outstanding requests, then keeps the connection); database read pools behind HAProxy mode tcp with leastconn.

ProductDirectiveCountsCaveat
NGINXleast_connActive connections per worker group (shared with zone)Without zone each worker counts alone
HAProxybalance leastconnEstablished + queued connectionsDynamic weights, slow start works
AWS ALBleast_outstanding_requestsIn-progress requestsNot combinable with slow start
EnvoyLEAST_REQUESTActive requests; P2C when weights are equalSee P2C
IPVSlc, wlc, sed, nqConnections in the kernel tablePer node, not cluster-wide

Fix / how to use it: prefer least outstanding requests over least connections for HTTP; add outlier detection so a fast-failing server cannot sinkhole; with many balancers prefer P2C. Code: balancer.LeastConn (weighted, rotating tie-break).

Least response time Important ​

In plain words: Prefer the server that has recently answered fastest, adjusted for how many requests it already has in flight.

Common misunderstanding: "Fastest server wins, so this is always optimal." Latency is a lagging signal: the fast server attracts traffic, slows down, the next one becomes "fastest", and the pool oscillates. And as the SRE Book points out, a server that is twice as capable may show the same latency (requests spend most of their time waiting on the network) yet should get twice the traffic.

Definition: NGINX least_time header | last_byte [inflight] "selects the server with the lowest average response time and the lowest number of active connections"; header uses time to first byte, last_byte the full response, inflight includes incomplete requests. It was NGINX Plus only before 1.31.0. Traefik's leasttime strategy combines response time with active connections. IPVS sed approximates it with (C + 1) / U. Envoy's client-side weighted round robin goes further: weights from ORCA load reports, computed as qps / (utilization + eps/qps * error_utilization_penalty).

 1  t=0   EWMA latency: app1=40 ms app2=80 ms app3=45 ms
 2  t=0+  least_time sends most new requests to app1
 3  t=5s  app1 queueing: 120 ms; app3 now fastest, takes the flood
 4  t=10s app3 120 ms ... oscillation unless inflight is counted and decay is slow

Real scenario: a pool spread over two availability zones where one zone has a slower database replica; mixed-generation hardware; a backend that garbage-collects every few seconds.

ProductMechanismAvailability
NGINXleast_time header / last_byte / inflightOpen source since 1.31.0, NGINX Plus before
NGINXrandom two least_time=headerleast_time method of random is NGINX Plus
Traefikstrategy: leasttimeTraefik service load balancer
EnvoyClientSideWeightedRoundRobin with ORCAExtension policy
IPVSsed, nqKernel schedulers

Fix / how to use it: use it when servers differ in speed and you cannot express that as static weights; always include in-flight requests; prefer server-reported utilization (ORCA) over measured latency when available.

Random and power of two random choices (P2C) Must-know ​

In plain words: Pick two servers at random and send the request to the one with fewer requests in flight. That small amount of information removes almost all the imbalance of pure random choice.

Common misunderstanding: "Random is lazy; least connections is the serious algorithm." With N independent balancers each acting on its own (or slightly stale) view, least connections makes every balancer send the next burst to the same "least loaded" server. P2C cannot herd: the worst server is never chosen unless both draws are bad, and the decision needs only two counters.

Definition: Mitzenmacher (2001) studies a model where each customer picks d servers uniformly at random and joins the shortest queue: two choices "leads to exponential improvements in the expected time a customer spends in the system" compared with one, while three choices are "only a constant factor better" than two. Envoy's least-request balancer with equal weights "selects N random available hosts as specified in the configuration (2 by default) and picks the host which has the fewest active requests", noting P2C's "resistance to herding behavior". HAProxy's random(<draws>) defaults to 2: "picking the least loaded of two servers is enough to significantly improve the fairness". Pure random is still useful: Envoy says random "generally performs better than round robin if no health checking policy is configured", because it "avoids bias towards the host in the set that comes after a failed host".

 1  active: a=2 b=9 c=3 d=40 (d is hot: GC pause)
 2  req 1: draw (b, d) -> b (9 < 40)
 3  req 2: draw (a, c) -> a
 4  req 3: draw (d, c) -> c
 5  d is only chosen if drawn with itself: impossible, draws are distinct
 6  10 balancers doing this independently do not converge on one server
hash mod N: N changes, most keys moveConsistent hash ring: only the lost arc movesN=4ABCDABCDkeys k0..k7N=3ABCABCABred: 5 of 8 keys changed backendABCDACk5k1virtual nodesper backendD removed:keys on its arcgo clockwise to A;all other keys stayabout 1/N movesTests in balancer/: mod-N 10 to 9 backends moved 90.4% of keys; ring hash moved 9.4%; Maglev moved 0.19% between survivors.

Real scenario: a sidecar mesh where every Pod's Envoy balances independently (thousands of balancers); Traefik p2c across Docker containers; HAProxy with frequently added and removed servers, where the docs say random "may avoid the hammering effect that could result from roundrobin or leastconn".

ProductP2CPlain random
EnvoyLEAST_REQUEST with choice_count: 2 (default)RANDOM
HAProxybalance random(2) (2 is the default draw count)balance random(1)
NGINXrandom two least_connrandom
Traefikstrategy: p2c—
AWS ALB—weighted_random (with ATW anomaly mitigation)
gRPCLibrary-specific; round_robin and pick_first are built in—

Fix / how to use it: make P2C on in-flight requests your default for HTTP and gRPC at L7, especially with many balancers. Code: balancer.P2C; the test TestP2CAvoidsHotBackend shows a backend with 100 in-flight requests is never picked.

Hash-based balancing: IP hash, URL hash, ring hash, Maglev Must-know ​

In plain words: Compute a hash of something in the request (client IP, URL, a header, a cookie) and let the hash decide the server, so the same key always lands on the same server.

Common misunderstanding: "Any hash gives stickiness." hash(key) mod N does, until N changes; then almost every key moves. The SRE Book walks through exactly this: "Suddenly N becomes N-1 ... Almost every packet suddenly maps to a different backend!" The before test in this chapter measures 90.4% of keys moving from 10 to 9 servers. Consistent hashing fixes it.

Definition: IP hash keys on the client address (NGINX ip_hash uses the first three octets of an IPv4 address; HAProxy balance source). URL hash keys on the path (HAProxy balance uri, with len, depth, whole, path-only), and is "used with proxy caches and anti-virus proxies in order to maximize the cache hit rate". With hash-type map-based (HAProxy's default) or NGINX hash without consistent, "adding or removing a server from the group may result in remapping most of the keys". Consistent hashing places servers on a ring at many points (virtual nodes) and sends a key to the first point clockwise; Envoy: "the addition or removal of one host from a set of N hosts will affect only 1/N requests". NGINX hash $key consistent uses ketama "compatible with the Cache::Memcached::Fast Perl library with the ketama_points parameter set to 160". Maglev (NSDI 2016, section 3.4) instead fills a prime-sized lookup table (Envoy uses 65537) from per-backend permutations: lookup is one array index, build is fast, entries per backend are nearly equal; Envoy notes Maglev is about 10x faster to build and 5x faster to select than a 256K-entry ring but moves roughly double the keys on removal. Rendezvous hashing (highest random weight) is Traefik's hrw. Ring internals belong to Consistent Hashing.

 1  ring: a, b, c, d with 160 virtual nodes each
 2  key "user-42" -> hash 0x7a.. -> first point clockwise belongs to c
 3  d removed -> only keys whose first point was d move (to the next point)
 4  measured in balancer tests: ring hash moved 9.4% (1/10 expected)
 5  Maglev table 65537: slots per backend differ by at most 1; 0.19% of keys moved between survivors

Real scenario: a Varnish or NGINX cache tier where URL hashing turns ten 100 GB caches into one 1 TB cache instead of ten copies of the same 100 GB; WebSocket chat rooms where all members of a room should be on one server; Redis or Memcached client-side sharding; per-tenant routing by header; Google's front end falling back to consistent hashing "when the system is under pressure (e.g., during an ongoing denial of service attack)".

ProductMod-N hashConsistent hashBounded load
NGINXhash $key, ip_hashhash $key consistent (ketama)—
HAProxyhash-type map-based (default)hash-type consistenthash-balance-factor 150
Envoy—RING_HASH, MAGLEV + route hash_policy—
IPVSsh, dhmh (Maglev; kube-proxy sets mh-port)—
Traefik—hrw (rendezvous)—
AWS NLB5-tuple flow hash (per connection)——

Fix / how to use it: never use mod-N for anything whose remapping is expensive; use ring hash where stability matters most, Maglev where lookup speed matters most, and add a bounded-load factor (HAProxy hash-balance-factor) so one hot key cannot overload one server. Code: balancer.RingHash, balancer.Maglev, and before.Pick for the contrast.

L4 load balancing: NAT, DSR, tunnelling, IPVS, NLB Must-know ​

In plain words: An L4 balancer chooses a server per connection (or per UDP flow) by looking only at addresses and ports, then forwards packets without reading HTTP.

Common misunderstanding: "L4 balances requests." It balances connections. One client keeping one HTTP/2 or gRPC connection open for an hour sends all its requests to one server for an hour, no matter how busy that server is. That is why gRPC needs client-side or L7 balancing.

Definition: Forwarding modes (keepalived lb_kind NAT|DR|TUN names them): NAT rewrites the destination address to the server and the source back on the reply, so replies must return through the balancer; DR / DSR (direct routing, direct server return) changes only the destination MAC (layer 2), the server owns the VIP on a loopback and replies directly to the client, so only the small inbound side crosses the balancer (the SRE Book: "If user requests are small and replies are large ... DSR provides tremendous savings"); TUN encapsulates (IP-in-IP or GRE) so balancer and server need not share a broadcast domain (Google's front end uses GRE with "24 bytes in the case of IPv4+GRE" overhead, and Maglev uses DSR for responses). A full-proxy L4 (HAProxy mode tcp, NGINX stream, Envoy TCP proxy, AWS NLB with TLS listeners) terminates TCP and opens a second connection. AWS NLB picks the target with "a flow hash algorithm based on the protocol, source IP address, source port, destination IP address, destination port, and TCP sequence number"; "Each individual TCP connection is routed to a single target for the life of the connection".

 NAT                                   DSR (direct routing)
 1 client -> VIP:443                   1 client -> VIP:443
 2 LB: dst=10.0.1.11, keeps state      2 LB: dst MAC = server MAC, IP untouched
 3 server -> LB (reply)                3 server owns VIP on lo, replies src=VIP
 4 LB: src=VIP -> client               4 server -> client directly (LB bypassed)

Real scenario: AWS NLB with static Elastic IPs per zone in front of an NGINX fleet; keepalived + IPVS in DR mode in front of video servers where responses are 100x larger than requests; HAProxy mode tcp + leastconn in front of PostgreSQL replicas; Google Maglev in front of every Google service; NLB preserving the client IP (on by default for instance targets) or sending PROXY protocol v2.

ModeReturn pathBalancer stateClient IP at serverLimits
NATThrough the balancerConnection tableYes (source untouched)Balancer carries both directions
DR / DSRServer to clientOptionalYesSame L2 segment; VIP on every server; no TLS or HTTP features
TUN / GREServer to clientOptionalYesMTU overhead; server must decapsulate
Full proxy (two TCP connections)Through the balancerTwo sockets per flowNo, unless PROXY protocol or IP preservationMost features, most cost

Fix / how to use it: use L4 in front of non-HTTP protocols, for TLS passthrough, and as the first tier that spreads load over many L7 balancers; put per-request policy at L7. Kernel and kube-proxy details: Kubernetes Networking.

L7 load balancing Must-know ​

In plain words: An L7 balancer reads each HTTP (or gRPC) request and decides per request, so it can route /api and /images to different pools, retry a failed GET elsewhere, and balance the many requests that share one HTTP/2 connection.

Common misunderstanding: "L7 is only for routing by path." Its main balancing value is per-request granularity: least outstanding requests, outlier detection by status code, retries, cookie affinity, header-based canaries, all impossible at L4. Its cost is parsing, TLS termination and a larger attack surface; see L4 vs L7 in the proxies chapter.

Definition: An L7 balancer terminates the client's HTTP connection, chooses a route (host, path, method, header, query, cookie), then a backend from that route's pool, then a pooled upstream connection. One client connection fans out to many backends; many client connections share upstream keepalive connections.

 1  client -> ALB   HTTP/2, 40 streams on one TLS connection
 2  ALB             rule: Host shop.example, path /api/* -> target group api
 3  ALB             least_outstanding_requests per stream -> api-2, api-5, api-1 ...
 4  ALB -> targets  HTTP/1.1 keepalive (or HTTP/2, gRPC) connections reused
 5  api-5 returns 503 -> ALB returns it; NGINX/Envoy could retry if configured

Real scenario: AWS ALB listener rules splitting /api and /admin; NGINX in front of Laravel Octane doing TLS, static files and least_conn; Envoy as an edge proxy with per-route retry policy; Traefik discovering Docker containers by labels; Kubernetes Gateway API HTTPRoute splitting 90/10 between Services.

CapabilityAWS ALBNGINXHAProxy mode httpEnvoyTraefik
Host/path/header routingListener rulesserver_name, location, mapACLs, use_backendRoute tableRouters and rules
Per-request algorithmRR, LOR, weighted randomRR, least_conn, random two, least_time, hashAll balance algorithmsRR, least request, ring hash, Maglev, randomwrr, p2c, hrw, leasttime
RetriesNo configurable policyproxy_next_upstreamretries, option redispatch, retry-onRoute retry_policyretry middleware
Cookie affinityAWSALB duration-based or application-basedsticky cookie (open source 1.29.6+)cookie ... insertStateful session filter or hash on cookiesticky.cookie

Fix / how to use it: put HTTP and gRPC behind an L7 tier; keep the L7 tier itself stateless and horizontally scaled behind L4 or anycast; set routing and timeouts per route, not globally.

DNS and global load balancing: GSLB, GeoDNS, latency routing, anycast Important ​

In plain words: Before a client connects, DNS chooses which site's address it gets. Global server load balancing (GSLB) makes that choice using geography, measured latency and each region's health. Anycast does it in routing instead: many sites announce the same IP and the network delivers each packet to the nearest.

Common misunderstanding: "DNS failover is instant." Answers are cached by recursive resolvers for at least the TTL, and some resolvers ignore TTL (the SRE Book's footnote: "Sadly, not all DNS resolvers respect the TTL value"). And the authoritative server sees the resolver, not the user, unless EDNS Client Subnet is used. DNS balances slowly and coarsely; it chooses a region, never a server.

Definition: GeoDNS and latency-based routing answer per resolver (AWS Route 53 latency routing serves "requests from the AWS Region with the lowest latency", using latency data "based entirely on traffic between users and AWS data centers"). GSLB adds health checks per region and failover or weighted pools (Cloudflare Load Balancing: monitors, pools, global and local traffic steering). Anycast + BGP sends packets to the nearest announcing site; inside a site, routers use ECMP to spread flows over L4 balancers (Maglev: "Network routers distribute packets evenly to the Maglev machines via Equal Cost Multipath (ECMP)"). DNS design itself is in IP, DNS & GeoDNS.

 1  user (Frankfurt) -> resolver -> authoritative: shop.example?
 2  GSLB: eu-central-1 healthy, 18 ms; us-east-1 95 ms -> answer 203.0.113.10 (TTL 60)
 3  eu-central-1 health checks fail
 4  GSLB answers 203.0.113.20 (eu-west-1) to new queries
 5  users with cached answers keep hitting the dead region until TTL (or longer) -> keep an anycast/L4 layer able to fail over too

Real scenario: an active-active two-region API with Route 53 latency records and health checks; Cloudflare in front of origins in three clouds with pools and failover; a game backend using anycast UDP so players reach the nearest site.

TechniqueGranularityFailover speedKnows user locationProducts
DNS round robin (several A records)Per resolver, randomTTL plus resolver behaviourNoAny DNS
GeoDNSPer resolver regionTTLApproximate (resolver or ECS)Route 53 geolocation, NS1, Cloudflare
Latency-based routingPer resolver, measured latencyTTLVia resolverRoute 53 latency, Azure Traffic Manager
GSLB with healthPer region poolTTL plus probe intervalYes, with steeringCloudflare Load Balancing, F5 DNS
AnycastPer packet to nearest siteBGP convergence (seconds)Network topologyCloudflare, Google front end, Fastly

Fix / how to use it: use DNS/GSLB to pick a region, anycast or L4 to absorb site failures quickly, L7 to pick a server; keep TTLs short (30 to 60 s) for records you may need to move, and never rely on DNS alone for failover.

Active health checks Must-know ​

In plain words: The balancer asks each server "are you OK?" on a timer (an HTTP GET, a TCP connect, a gRPC health call) and takes it out of rotation after enough failures in a row.

Common misunderstanding: "A failed check removes the server immediately." Detection time is interval × unhealthy threshold plus the probe timeout: AWS ALB defaults are 30 s and 2 failures, so a dead instance target can receive traffic for about a minute. Removal is also per balancer node: every node of the fleet probes on its own.

Definition: An active health check has a target (path /up, port, expected status or body), an interval, a timeout, an unhealthy threshold (fall, UnhealthyThresholdCount, unhealthy_threshold, fails) and a healthy threshold (rise, HealthyThresholdCount, healthy_threshold, passes). HAProxy's fall "defaults to 3", rise "defaults to 2", inter "defaults to 2000 ms", and fastinter/downinter change the pace while a server is transitioning or down. ALB: interval 5 to 300 s (default 30 s for instance and IP targets), timeout 2 to 120 s (default 5 s), healthy threshold 2 to 10 (default 5), unhealthy 2 to 10 (default 2). NGINX Plus health_check defaults to 5 s with one failure and one pass; open source NGINX has passive checks only. Envoy's health_checks takes interval, timeout, healthy_threshold, unhealthy_threshold; without active checks "all upstream cluster members are considered healthy".

 1  t=0    app-2 crashes
 2  t=0..  ALB keeps sending: app-2 still "healthy"; requests get 502
 3  t=30s  probe 1 fails (timeout 5 s)
 4  t=60s  probe 2 fails -> UnhealthyThresholdCount 2 reached -> out of service
 5  with HAProxy inter 2s fall 3 the same takes about 6 s; passive checks cut it to the first errors

Real scenario: an ALB target group pointing at /up; HAProxy option httpchk with http-check expect status 200; Envoy gRPC health checks against grpc.health.v1.Health; keepalived HTTP_GET checks for IPVS real servers.

ProductProbeIntervalFall / riseTimeout
AWS ALBHTTP/HTTPS path, matcher codes30 s default (5..300)2 / 55 s
AWS NLBTCP, HTTP, HTTPSSee NLB target group docsConfigurableConfigurable
HAProxycheck, option httpchk, tcp-check, agent-check2 s (inter)3 / 2timeout check, else inter
EnvoyHTTP, gRPC, TCP, Redis, Thriftintervalunhealthy_threshold / healthy_thresholdtimeout
NGINX Plushealth_check uri= interval= fails= passes=5 s1 / 1—
keepalivedHTTP_GET, SSL_GET, TCP_CHECKdelay_loopRetries per checkerconnect_timeout

Fix / how to use it: probe a cheap endpoint every 2 to 10 s with fall 2 to 3 and rise 2 to 3; add passive checks so real traffic detects failure faster than probes. Code: lbproxy.Pool.CheckOnce, Run, and TestHealthCheckRiseAndFall.

Passive health checks and outlier detection Must-know ​

In plain words: Instead of (or as well as) probing, the balancer watches real traffic: a server that returns errors or refuses connections several times in a row is taken out for a while.

Common misunderstanding: "Passive checks replace active ones." A passive check only learns from traffic it sends; an ejected server gets no traffic and so cannot prove it recovered, which is why products bring it back on a timer (NGINX "will start to gracefully probe the server with the live client's requests" after fail_timeout) or on a successful active check (Envoy: "a successful active health check unejects the host").

Definition: NGINX max_fails=1 fail_timeout=10s (defaults): max_fails failures within fail_timeout mark the server unavailable for fail_timeout; what counts as a failure is set by proxy_next_upstream (error, timeout and invalid_header always count; http_500 etc. only if listed; 403 and 404 never). Envoy outlier detection is "a form of passive health checking": consecutive_5xx (default 5), consecutive_gateway_failure (502/503/504), success-rate and failure-percentage detectors, interval 10 s, base_ejection_time 30 s multiplied by the number of consecutive ejections up to max_ejection_time, and max_ejection_percent 10% so it never ejects most of the pool. HAProxy: observe layer4|layer7 with error-limit and on-error fastinter|fail-check|sudden-death|mark-down. AWS ALB: Automatic Target Weights anomaly detection (needs at least three healthy targets; mitigation with weighted_random).

 1  app-3 starts returning 503 (connection pool to DB exhausted)
 2  Envoy: 5 consecutive 5xx from app-3 -> eject for 30 s (1st ejection)
 3  t+30s  app-3 back in rotation; still failing -> 5 x 5xx -> eject 60 s (2nd)
 4  ejected hosts are capped at 10% of the cluster: a pool-wide failure is not "fixed" by ejecting everyone

Real scenario: one Pod on a noisy node timing out while its health endpoint still answers; a backend with a broken dependency failing fast (the sinkhole case); canary instances returning 500s that outlier detection removes before the human notices.

ProductKnobDefaultUnit
NGINXmax_fails / fail_timeout1 / 10 sFailures in window, window = ejection
HAProxyobserve layer7 + error-limit + on-errorerror-limit 10, on-error fail-checkConsecutive errors
Envoyconsecutive_5xx / base_ejection_time / max_ejection_percent5 / 30 s / 10%Consecutive errors, growing ejection
TraefikpassiveHealthCheckSee Traefik docsFailed requests
AWS ALBATW anomaly detectionAlways on; mitigation opt-inDeviation from other targets

Fix / how to use it: run both: active for "can it serve at all", passive for "is it serving real requests well"; cap ejection so a shared dependency outage does not eject the whole pool. Code: lbproxy.Pool.observe ejects after EjectAfter consecutive failures and never ejects the last eligible backend; tested in TestSafeRetryAndPassiveEjection.

What a health check should test: deep vs shallow, hysteresis, panic Must-know ​

In plain words: A shallow check asks "is this process up and able to answer?"; a deep check asks "can it reach its database, cache and dependencies?". Deep sounds better and is often worse, because when a shared dependency blips every server fails its check at the same moment and the balancer removes all of them.

Common misunderstanding: "The health check should verify everything the request needs." If the database is down, removing every app server does not help users: they get 503 from the balancer instead of a degraded page from the app. Products protect themselves from this: AWS ALB "fails open" ("if all targets fail health checks at the same time in all enabled Availability Zones"), Envoy has a panic threshold (default 50%: below it, balance across all hosts or none), NGINX ignores max_fails when a group has a single server.

Definition: Hysteresis means different thresholds for going down and coming back (fall 3, rise 2; ALB 2 down, 5 up), so one slow probe cannot flap a server in and out. Liveness (should it be restarted?) and readiness (should it get traffic?) are different checks; Laravel's /up is liveness ("will return a 200 HTTP response if the application has booted without exceptions"), and this chapter's /ready adds drain state and a cached, local dependency check.

Backend lifecycle as the load balancer sees itinitialregisteredhealthyslow start ramphealthyfull weightunhealthyactive checkejectedpassive / outlierdrainingno new requestsremovedunusedrise x2window endsfall x3rise x25 x 5xxtimerderegisterin-flight 0 or delayDefaultsALB: 30s,5 up / 2 downHAProxy: 2s,rise 2 fall 3Envoy outlier:5 x 5xx, 30sALB drain 300sHysteresis: different thresholds to go down and come back keep one slow probe from flapping a server.
 1  09:00:00 PostgreSQL primary failover takes 20 s
 2  deep check /health does SELECT 1 -> fails on all 40 servers
 3  ALB: 2 failures each -> all 40 unhealthy -> fail open (all targets get traffic anyway)
 4  HAProxy/NGINX without fail-open: "no live upstreams" -> 502/503 for every request, even cached pages
 5  09:00:20 DB back; rise 5 x 30 s -> 2.5 minutes before ALB marks targets healthy again

Real scenario: a deep check calling a third-party API, which rate-limits the health checks of a 200-instance fleet; a readiness endpoint that opens a new database connection on every probe, multiplied by every balancer node; a health check served by NGINX itself (static 200) that stays green while PHP-FPM is dead.

Check typeTestsUse forRisk
TCP connectPort openL4 pools, databasesProcess accepting but wedged
Shallow HTTP (/up)App boots and answersLiveness, LB defaultMisses broken dependencies
Readiness (/ready)Not draining, local resources, cached dependency statusLB target health, Kubernetes readinessProbeMust not fail fleet-wide together
Deep HTTPEvery dependency liveDashboards and alerts, not LB membershipCorrelated failure removes the whole pool
Agent check (HAProxy agent-check)Server reports its own weight or stateLoad-aware weights, drainAgent must be secured

Fix / how to use it: point the balancer at a readiness endpoint that is cheap, local and includes drain state; keep dependency checks cached for a few seconds; let alerts, not the balancer, react to deep failures; know your product's fail-open or panic behaviour. Code: ReadinessController (Laravel) and the panic-like rule in lbproxy.observe.

Connection draining and deregistration delay Must-know ​

In plain words: Before a server leaves the pool, stop sending it new requests but let the ones it already has finish.

Common misunderstanding: "Kubernetes or the ASG stops the instance and the balancer notices." The order matters: if the process gets SIGTERM before every balancer has stopped sending to it, requests in flight or just routed get 502. Removal from the balancer propagates asynchronously, so the server must keep serving for a few seconds after it starts draining.

Definition: AWS ELB deregistration delay: the target enters draining, ELB "stops sending requests to targets that are deregistering", and "By default, Elastic Load Balancing waits 300 seconds before completing the deregistration process"; if the target has no in-flight requests the process completes immediately, and "If a deregistering target terminates the connection before the deregistration delay elapses, the client receives a 500-level error response". HAProxy drain state "will not accept any new connections other than those that are accepted via persistence". NGINX drain (open source since 1.29.6): "only requests bound to the server will be proxied to it". Google calls the server-side version lame duck state: the task "asks its clients to send new requests to other backend tasks" from the SIGTERM handler while ongoing requests execute normally.

 1  t=0    deploy: lb:drain (readiness -> 503) or deregister from target group
 2  t=0-6  balancers' health checks notice (HAProxy 2 s x fall 3); ALB stops at once on deregister
 3  t=0+   in-flight requests continue; long ones keep running
 4  t=15   preStop sleep ends -> SIGTERM -> Octane/FPM finish in-flight and exit
 5  t=15+  deregistration delay or active=0 -> target unused -> instance terminated

Real scenario: zero-downtime rolling deploys; scale-in of an Auto Scaling group; WebSocket servers where "in flight" means connections lasting hours (drain timeout must be bounded and clients must reconnect); Kubernetes Pods where endpoint removal and SIGTERM happen concurrently, fixed with a preStop sleep.

ProductMechanismDefaultBound
AWS ALB/NLBderegistration_delay.timeout_seconds300 sCompletes early when the target has nothing in flight
HAProxyRuntime API set server b/s state drain, agent-check "drain"—Until maint or removal
NGINXserver ... drain—Open source since 1.29.6
EnvoyEndpoint health status DRAINING via EDS; listener drain on hot restart—drain_timeout
KubernetesEndpoint removed when Pod terminating; preStop; terminationGracePeriodSeconds30 s graceGrace period

Fix / how to use it: sequence it: fail readiness, wait interval × threshold + margin, then SIGTERM; set the deregistration delay just above your longest normal request (300 s is often too long and slows deploys); bound drains for long-lived connections. Code: lbproxy.Pool.Drain (TestDrainWaitsForInFlight, TestDrainDeadlineExpires) and Laravel lb:drain.

Slow start and warm-up Important ​

In plain words: A server that just joined (or rejoined) gets a small share of traffic at first and more over the next seconds, so it can fill caches, JIT-compile and open connection pools before taking full load.

Common misunderstanding: "A healthy server can take its full share." Health means "answers /up", not "is warm". A cold server receiving a full share under least connections is worse: it has zero connections, so every balancer sends it everything at once, it slows, fails its checks, and flaps. NGINX's docs: "A recently recovered server can be easily overwhelmed by connections, which may cause the server to be marked as unavailable again."

Definition: Slow start ramps a server's effective weight from near zero to nominal over a window. HAProxy slowstart: "The speed grows linearly from 0 to 100% during this time", applying to maxconn and to weight for dynamic algorithms, and "never applies when HAProxy starts" (only after a server was seen failed). AWS ALB slow_start.duration_seconds linearly increases requests; it cannot be combined with least outstanding requests or weighted random, and targets enter slow start only when at least one other healthy target is not in slow start. Envoy slow_start_config scales weight by max(MinWeightPercent, TimeFactor^(1/Aggression)). NGINX slow_start= is NGINX Plus only and incompatible with hash, ip_hash and random.

 slow start 30 s, nominal weight 10 (lbproxy uses a 10% floor)
 1  t=0    healthy (rise reached) -> effective weight 1
 2  t=15s  effective weight 5
 3  t=30s  effective weight 10 -> slow start over
 4  becomes unhealthy and recovers -> ramp starts again

Real scenario: JVM services that are slow until hot paths are compiled (the SRE Book describes keeping restarted tasks in lame duck state and prewarming them); PHP Octane workers that bootstrap the framework once per worker; caches that start empty; autoscaling events adding ten instances at once.

ProductKnobCurveRestrictions
HAProxyslowstart <time>Linear, weight and maxconnNot on startup; set inter smaller than slowstart
AWS ALBslow_start.duration_secondsLinearRound robin only
Envoyslow_start_config (window, aggression, min weight percent)Configurable exponentRR and least request
NGINX Plusserver ... slow_start=30sFrom zero to nominalNot with hash, ip_hash, random
Traefik / KubernetesReadiness gates, warm-up in the appApp-defined—

Fix / how to use it: enable slow start where the algorithm supports it; otherwise warm up in the app before reporting ready (prime caches, open pools) and roll out in small batches. Code: Backend.EffectiveWeight and TestSlowStartRampsLinearly.

Session affinity (sticky sessions) Important ​

In plain words: Send all requests of one user to the same server, using a cookie the balancer sets (cookie affinity) or the client's IP (source IP affinity).

Common misunderstanding: "Affinity is free." It fights every other goal: balancing (one heavy user makes one hot server), deploys (draining a server with sticky users takes as long as their sessions), failover (the server dies and its users lose state), and scale-out (new servers get only new users). Source IP affinity is worse: thousands of users behind one carrier-grade NAT or corporate proxy land on one server, and mobile clients change IP mid-session.

Definition: Cookie affinity: the balancer inserts or reads a cookie naming the server (AWS ALB duration-based AWSALB, or application-based with your cookie name; HAProxy cookie SRV insert indirect nocache; NGINX sticky cookie srv_id expires=1h, open source since 1.29.6, whose value is by default "a hexadecimal representation of the MD5 hash of the IP address and port"; Traefik sticky.cookie). Source IP affinity: NGINX ip_hash, HAProxy balance source or stick on src with a stick-table, IPVS sh, keepalived persistence_timeout, Kubernetes sessionAffinity: ClientIP (default timeoutSeconds 10800, three hours). If the bound server is unavailable, all products pick a new one "as if the client has not been bound yet" (NGINX wording).

 1  GET /cart (no cookie) -> RR picks app-2 -> Set-Cookie: AWSALB=...app-2
 2  GET /cart (cookie app-2) -> app-2   (algorithm bypassed)
 3  app-2 deployed / crashed -> cookie target unavailable -> new target app-4
 4  session data lived in app-2's memory (file driver) -> user logged out, cart empty
 5  with SESSION_DRIVER=redis: step 4 is harmless; affinity was never needed

Real scenario: legacy PHP apps with SESSION_DRIVER=file; WebSocket or SSE servers that keep per-connection state (the connection itself is sticky; reconnects need not be); in-memory per-user caches; shards where affinity is the design (use consistent hashing on the user id, not a cookie). For sessions and cookies themselves see Web Sessions, Cookies & CORS.

ProductCookie affinitySource IP affinityCaveats
AWS ALBAWSALB (duration) or application cookie—Not with weighted_random; AWSALBCORS for CORS
AWS NLB—Target group sticky sessions by source IPDocs warn: clients behind one NAT share a target
NGINXsticky cookie, sticky route, sticky learnip_hash, hash $remote_addr consistentsticky open source since 1.29.6
HAProxycookie <name> insertbalance source, stick on srcStick tables can sync between peers
Kubernetes Service—sessionAffinity: ClientIPDefault 10800 s
EnvoyStateful session filter, hash_policy cookiehash_policy source IPHash-based breaks on resize unless ring/Maglev

Fix / how to use it: remove the need: shared session store (Laravel redis or database driver), stateless tokens, shared caches. Where locality matters, hash a stable key consistently instead of pinning a cookie; keep cookie affinity short-lived and accept that it breaks on failure.

TLS termination, passthrough and re-encryption Must-know ​

In plain words: The balancer can decrypt TLS itself (termination), forward the encrypted bytes untouched to a backend that decrypts (passthrough), or decrypt, inspect, and encrypt again to the backend (re-encryption).

Common misunderstanding: "Passthrough is more secure, so prefer it." Passthrough keeps the key off the balancer but also blinds it: no L7 routing, no per-request balancing, no retries, no WAF, no X-Forwarded-For (client IP needs PROXY protocol or IP preservation). Re-encryption gives both visibility and encryption in transit at the cost of two handshakes and two certificate lifecycles.

Definition: Termination: the balancer holds the public certificate (ACM on AWS ALB, files in NGINX/HAProxy, SDS in Envoy) and talks HTTP or HTTPS upstream. Passthrough: an L4 balancer reads only the SNI in the ClientHello to choose a pool (SNI routing: HAProxy req.ssl_sni in mode tcp, NGINX ssl_preread, Envoy tls_inspector + filter chain match, Gateway API listener tls.mode: Passthrough with TLSRoute). Re-encryption: termination plus TLS (often mTLS) upstream; in Gateway API this is BackendTLSPolicy, "commonly known as a connection that is terminated and then re-encrypted at the Gateway". The wire handshake is in TLS in Practice; certificate design in Cryptography, TLS, PKI & Secrets; service identity in Mutual TLS.

Where TLS ends at the load balancerTerminationClientLBBackendTLSHTTPLB holds the public cert; sees HTTP; plain hop insideRe-encryptionClientLBBackendTLSTLSLB decrypts, routes, opens new TLS (or mTLS) upstreamPassthroughClientLB (L4, SNI)BackendTLSTLSL4 relays bytes; SNI picks the pool; backend holds the key
 1  ClientHello SNI=api.example.com, ALPN h2
 2  passthrough: LB reads SNI -> pool api (L4), relays bytes; backend presents cert
 3  termination: LB presents cert (ACM), decrypts, routes /v1 -> pool v1, HTTP/1.1 upstream
 4  re-encrypt: as 3, then new TLS to backend with internal CA; backend verifies LB cert (mTLS)
 5  backend sees X-Forwarded-Proto: https (termination) or the real TLS session (passthrough)

Real scenario: an ALB with ACM certificates terminating TLS for a Laravel app (TrustProxies needed for https:// URLs); an NLB TLS listener offloading TLS for a non-HTTP protocol; HAProxy SNI routing many tenants' domains to per-tenant backends with passthrough because tenants own their keys; regulated workloads requiring re-encryption inside the VPC.

ModeBalancer canBalancer cannotCertificates
Termination, HTTP upstreamRoute, retry, WAF, compress, add headersProve encryption inside the networkPublic cert on balancer
Re-encryption (HTTPS/mTLS upstream)Everything above, plus encryption in transitAvoid the second handshake costPublic cert + internal CA on both
Passthrough with SNI routingChoose pool by SNI, L4 balancingSee paths, headers, status codesCert on every backend
TLS offload at L4 (NLB TLS listener)Decrypt non-HTTP protocols, balance flowsRoute by HTTP contentPublic cert on balancer

Fix / how to use it: terminate at the L7 tier by default; re-encrypt when the network between balancer and backend is shared or policy says so; pass through only when the backend must own the key or the protocol is not HTTP. Rotate certificates automatically (ACM, cert-manager, SDS).

Load balancer high availability: VRRP, keepalived, ECMP, anycast Important ​

In plain words: The balancer must not be the new single point of failure. Either two balancers share one virtual IP and the standby takes it over (active-passive), or many balancers share the traffic through routing (active-active).

Common misunderstanding: "Two balancers means twice the capacity." In active-passive the standby carries nothing until failover, and the capacity is one node. In active-active with ECMP each node must also handle its neighbour's share when one fails, so plan for N-1.

Definition: VRRP (RFC 5798) "specifies an election protocol that dynamically assigns responsibility for a virtual router to one of the VRRP routers on a LAN": the highest-priority node owns the VIP and sends advertisements every advert_int; when they stop, a backup takes the VIP (gratuitous ARP). keepalived implements VRRP plus IPVS management ("High availability is achieved by the Virtual Redundancy Routing Protocol (VRRP)" and its load balancing "relies on the well-known and widely used Linux Virtual Server (IPVS) kernel module"); vrrp_script with weight lowers the priority when the local HAProxy dies. Active-active: routers spread flows over many balancers with ECMP (RFC 2992 hash-threshold) and the balancers use consistent hashing plus connection tracking so a flow that changes balancer still reaches the same backend (Maglev). Anycast extends this across sites. Managed services (ALB, NLB, GCP load balancers, Cloudflare) run these mechanisms for you across zones.

 active-passive with keepalived
 1  lb1 priority 150 MASTER owns 192.0.2.10; lb2 priority 100 BACKUP
 2  lb1 haproxy dies -> vrrp_script fails (fall 2) -> lb1 priority 150-20=130
 3  lb2 (100) still lower -> no takeover! weight must push lb1 below lb2: use -60 or a higher base on lb2
 4  with weight -60: lb1=90 < lb2=100 -> lb2 becomes MASTER, gratuitous ARP for the VIP
 5  established TCP connections through lb1 are lost unless state is synchronised (conntrackd, LVS sync daemon)

Real scenario: two on-premise HAProxy nodes with keepalived; Google's Maglev fleet behind ECMP; Cloudflare's anycast edge; an AWS ALB, which is itself a fleet of nodes per zone behind DNS (clients must re-resolve; NLB offers static IPs per zone).

ModelCapacityFailoverConnection survivalExample
Active-passive VRRPOne node1 to 3 advertisement intervalsLost unless state syncedkeepalived + HAProxy
Active-active ECMPN nodes, plan N-1Route withdrawal (BFD/BGP, seconds)Consistent hashing + conntrackMaglev, IPVS fleets
Anycast multi-siteGlobalBGP convergenceLost for that site's flowsCloudflare, Google front end
DNS across balancer nodesN nodesTTLNew connections onlyAWS ALB node IPs
ManagedProvider-scaledProvider-handledProvider-specificALB, NLB, GCP LB

Fix / how to use it: on your own hardware use keepalived with a tracking script whose weight really flips priority (the timeline's mistake is common); in cloud use the managed balancer and spread targets across zones. Config: keepalived.conf below uses priorities 150 and 100 with weight -60, so a failed check drops the primary to 90, below the backup.

Timeouts, limits and the 502 / 503 / 504 split Must-know ​

In plain words: Every balancer has timers (connect, read, idle) and limits (connections per server, queue length). Which one fires decides the status code the user sees.

Common misunderstanding: "504 means the backend is down." 504 means the balancer's timer fired while the backend may still be working (and will finish the work after the client left). 502 means the balancer could not get a valid response at all. 503 from a balancer means it had nowhere to send the request.

Definition: Idle timeout: AWS ALB default 60 s ("The idle timeout value, in seconds. The default is 60 seconds"); the backend's keepalive timeout must be longer, or the backend closes a pooled connection just as the balancer sends a request on it (ALB 502: "Check whether the keep-alive duration of the target is shorter than the idle timeout value of the load balancer"). Connect timeout: ALB 10 s (then 504). Max connections and queue: HAProxy maxconn per server queues the excess, and timeout queue drops it: "it is dropped and a 503 error is returned to the client"; NGINX Plus queue returns 502 when full or timed out. ALB 503: "no registered targets, or all of the registered targets are in an unused state". The proxy-level 502/504 mechanics (NGINX proxy_read_timeout, log lines) are in the proxies chapter.

 1  client -> ALB (idle 60 s) -> app (keepalive 5 s, Node/Go defaults vary)
 2  ALB reuses pooled connection idle for 5.1 s
 3  app had closed it at 5.0 s -> TCP RST -> ALB 502 (sporadic, a few per hour)
 4  fix: app keepalive 65 s > ALB idle 60 s; Go lbproxy uses IdleConnTimeout 50 s below its backends' timeout

Real scenario: a report endpoint exceeding the balancer's read timeout (504 while the database keeps working); HAProxy maxconn 200 per server protecting Octane workers, with a short timeout queue turning overload into fast 503s rather than slow everything; WebSockets cut at 60 s by an idle timeout.

StatusAWS ALB causeHAProxy causeNGINX causeRetry?
502RST on connect, target closed during request, malformed response, deregistration delay elapsedEmpty, invalid or incomplete response (SH, SD flags)Refused, reset, upstream prematurely closed, Plus queue fullSafe methods only
503No registered or healthy-routable targetsNo server available, connection refused after retries (SC), timeout queue (sQ)no live upstreams reported as 502 by NGINX; 503 from limit_req or appWith backoff and Retry-After
504Connect timeout 10 s, idle timeout while waiting for responsetimeout server (sH)proxy_read_timeout, proxy_connect_timeoutOutcome unknown: only idempotent
460 / 499ALB 460: client closed before idle timeoutCD flags499 client closedNo

Fix / how to use it: order the timers: client timeout > balancer timeout > backend timeout > dependency timeout, and backend keepalive > balancer idle timeout; protect backends with per-server maxconn and a short queue; return 503 with Retry-After when shedding. Code: lbproxy returns 503 with Retry-After when no backend is eligible and 504 on header timeout (TestSlowBackendIs504).

Retries and idempotency at the balancer Must-know ​

In plain words: A balancer can hide a dead server by sending the failed request to another one, but only when sending it twice cannot do harm.

Common misunderstanding: "Retrying 5xx on another server is free reliability." A POST that reached the first server may have charged the card before the connection broke. And retries multiply load exactly when the system is overloaded: three layers retrying three times is 27 attempts.

Definition: Safe to retry at the balancer: failures before the request reached the backend (connect refused, reset before sending), and idempotent methods (GET, HEAD, PUT, DELETE, OPTIONS) or requests carrying an idempotency key the backend deduplicates. NGINX: proxy_next_upstream error timeout by default; "requests with a non-idempotent method (POST, LOCK, PATCH) are not passed to the next server if a request has been sent to an upstream server" unless non_idempotent is set; "passing a request to the next server is only possible if nothing has been sent to a client yet"; bound with proxy_next_upstream_tries and _timeout. HAProxy: retries and option redispatch (retry on another server after a connection failure). Envoy: route retry_policy with retry_on, retry budgets and num_retries. AWS ALB exposes no retry policy to configure; do not count on it. Keys and storage: API Idempotency; budgets and jitter: Timeouts, Retries & Jitter.

 1  POST /orders -> app-2: request sent, app-2 crashes before responding
 2  NGINX: non-idempotent and already sent -> do not pass to next server -> 502 to client
 3  client retries with Idempotency-Key: 7c0e... -> app-4 checks key store -> not seen -> creates order
 4  (if app-2 had committed: key found -> returns the original 201, no double order)

Real scenario: connection refused during a deploy (safe to retry, TestSafeRetryAndPassiveEjection); a timeout on payment capture (never retry at the balancer; the client retries with a key); retry storms during a brownout (limit with budgets and circuit breakers).

ProductRetries whatNon-idempotentLimit
NGINXerror timeout (+ listed codes)Only with non_idempotentproxy_next_upstream_tries, _timeout
HAProxyConnection failures (retries, redispatch); retry-on for moreOnly if configured in retry-onretries count
Envoyretry_on: connect-failure, 5xx, reset, retriable-status-codes ...Per route decisionnum_retries, retry budget, per_try_timeout
AWS ALBNo configurable retry policyNo—
Go lbproxyDial errors on idempotent body-less requestsOnly with Idempotency-Key and no bodyAttempts

Fix / how to use it: let the balancer retry connection failures for idempotent requests once; leave everything else to clients with idempotency keys; cap retries with budgets. Code: lbproxy.errorHandler and TestPostNotRetried.

Client-side load balancing, gRPC and the service mesh Important ​

In plain words: Instead of a balancer in the middle, the caller itself knows the list of servers and picks one per request.

Common misunderstanding: "An L4 load balancer in front of gRPC servers balances gRPC." gRPC multiplexes all calls over one long-lived HTTP/2 connection; an L4 balancer picks a server once per connection, so each client sticks to one server and new servers get no traffic until clients reconnect. You need L7 (Envoy, ALB with gRPC) or client-side balancing.

Definition: gRPC's load-balancing guide: in proxy load balancing "the client issues RPCs to the a Load Balancer (LB) proxy" and "clients can be untrusted"; in client-side load balancing "the client is aware of multiple backend servers and chooses one to use for each RPC". Options are a thick client (the library does discovery, health and the algorithm) and lookaside balancing (an external service tells clients which backends to use). A service mesh moves the thick client into a sidecar proxy (Envoy in Istio) controlled by xDS, so every caller balances with P2C and outlier detection without library code. Google's SRE Book adds subsetting: each client connects to a subset of backends (deterministic subsetting) so neither side holds thousands of connections. Discovery itself: Service Discovery; sidecars: Service Mesh & Sidecar.

 1  orders (Go, gRPC) resolves dns:///inventory.internal -> 6 addresses
 2  round_robin policy: subchannel per address, RPCs rotate across ready subchannels
 3  inventory-4 sends GOAWAY (draining) -> client stops using it, reconnects elsewhere
 4  scale-out to 9 pods: DNS re-resolution on reconnect or periodic -> new subchannels
 5  mesh alternative: orders -> local Envoy -> P2C over 9 endpoints from EDS

Real scenario: Go services calling each other over gRPC with round_robin; Istio sidecars doing least request with outlier detection; Google's deterministic subsetting so 300 clients connect to 10 of 300 backends each.

ApproachWhere the algorithm runsProsCons
Proxy (central L4/L7)Balancer fleetUntrusted clients, one place for policyExtra hop, balancer capacity
Thick clientCaller libraryNo hop, per-request decisionsEvery language needs the library
LookasideExternal LB service + clientCentral policy, no data hopExtra protocol
Sidecar meshPer-pod proxyUniform policy, no library codeA proxy per pod, control plane
SubsettingClient to a subsetFewer connectionsUneven load if subsets are random

Fix / how to use it: for internal gRPC, use client-side round_robin with DNS re-resolution or a mesh; set server MaxConnectionAge so long-lived connections rebalance after scale-out; for public clients, put an L7 balancer in front.

Hot backends and uneven load Important ​

In plain words: One server runs at 90% CPU while the rest idle at 30%. The algorithm, the keys or the connections are not as uniform as you assumed.

Common misunderstanding: "Add servers until the hot one cools down." If the cause is a hot key (one tenant, one cache key, one chat room) or one long-lived connection, more servers change nothing; the hot one stays hot.

Definition: Causes: hash affinity with a skewed key distribution (celebrity user, big tenant); source IP affinity behind NAT; long-lived connections at L4 (gRPC, WebSocket) after scale-out; least connections sinkholing to a failing server; a server in a slower zone or on a noisy host; balancers without shared counters (NGINX without zone). Fixes are per-request algorithms (least outstanding requests, P2C), bounded-load consistent hashing (HAProxy hash-balance-factor: "if <factor> is 150, then no server will be allowed to have a load more than 1.5 times the average"), connection age limits, and splitting hot keys.

 1  WebSocket fleet 4 servers, 40k connections, 10k each
 2  scale-out to 8 at peak -> new servers get only NEW connections
 3  old 4 still hold ~10k each, new 4 slowly fill -> imbalance for hours
 4  fix: max connection age + jittered client reconnect; or least-conn for new connections only

Real scenario: a multi-tenant SaaS where one tenant is 30% of traffic and tenant-hashing puts it on one server; a cache tier with one viral URL; gRPC clients pinned to the first three pods after a deploy.

SymptomLikely causeFix
One server hot, its requests normalHot key under hash affinityBounded load, split key, replicate hot items
New servers idle after scale-outLong-lived connections at L4Max connection age, L7 or client-side balancing
Failing server gets more trafficLeast-conn sinkholeOutlier detection, count errors as load
Hot servers in one zoneCross-zone disabled with uneven targets per zoneEnable cross-zone load balancing or balance targets per zone
Uneven with many balancersEach balancer's own view, herdingP2C, shared state (zone)

Fix / how to use it: graph requests, in-flight and latency per backend first; then pick the fix from the table. Code: TestP2CAvoidsHotBackend and HAProxy hash-balance-factor in the config snippet.

Per-backend observability Important ​

In plain words: Graph each backend separately. Pool averages hide the one server that is failing.

Common misunderstanding: "The balancer's 5xx rate is the app's error rate." It mixes app errors (backend returned 500) with balancer errors (502/503/504 the balancer generated). ALB reports them separately (HTTPCode_Target_5XX_Count vs HTTPCode_ELB_5XX_Count), NGINX logs $upstream_status next to $status, Envoy has per-host stats and response flags.

Definition: Per backend: request rate, in-flight requests, latency percentiles (time to first byte and total), status code split, health state transitions, ejections, connection errors and retries. Per pool: healthy host count, panic state, queue length, and for hash policies the ring or table balance (Envoy min_hashes_per_host, max_entries_per_host). Log $upstream_addr and $upstream_response_time in NGINX ("If several servers were contacted during request processing, their addresses are separated by commas"); see Observability.

 1  pool p99 = 180 ms (fine), pool 5xx = 0.4%
 2  per backend: app-7 p99 = 2.1 s, 5xx = 6%; others 120 ms, 0.1%
 3  app-7 on a host with a failing disk -> drain, replace

Real scenario: finding one bad instance after an ASG rollout; noticing that retries hide a failing zone (upstream_addr shows two servers per request); checking a Maglev table for missing hosts.

SignalNGINXHAProxyEnvoyAWS ALB
Which backend served$upstream_addr%s server name in log%UPSTREAM_HOST%Access log target:port
Backend latency$upstream_response_time, $upstream_header_timeTc/Tr/Td timersupstream_rq_time histogramTargetResponseTime
Errors by origin$upstream_status vs $statusTermination flagsResponse flags UF, UT, UHHTTPCode_Target_5XX vs HTTPCode_ELB_5XX
HealthPlus API / statusStats page, show servers state/clusters admin, membership_healthyHealthyHostCount, UnHealthyHostCount

Fix / how to use it: log the chosen backend on every request and keep a per-backend dashboard; the SQL in Laravel shows the query over an access-log table.

Kubernetes: Service, Ingress and Gateway API Important ​

In plain words: A Kubernetes Service is an L4 load balancer for Pods built into every node; Ingress and Gateway API describe L7 routing that a controller (NGINX, Envoy, Traefik, a cloud LB) implements.

Common misunderstanding: "A Service balances requests." kube-proxy balances connections (iptables and nftables pick an endpoint at random per new connection; IPVS uses its scheduler); HTTP keepalive and gRPC make that per-connection choice sticky. And Ingress is not deprecated but frozen: "The Ingress API is generally available ... The Ingress API is no longer being developed", and "The Kubernetes project recommends using Gateway instead of Ingress".

Definition: Service (ClusterIP, NodePort, LoadBalancer) plus EndpointSlices of Ready Pods; kube-proxy modes iptables, nftables (recommended replacement) and ipvs (deprecated since v1.35, disabled by default from v1.40, removed in v1.43; schedulers rr, wrr, lc, wlc, lblc, lblcr, sh, dh, sed, nq, mh). sessionAffinity: ClientIP with timeoutSeconds (default 10800). Gateway API: GatewayClass (controller), Gateway (listeners, TLS mode Terminate or Passthrough), HTTPRoute (matches, filters, weighted backendRefs), TLSRoute, GRPCRoute, BackendTLSPolicy. Mechanics of kube-proxy and CNI: Kubernetes Networking; the platform: Containers & Kubernetes.

 1  cloud LB (Service type LoadBalancer or Gateway) -> node -> kube-proxy rule -> Pod
 2  Pod not Ready -> removed from EndpointSlice -> no new connections
 3  Pod terminating -> removed from endpoints AND SIGTERM concurrently -> preStop sleep covers the gap
 4  HTTPRoute weights 90/10 -> controller programs Envoy/NGINX with the split

Real scenario: a canary with HTTPRoute weights; a gRPC service behind a ClusterIP where one Pod gets all traffic (fix: headless Service + client-side round_robin, or a mesh); an AWS Load Balancer Controller creating an ALB per Ingress or Gateway with IP targets pointing straight at Pods.

ObjectLayerBalancesNotes
Service ClusterIPL4 in-clusterConnections to Ready Podsiptables/nftables random; IPVS schedulers
Service LoadBalancerL4 externalCloud LB to nodes or PodsexternalTrafficPolicy: Local routes only to node-local endpoints
IngressL7Requests by host/pathFrozen API, controller-specific annotations
Gateway + HTTPRouteL7Requests by host/path/header, weightsRole-oriented, portable
TLSRoute / PassthroughL4 with SNIConnections by SNIBackend holds the key
Headless ServiceDNS onlyNothing; clients balanceFor gRPC client-side LB, StatefulSets

Fix / how to use it: use Gateway API for new L7 routing, readiness probes plus preStop for draining, and headless Services or a mesh for gRPC. Config: kubernetes-gateway.yaml below.

Products: what each one is for Must-know ​

ProductLayerAlgorithmsHealthStrengthWatch out
NGINX (open source)L7, L4 via streamRR, least_conn, ip_hash, hash [consistent], random [two], least_time (1.31.0+)Passive only (max_fails)Ubiquitous, fast, static files, TLSActive checks, slow start, queue need NGINX Plus
NGINX PlusL7, L4As above + least_time with randomActive health_check, mandatoryAPI reconfiguration, slow startLicence
HAProxyL4 (mode tcp) and L7 (mode http)roundrobin, static-rr, leastconn, first, source, uri, url_param, hdr, random(n), hashActive, agent, passive (observe)Richest knobs, stick tables, runtime APIConfig is code: review it
EnvoyL4 and L7, sidecar or edgeRR, least request (P2C), ring hash, Maglev, random, client-side WRRActive, outlier detection, panic thresholdxDS dynamic config, mesh data planeComplex config; use a control plane
TraefikL7, L4wrr, p2c, hrw, leasttimeActive, passiveAuto-discovery from Docker/KubernetesLess fine-grained timers
AWS ALBL7Round robin, least outstanding requests, weighted randomTarget group checks, ATWManaged, ACM certificates, Lambda targetsDNS-only addresses, 60 s idle timeout, no configurable retries
AWS NLBL4 (TCP, UDP, TLS, QUIC)Flow hashTCP/HTTP/HTTPS checksStatic IPs, millions of requests per second, client IP preservationPer-connection balancing
GCP / Azure LBsL4 and L7, global and regionalProvider-specificProvider checksGlobal anycast front ends (GCP)Provider semantics differ
Cloudflare Load BalancingDNS/anycast GSLB + proxySteering policies, weightsMonitors per poolGlobal health-based steeringOrigin must trust Cloudflare ranges
IPVS + keepalivedL4 in kernelrr, wrr, lc, wlc, sh, dh, lblc, mh ...keepalived checkersVery fast, NAT/DR/TUNOperations burden, no L7
Kubernetes kube-proxyL4 per nodeRandom (iptables/nftables), IPVS schedulersPod readinessBuilt inPer connection

Mechanics ​

The exact knobs ​

KnobProductDefaultWhat it controls
weight=NGINX server1Share in WRR, least_conn, hash
max_fails / fail_timeoutNGINX server1 / 10 sPassive check: failures in window; also the ejection time
backup / down / drainNGINX server—Spare server; permanently off; only bound requests (drain open source since 1.29.6)
keepaliveNGINX upstream32 (local) since 1.29.7Idle upstream connections cached per worker
hash $key consistentNGINX upstream—Ketama ring (160 points per server, Cache::Memcached::Fast compatible)
random two least_connNGINX upstream—P2C on connections
proxy_next_upstreamNGINXerror timeoutWhich failures pass the request to the next server
balanceHAProxy backendroundrobinAlgorithm
inter / fall / riseHAProxy server2000 ms / 3 / 2Active check pace and hysteresis
slowstartHAProxy serveroffLinear ramp of weight and maxconn after recovery
maxconn + timeout queueHAProxyqueue timeout = timeout connect if unsetPer-server concurrency; queued requests get 503 when it expires
hash-type / hash-balance-factorHAProxymap-based / 0Consistent vs mod-N; bounded load
lb_policyEnvoy clusterROUND_ROBINLEAST_REQUEST, RING_HASH, MAGLEV, RANDOM
choice_countEnvoy least request2P2C draws
consecutive_5xx / base_ejection_time / max_ejection_percentEnvoy outlier detection5 / 30 s / 10%Passive ejection
healthy_panic_thresholdEnvoy50%Below it, ignore health and use all hosts (or none)
load_balancing.algorithm.typeAWS ALB target groupround_robinleast_outstanding_requests, weighted_random
deregistration_delay.timeout_secondsAWS ELB300Draining time
slow_start.duration_secondsAWS ALB0 (off)Linear ramp
idle timeoutAWS ALB60 sClose idle connections; backend keepalive must be longer
sessionAffinityConfig.clientIP.timeoutSecondsKubernetes Service10800Source IP affinity lifetime
advert_int / prioritykeepalived VRRP1 s / per nodeFailover pace and election

Status codes and log lines ​

WhereYou seeMeaning
NGINX error logno live upstreams while connecting to upstreamEvery server in the group is marked failed: the client gets 502
NGINX error logconnect() failed (111: Connection refused) while connecting to upstreamNothing listening: 502, retried if proxy_next_upstream error
NGINX error logupstream timed out (110: Connection timed out) while reading response header from upstreamproxy_read_timeout: 504
NGINX access log$upstream_addr = 10.0.1.11:8000, 10.0.1.12:8000The request was retried on a second server
HAProxy logtermination state sQ / SC / sHExpired in queue (503) / server refused the connection (503 after retries) / timeout server before headers (504)
HAProxy statsDRAIN, MAINT, DOWN 1/3Admin drain, maintenance, health transition (1 of 3 failures)
Envoy access logUH, UF, UT, UONo healthy upstream (503), connection failure, upstream timeout, overflow (circuit breaker)
AWS ALB metricsHTTPCode_ELB_5XX_Count vs HTTPCode_Target_5XX_CountBalancer-generated vs backend-generated errors
AWS ALBHTTP 460Client closed the connection before the idle timeout
Go httputil.ReverseProxyhttp: proxy error: dial tcp ...: connect: connection refusedDefault ErrorHandler; lbproxy replaces it

The arithmetic ​

 detection time (active)    = interval x unhealthy_threshold + timeout
   ALB defaults             = 30 s x 2 (+5 s)  ~ 60-65 s
   HAProxy defaults         = 2 s x 3          ~ 6 s
 recovery time              = interval x healthy_threshold  (ALB 30 s x 5 = 150 s)
 drain budget (k8s)         = readiness detection + preStop sleep < terminationGracePeriodSeconds
   example                  = 2 s x 2 = 4 s detection; preStop 15 s; grace 45 s
 keys moved on resize       = mod-N: (N-1)/N of keys ; consistent: ~1/N
   measured (10 -> 9)       = mod-N 90.4% ; ring hash 9.4% ; Maglev 0.19% between survivors
 retry amplification        = attempts per layer ^ layers  (3 layers x 3 tries = 27)
 N+1 capacity               = per-node load at N-1 nodes must stay under the knee (see latency budgets)

Back-of-envelope, labelled as estimate: an extra L7 hop inside one zone costs roughly 0.1 to 1 ms (the same estimate the proxies chapter uses); the expensive parts are TLS handshakes at the edge and connection setup to backends, which keepalive pools amortise. The SRE Book's warning about subsetting gives the other number: if a subset algorithm overloads one backend by 10%, "the whole set of backends needs to be overprovisioned by 10%".

Go ​

Before: hash mod N ​

before.Pick is a reasonable first design: deterministic, even, stateless. Its flaw shows when the pool changes size.

go
// Package before shows the naive hash-mod-N choice that many first load
// balancers and client libraries use. It is not broken: it spreads keys evenly
// and is deterministic. Its design flaw is what happens when N changes.
package before

import "hash/fnv"

// Pick returns the index of the backend for key with hash(key) mod n.
// Removing or adding one backend changes n, so almost every key moves.
func Pick(key string, n int) int {
	h := fnv.New64a()
	_, _ = h.Write([]byte(key))
	return int(h.Sum64() % uint64(n))
}
go
package before

import (
	"fmt"
	"testing"
)

// Going from 10 to 9 backends remaps roughly 90% of keys: every cache,
// sticky session or connection keyed this way is lost at once.
func TestModuloRemapsMostKeys(t *testing.T) {
	const keys = 10000
	moved := 0
	for i := 0; i < keys; i++ {
		k := fmt.Sprintf("user-%d", i)
		if Pick(k, 10) != Pick(k, 9) {
			moved++
		}
	}
	frac := float64(moved) / keys
	t.Logf("moved %.1f%% of keys going from 10 to 9 backends", frac*100)
	if frac < 0.8 {
		t.Fatalf("expected most keys to move, moved %.2f", frac)
	}
}

After: pluggable algorithms ​

The balancer package holds the backend state machine (healthy, draining, ejected, slow start) and six pickers behind one interface: smooth weighted round robin, weighted least connections, P2C, random, ring hash and Maglev.

go
// Package balancer holds the backend state and the pluggable picking
// algorithms of a small L7 load balancer: smooth weighted round robin,
// weighted least connections, power of two random choices, random,
// ring hash (Ketama style) and Maglev.
package balancer

import (
	"hash/fnv"
	"net/url"
	"sync/atomic"
	"time"
)

// Backend is one member of a backend pool (an "upstream server" in NGINX,
// a "server" in HAProxy, an "endpoint" in Envoy, a "target" in AWS ELB).
type Backend struct {
	Name   string
	URL    *url.URL
	Weight int // nominal weight, >= 1

	active       atomic.Int64 // in-flight requests (outstanding requests)
	healthy      atomic.Bool  // result of active health checks
	draining     atomic.Bool  // no new requests; in-flight ones finish
	ejectedUntil atomic.Int64 // unix nanos; passive health check (outlier) ejection
	healthySince atomic.Int64 // unix nanos; start of the slow-start window
}

// NewBackend returns a backend that is not yet healthy: it must pass the
// health checker's rise threshold first, like a new AWS ALB target.
func NewBackend(name string, u *url.URL, weight int) *Backend {
	if weight < 1 {
		weight = 1
	}
	return &Backend{Name: name, URL: u, Weight: weight}
}

func (b *Backend) Active() int64      { return b.active.Load() }
func (b *Backend) Acquire()           { b.active.Add(1) }
func (b *Backend) Release()           { b.active.Add(-1) }
func (b *Backend) Healthy() bool      { return b.healthy.Load() }
func (b *Backend) Draining() bool     { return b.draining.Load() }
func (b *Backend) SetDraining(d bool) { b.draining.Store(d) }

// SetHealthy flips the health state; becoming healthy restarts slow start.
func (b *Backend) SetHealthy(h bool, now time.Time) {
	if h && !b.healthy.Load() {
		b.healthySince.Store(now.UnixNano())
	}
	b.healthy.Store(h)
}

// Eject removes the backend from rotation until now+d (outlier detection).
func (b *Backend) Eject(now time.Time, d time.Duration) {
	b.ejectedUntil.Store(now.Add(d).UnixNano())
}

// Eligible reports whether new requests may be sent to the backend.
func (b *Backend) Eligible(now time.Time) bool {
	return b.healthy.Load() && !b.draining.Load() && now.UnixNano() >= b.ejectedUntil.Load()
}

// EffectiveWeight applies a linear slow start: a backend that just became
// healthy starts at 10% of its weight and reaches 100% after window.
// HAProxy "slowstart" and AWS ALB slow start mode are also linear; Envoy
// adds an "aggression" exponent.
func (b *Backend) EffectiveWeight(now time.Time, window time.Duration) float64 {
	w := float64(b.Weight)
	if window <= 0 {
		return w
	}
	since := b.healthySince.Load()
	if since == 0 {
		return w
	}
	elapsed := now.Sub(time.Unix(0, since))
	if elapsed >= window {
		return w
	}
	frac := float64(elapsed) / float64(window)
	if frac < 0.1 {
		frac = 0.1
	}
	return w * frac
}

// Picker chooses one backend among the eligible candidates. key is the hash
// key (client IP, cookie, header or URL) and is ignored by non-hash pickers.
// Pick returns nil only when candidates is empty.
type Picker interface {
	Pick(key string, candidates []*Backend, now time.Time) *Backend
}

// hash64 is FNV-1a followed by a splitmix64 finaliser for better avalanche.
// It must be stable across processes so that every load balancer instance
// maps a key to the same backend; hash/maphash is seeded per process.
func hash64(s string) uint64 {
	h := fnv.New64a()
	_, _ = h.Write([]byte(s))
	x := h.Sum64()
	x ^= x >> 30
	x *= 0xbf58476d1ce4e5b9
	x ^= x >> 27
	x *= 0x94d049bb133111eb
	x ^= x >> 31
	return x
}
go
package balancer

import (
	"sync"
	"time"
)

// RoundRobin is the smooth weighted round robin used by NGINX: weights
// 5,1,1 give a a b a c a a instead of a a a a a b c, so a heavy server
// never receives a burst.
type RoundRobin struct {
	SlowStart time.Duration
	mu        sync.Mutex
	current   map[*Backend]float64
}

func (rr *RoundRobin) Pick(_ string, cs []*Backend, now time.Time) *Backend {
	if len(cs) == 0 {
		return nil
	}
	rr.mu.Lock()
	defer rr.mu.Unlock()
	if rr.current == nil {
		rr.current = make(map[*Backend]float64)
	}
	var best *Backend
	total := 0.0
	for _, b := range cs {
		w := b.EffectiveWeight(now, rr.SlowStart)
		rr.current[b] += w
		total += w
		if best == nil || rr.current[b] > rr.current[best] {
			best = b
		}
	}
	rr.current[best] -= total
	return best
}
go
package balancer

import (
	"sync/atomic"
	"time"
)

// LeastConn is weighted least connections (HAProxy "leastconn", NGINX
// "least_conn", AWS ALB "least_outstanding_requests" in spirit): the lowest
// active/weight wins; ties rotate so that equal servers share the load.
type LeastConn struct {
	SlowStart time.Duration
	next      atomic.Uint64
}

func (lc *LeastConn) Pick(_ string, cs []*Backend, now time.Time) *Backend {
	n := len(cs)
	if n == 0 {
		return nil
	}
	start := int(lc.next.Add(1) % uint64(n))
	var best *Backend
	bestScore := 0.0
	for i := 0; i < n; i++ {
		b := cs[(start+i)%n]
		score := float64(b.Active()+1) / b.EffectiveWeight(now, lc.SlowStart)
		if best == nil || score < bestScore {
			best, bestScore = b, score
		}
	}
	return best
}
go
package balancer

import (
	"math/rand/v2"
	"sync"
	"time"
)

// P2C is "power of two random choices": draw two distinct backends at
// random and keep the one with fewer in-flight requests per unit of weight.
// O(1), no shared global view needed, and it never herds every new request
// onto the single least-loaded server the way a stale least-conn view can.
type P2C struct {
	SlowStart time.Duration
	mu        sync.Mutex
	rng       *rand.Rand
}

// NewP2C returns a P2C picker; seed makes tests deterministic.
func NewP2C(seed uint64) *P2C {
	return &P2C{rng: rand.New(rand.NewPCG(seed, seed^0x9e3779b97f4a7c15))}
}

func (p *P2C) Pick(_ string, cs []*Backend, now time.Time) *Backend {
	n := len(cs)
	switch n {
	case 0:
		return nil
	case 1:
		return cs[0]
	}
	p.mu.Lock()
	i := p.rng.IntN(n)
	j := p.rng.IntN(n - 1)
	p.mu.Unlock()
	if j >= i {
		j++
	}
	a, b := cs[i], cs[j]
	la := float64(a.Active()+1) / a.EffectiveWeight(now, p.SlowStart)
	lb := float64(b.Active()+1) / b.EffectiveWeight(now, p.SlowStart)
	if lb < la {
		return b
	}
	return a
}

// Random picks uniformly; Envoy notes it beats round robin when no health
// checking is configured because it avoids bias towards the host after a
// failed one.
type Random struct {
	mu  sync.Mutex
	rng *rand.Rand
}

func NewRandom(seed uint64) *Random {
	return &Random{rng: rand.New(rand.NewPCG(seed, seed+1))}
}

func (r *Random) Pick(_ string, cs []*Backend, _ time.Time) *Backend {
	if len(cs) == 0 {
		return nil
	}
	r.mu.Lock()
	defer r.mu.Unlock()
	return cs[r.rng.IntN(len(cs))]
}
go
package balancer

import (
	"slices"
	"sort"
	"strconv"
	"strings"
	"sync"
	"time"
)

// RingHash is consistent hashing on a ring (Ketama, Envoy RING_HASH,
// NGINX "hash $key consistent", HAProxy "hash-type consistent"). Each
// backend owns VNodes*Weight points; a key goes to the first point
// clockwise from hash(key). Removing one of N backends moves about 1/N of
// the keys, and only keys that were on the removed backend.
type RingHash struct {
	VNodes int // points per unit of weight; Envoy's ring is 1024..8M points

	mu     sync.Mutex
	sig    string
	points []ringPoint
}

type ringPoint struct {
	hash uint64
	b    *Backend
}

func signature(cs []*Backend) string {
	parts := make([]string, len(cs))
	for i, b := range cs {
		parts[i] = b.Name + "/" + strconv.Itoa(b.Weight)
	}
	slices.Sort(parts)
	return strings.Join(parts, ",")
}

// build is called when the candidate set changes (a backend added, removed,
// ejected or drained). The ring is a function of names only, so every load
// balancer instance builds the same ring.
func (r *RingHash) build(cs []*Backend) {
	v := r.VNodes
	if v <= 0 {
		v = 100
	}
	r.points = r.points[:0]
	for _, b := range cs {
		for i := 0; i < v*b.Weight; i++ {
			r.points = append(r.points, ringPoint{hash64(b.Name + "#" + strconv.Itoa(i)), b})
		}
	}
	sort.Slice(r.points, func(i, j int) bool { return r.points[i].hash < r.points[j].hash })
}

func (r *RingHash) Pick(key string, cs []*Backend, _ time.Time) *Backend {
	if len(cs) == 0 {
		return nil
	}
	r.mu.Lock()
	defer r.mu.Unlock()
	if s := signature(cs); s != r.sig {
		r.build(cs)
		r.sig = s
	}
	h := hash64(key)
	i := sort.Search(len(r.points), func(i int) bool { return r.points[i].hash >= h })
	if i == len(r.points) {
		i = 0 // wrap around the ring
	}
	return r.points[i].b
}
go
package balancer

import (
	"slices"
	"sync"
	"time"
)

// Maglev implements the lookup-table population of Eisenbud et al.,
// "Maglev: A Fast and Reliable Software Network Load Balancer" (NSDI 2016),
// section 3.4. Each backend gets a permutation of the M table slots derived
// from offset and skip; backends take turns claiming their next free slot
// until the table is full. Every backend ends up with M/N slots (+-1), and
// a lookup is one hash and one array index.
type Maglev struct {
	M int // table size, a prime much larger than N; Envoy uses 65537

	mu    sync.Mutex
	sig   string
	table []*Backend
}

func (m *Maglev) build(cs []*Backend) {
	size := m.M
	if size <= 0 {
		size = 65537
	}
	sorted := slices.Clone(cs)
	slices.SortFunc(sorted, func(a, b *Backend) int {
		if a.Name < b.Name {
			return -1
		}
		if a.Name > b.Name {
			return 1
		}
		return 0
	})
	n := len(sorted)
	offset := make([]uint64, n)
	skip := make([]uint64, n)
	next := make([]uint64, n)
	for i, b := range sorted {
		offset[i] = hash64("offset:"+b.Name) % uint64(size)
		skip[i] = hash64("skip:"+b.Name)%uint64(size-1) + 1
	}
	table := make([]*Backend, size)
	filled := 0
	for filled < size {
		for i := 0; i < n && filled < size; i++ {
			c := (offset[i] + next[i]*skip[i]) % uint64(size)
			for table[c] != nil {
				next[i]++
				c = (offset[i] + next[i]*skip[i]) % uint64(size)
			}
			table[c] = sorted[i]
			next[i]++
			filled++
		}
	}
	m.table = table
}

func (m *Maglev) Pick(key string, cs []*Backend, _ time.Time) *Backend {
	if len(cs) == 0 {
		return nil
	}
	m.mu.Lock()
	defer m.mu.Unlock()
	if s := signature(cs); s != m.sig {
		m.build(cs)
		m.sig = s
	}
	return m.table[hash64(key)%uint64(len(m.table))]
}
go
package balancer

import (
	"fmt"
	"strings"
	"testing"
	"time"
)

var t0 = time.Unix(1_700_000_000, 0)

func pool(weights ...int) []*Backend {
	bs := make([]*Backend, len(weights))
	for i, w := range weights {
		bs[i] = NewBackend(string(rune('a'+i)), nil, w)
		bs[i].SetHealthy(true, t0.Add(-time.Hour))
	}
	return bs
}

// The NGINX documentation's example: weights 5,1,1 over 7 requests.
func TestSmoothWeightedRoundRobin(t *testing.T) {
	bs := pool(5, 1, 1)
	rr := &RoundRobin{}
	var seq []string
	for i := 0; i < 7; i++ {
		seq = append(seq, rr.Pick("", bs, t0).Name)
	}
	if got := strings.Join(seq, " "); got != "a a b a c a a" {
		t.Fatalf("sequence %q", got)
	}
}

func TestLeastConnPicksIdleServer(t *testing.T) {
	bs := pool(1, 1, 1)
	for i := 0; i < 5; i++ {
		bs[0].Acquire()
		bs[1].Acquire()
	}
	lc := &LeastConn{}
	for i := 0; i < 10; i++ {
		if b := lc.Pick("", bs, t0); b.Name != "c" {
			t.Fatalf("picked %s, want the idle c", b.Name)
		}
	}
}

// Weighted least connections: a weight-3 server with 3 active requests is
// "as loaded" as a weight-1 server with 1.
func TestLeastConnRespectsWeight(t *testing.T) {
	bs := pool(3, 1)
	bs[0].Acquire()
	bs[0].Acquire()
	bs[1].Acquire()
	if b := (&LeastConn{}).Pick("", bs, t0); b.Name != "a" {
		t.Fatalf("picked %s; (2+1)/3 < (1+1)/1 so a should win", b.Name)
	}
}

// A hot backend (100 in flight) loses every comparison it is drawn into,
// so P2C never picks it while any other candidate exists.
func TestP2CAvoidsHotBackend(t *testing.T) {
	bs := pool(1, 1, 1, 1)
	for i := 0; i < 100; i++ {
		bs[2].Acquire()
	}
	p := NewP2C(42)
	counts := map[string]int{}
	for i := 0; i < 4000; i++ {
		counts[p.Pick("", bs, t0).Name]++
	}
	if counts["c"] != 0 {
		t.Fatalf("hot backend picked %d times", counts["c"])
	}
	for _, n := range []string{"a", "b", "d"} {
		if counts[n] < 1000 {
			t.Fatalf("uneven: %v", counts)
		}
	}
}

func TestSlowStartRampsLinearly(t *testing.T) {
	b := NewBackend("new", nil, 10)
	b.SetHealthy(true, t0)
	w := 30 * time.Second
	cases := []struct {
		at   time.Duration
		want float64
	}{{0, 1}, {15 * time.Second, 5}, {30 * time.Second, 10}, {time.Hour, 10}}
	for _, c := range cases {
		if got := b.EffectiveWeight(t0.Add(c.at), w); got != c.want {
			t.Fatalf("at %v weight %.2f, want %.2f", c.at, got, c.want)
		}
	}
}

func owners(p Picker, bs []*Backend, keys int) map[string]string {
	m := make(map[string]string, keys)
	for i := 0; i < keys; i++ {
		k := fmt.Sprintf("user-%d", i)
		m[k] = p.Pick(k, bs, t0).Name
	}
	return m
}

// Consistent hashing property: removing one of 10 backends moves only the
// keys that lived on it (about 10%), never keys between survivors.
func TestRingHashMovesOnlyRemovedKeys(t *testing.T) {
	bs := pool(1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
	r := &RingHash{VNodes: 160}
	before := owners(r, bs, 20000)
	after := owners(r, append(bs[:3:3], bs[4:]...), 20000)
	moved := 0
	for k, was := range before {
		if after[k] != was {
			moved++
			if was != "d" {
				t.Fatalf("key %s moved from survivor %s to %s", k, was, after[k])
			}
		}
	}
	frac := float64(moved) / 20000
	t.Logf("ring hash moved %.1f%% of keys", frac*100)
	if frac < 0.05 || frac > 0.15 {
		t.Fatalf("moved %.3f, want about 0.10", frac)
	}
}

func TestMaglevBalancedAndMostlyStable(t *testing.T) {
	bs := pool(1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
	m := &Maglev{M: 65537}
	m.Pick("warm", bs, t0)
	slots := map[string]int{}
	for _, b := range m.table {
		slots[b.Name]++
	}
	lo, hi := 1<<30, 0
	for _, n := range slots {
		lo, hi = min(lo, n), max(hi, n)
	}
	if hi-lo > 1 {
		t.Fatalf("slots per backend differ by %d: %v", hi-lo, slots)
	}
	before := owners(m, bs, 20000)
	after := owners(m, append(bs[:3:3], bs[4:]...), 20000)
	survivorMoves := 0
	for k, was := range before {
		if was != "d" && after[k] != was {
			survivorMoves++
		}
	}
	frac := float64(survivorMoves) / 20000
	t.Logf("maglev moved %.2f%% of keys between surviving backends", frac*100)
	if frac > 0.05 {
		t.Fatalf("too much disruption: %.3f", frac)
	}
}

func TestIneligibleBackends(t *testing.T) {
	b := NewBackend("x", nil, 1)
	if b.Eligible(t0) {
		t.Fatal("new backend must pass health checks first")
	}
	b.SetHealthy(true, t0)
	b.Eject(t0, 10*time.Second)
	if b.Eligible(t0.Add(5 * time.Second)) {
		t.Fatal("ejected backend eligible")
	}
	if !b.Eligible(t0.Add(11 * time.Second)) {
		t.Fatal("ejection did not expire")
	}
	b.SetDraining(true)
	if b.Eligible(t0.Add(time.Minute)) {
		t.Fatal("draining backend eligible")
	}
}

After: an L7 load balancer with health checks and draining ​

lbproxy.Pool is an http.Handler built on httputil.ReverseProxy with Rewrite. It runs active checks with rise/fall hysteresis, passive ejection, safe retries, draining, and maps failures to 502, 503 and 504. cmd/lb wires it to flags and signals.

go
// Package lbproxy is a small L7 reverse-proxy load balancer: a backend pool
// with a pluggable picker, active health checks with rise/fall hysteresis,
// passive health checks (outlier ejection), slow start, connection draining,
// safe retries and the 502/503/504 split.
package lbproxy

import (
	"context"
	"errors"
	"net"
	"net/http"
	"net/http/httputil"
	"sync"
	"time"

	"academy/load-balancing/balancer"
)

type Config struct {
	Picker balancer.Picker
	// Key extracts the hash key for hash pickers (client IP, cookie,
	// header, URL). Nil means the request path (a URL hash).
	Key func(*http.Request) string

	HealthPath     string        // e.g. "/up" for Laravel, "/healthz"
	HealthInterval time.Duration // HAProxy inter, ALB HealthCheckIntervalSeconds
	HealthTimeout  time.Duration // ALB HealthCheckTimeoutSeconds
	Rise, Fall     int           // consecutive successes / failures to flip state

	EjectAfter int           // consecutive passive failures before ejection
	EjectFor   time.Duration // Envoy base_ejection_time
	Attempts   int           // total tries for a safe request (1 = no retry)

	Transport http.RoundTripper // with dial and ResponseHeaderTimeout set
}

type Pool struct {
	cfg   Config
	proxy *httputil.ReverseProxy
	hc    *http.Client

	mu       sync.RWMutex
	backends []*balancer.Backend
	state    map[*balancer.Backend]*counters
}

type counters struct {
	mu                sync.Mutex
	okRun, failRun    int // active check streaks
	passiveFailInARow int
}

type ctxKey struct{}

type attempt struct {
	b       *balancer.Backend
	retry   bool
	lastErr error
}

func New(cfg Config) *Pool {
	if cfg.Rise <= 0 {
		cfg.Rise = 2
	}
	if cfg.Fall <= 0 {
		cfg.Fall = 3
	}
	if cfg.Attempts <= 0 {
		cfg.Attempts = 2
	}
	if cfg.HealthTimeout <= 0 {
		cfg.HealthTimeout = 2 * time.Second
	}
	if cfg.Transport == nil {
		cfg.Transport = DefaultTransport()
	}
	p := &Pool{cfg: cfg, state: map[*balancer.Backend]*counters{}}
	p.hc = &http.Client{Transport: cfg.Transport, Timeout: cfg.HealthTimeout}
	p.proxy = &httputil.ReverseProxy{
		Transport: cfg.Transport,
		Rewrite: func(pr *httputil.ProxyRequest) {
			a := pr.In.Context().Value(ctxKey{}).(*attempt)
			pr.SetURL(a.b.URL)
			pr.SetXForwarded() // see the proxies chapter for trusting it
		},
		ModifyResponse: func(resp *http.Response) error {
			a := resp.Request.Context().Value(ctxKey{}).(*attempt)
			p.observe(a.b, resp.StatusCode < 500)
			return nil
		},
		ErrorHandler: p.errorHandler,
	}
	return p
}

// DefaultTransport is tuned for a proxy: bounded dial and header waits and a
// large idle pool per backend (Go's default MaxIdleConnsPerHost is 2).
func DefaultTransport() *http.Transport {
	return &http.Transport{
		DialContext:           (&net.Dialer{Timeout: 2 * time.Second, KeepAlive: 30 * time.Second}).DialContext,
		ResponseHeaderTimeout: 10 * time.Second,
		MaxIdleConnsPerHost:   64,
		IdleConnTimeout:       50 * time.Second, // below the backend's keepalive timeout
	}
}

func (p *Pool) Add(b *balancer.Backend) {
	p.mu.Lock()
	defer p.mu.Unlock()
	p.backends = append(p.backends, b)
	p.state[b] = &counters{}
}

func (p *Pool) eligible(now time.Time, exclude map[*balancer.Backend]bool) []*balancer.Backend {
	p.mu.RLock()
	defer p.mu.RUnlock()
	out := make([]*balancer.Backend, 0, len(p.backends))
	for _, b := range p.backends {
		if b.Eligible(now) && !exclude[b] {
			out = append(out, b)
		}
	}
	return out
}

// CheckOnce runs one active health check round (HAProxy "check", Envoy
// health_checks, ALB target group health check).
func (p *Pool) CheckOnce(ctx context.Context) {
	p.mu.RLock()
	bs := append([]*balancer.Backend(nil), p.backends...)
	p.mu.RUnlock()
	var wg sync.WaitGroup
	for _, b := range bs {
		wg.Add(1)
		go func() {
			defer wg.Done()
			p.recordCheck(b, p.probe(ctx, b))
		}()
	}
	wg.Wait()
}

func (p *Pool) probe(ctx context.Context, b *balancer.Backend) bool {
	req, err := http.NewRequestWithContext(ctx, http.MethodGet, b.URL.String()+p.cfg.HealthPath, nil)
	if err != nil {
		return false
	}
	resp, err := p.hc.Do(req)
	if err != nil {
		return false
	}
	resp.Body.Close()
	return resp.StatusCode >= 200 && resp.StatusCode < 300
}

// recordCheck applies hysteresis: Fall failures in a row to go down, Rise
// successes in a row to come back, so one slow probe does not flap a server.
func (p *Pool) recordCheck(b *balancer.Backend, ok bool) {
	c := p.counters(b)
	if c == nil {
		return // removed by Drain while the probe was in flight
	}
	c.mu.Lock()
	defer c.mu.Unlock()
	now := time.Now()
	if ok {
		c.okRun++
		c.failRun = 0
		if !b.Healthy() && c.okRun >= p.cfg.Rise {
			b.SetHealthy(true, now)
		}
		return
	}
	c.failRun++
	c.okRun = 0
	if b.Healthy() && c.failRun >= p.cfg.Fall {
		b.SetHealthy(false, now)
	}
}

// Run checks every HealthInterval until ctx is cancelled.
func (p *Pool) Run(ctx context.Context) {
	t := time.NewTicker(p.cfg.HealthInterval)
	defer t.Stop()
	for {
		p.CheckOnce(ctx)
		select {
		case <-ctx.Done():
			return
		case <-t.C:
		}
	}
}

func (p *Pool) counters(b *balancer.Backend) *counters {
	p.mu.RLock()
	defer p.mu.RUnlock()
	return p.state[b]
}

// observe is the passive health check: consecutive real-traffic failures
// eject the backend for EjectFor, but never the last eligible one (a crude
// version of Envoy's max_ejection_percent and panic threshold).
func (p *Pool) observe(b *balancer.Backend, ok bool) {
	if p.cfg.EjectAfter <= 0 {
		return
	}
	c := p.counters(b)
	if c == nil {
		return
	}
	c.mu.Lock()
	defer c.mu.Unlock()
	if ok {
		c.passiveFailInARow = 0
		return
	}
	c.passiveFailInARow++
	now := time.Now()
	if c.passiveFailInARow >= p.cfg.EjectAfter && len(p.eligible(now, nil)) > 1 {
		b.Eject(now, p.cfg.EjectFor)
		c.passiveFailInARow = 0
	}
}

// Drain stops new requests to the named backend and waits until its
// in-flight requests finish or ctx expires (AWS deregistration delay,
// HAProxy "set server ... state drain", NGINX "drain").
func (p *Pool) Drain(ctx context.Context, name string) error {
	p.mu.RLock()
	var target *balancer.Backend
	for _, b := range p.backends {
		if b.Name == name {
			target = b
		}
	}
	p.mu.RUnlock()
	if target == nil {
		return errors.New("lbproxy: unknown backend " + name)
	}
	target.SetDraining(true)
	tick := time.NewTicker(10 * time.Millisecond)
	defer tick.Stop()
	for target.Active() > 0 {
		select {
		case <-ctx.Done():
			return ctx.Err() // deregistration delay elapsed: in-flight requests will fail
		case <-tick.C:
		}
	}
	p.mu.Lock()
	defer p.mu.Unlock()
	for i, b := range p.backends {
		if b == target {
			p.backends = append(p.backends[:i], p.backends[i+1:]...)
			delete(p.state, b)
			break
		}
	}
	return nil
}

func idempotent(r *http.Request) bool {
	switch r.Method {
	case http.MethodGet, http.MethodHead, http.MethodOptions, http.MethodPut, http.MethodDelete:
		return r.Body == nil || r.Body == http.NoBody || r.ContentLength == 0
	}
	return r.Header.Get("Idempotency-Key") != "" && (r.Body == nil || r.Body == http.NoBody)
}

func (p *Pool) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	key := r.URL.Path
	if p.cfg.Key != nil {
		key = p.cfg.Key(r)
	}
	tried := map[*balancer.Backend]bool{}
	for i := 0; i < p.cfg.Attempts; i++ {
		now := time.Now()
		b := p.cfg.Picker.Pick(key, p.eligible(now, tried), now)
		if b == nil {
			if i == 0 {
				w.Header().Set("Retry-After", "1")
				http.Error(w, "no healthy upstream", http.StatusServiceUnavailable)
				return
			}
			break // retries exhausted the pool; fall through to 502
		}
		tried[b] = true
		a := &attempt{b: b, retry: i+1 < p.cfg.Attempts && idempotent(r)}
		b.Acquire()
		p.proxy.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), ctxKey{}, a)))
		b.Release()
		if a.lastErr == nil {
			return // response (any status) was written
		}
	}
	http.Error(w, "upstream connect error", http.StatusBadGateway)
}

// errorHandler runs before anything was written to the client. A dial
// failure on a safe request is retried on another backend; a timeout
// becomes 504 (the outcome is unknown, so it is never retried here);
// everything else is 502.
func (p *Pool) errorHandler(w http.ResponseWriter, r *http.Request, err error) {
	a := r.Context().Value(ctxKey{}).(*attempt)
	p.observe(a.b, false)
	var op *net.OpError
	if errors.As(err, &op) && op.Op == "dial" && a.retry {
		a.lastErr = err // tell ServeHTTP to try the next backend
		return
	}
	var ne net.Error
	if errors.Is(err, context.DeadlineExceeded) || (errors.As(err, &ne) && ne.Timeout()) {
		w.Header().Set("X-LB-Upstream", a.b.Name)
		http.Error(w, "upstream timeout", http.StatusGatewayTimeout)
		return
	}
	w.Header().Set("X-LB-Upstream", a.b.Name)
	http.Error(w, "bad gateway", http.StatusBadGateway) // never echo internal addresses
}
go
package lbproxy

import (
	"context"
	"io"
	"net"
	"net/http"
	"net/http/httptest"
	"net/url"
	"strings"
	"sync/atomic"
	"testing"
	"time"

	"academy/load-balancing/balancer"
)

// app is a fake backend whose health endpoint can be switched off.
type app struct {
	srv     *httptest.Server
	healthy atomic.Bool
	hits    atomic.Int64
	delay   time.Duration
}

func newApp(t *testing.T, name string, delay time.Duration) *app {
	a := &app{delay: delay}
	a.healthy.Store(true)
	a.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path == "/up" {
			if !a.healthy.Load() {
				w.WriteHeader(http.StatusServiceUnavailable)
				return
			}
			io.WriteString(w, "ok")
			return
		}
		a.hits.Add(1)
		time.Sleep(a.delay)
		io.WriteString(w, name)
	}))
	t.Cleanup(a.srv.Close)
	return a
}

func backend(t *testing.T, name, raw string) *balancer.Backend {
	u, err := url.Parse(raw)
	if err != nil {
		t.Fatal(err)
	}
	return balancer.NewBackend(name, u, 1)
}

// deadURL returns an address where nothing listens: dialing it is refused.
func deadURL(t *testing.T) string {
	l, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		t.Fatal(err)
	}
	addr := l.Addr().String()
	l.Close()
	return "http://" + addr
}

func newPool(cfg Config) *Pool {
	cfg.HealthPath = "/up"
	if cfg.Picker == nil {
		cfg.Picker = &balancer.RoundRobin{}
	}
	return New(cfg)
}

func TestHealthCheckRiseAndFall(t *testing.T) {
	a := newApp(t, "a", 0)
	b := backend(t, "a", a.srv.URL)
	p := newPool(Config{Rise: 2, Fall: 3})
	p.Add(b)
	ctx := context.Background()

	p.CheckOnce(ctx)
	if b.Healthy() {
		t.Fatal("healthy after 1 success; rise is 2")
	}
	p.CheckOnce(ctx)
	if !b.Healthy() {
		t.Fatal("not healthy after 2 successes")
	}
	a.healthy.Store(false)
	p.CheckOnce(ctx)
	p.CheckOnce(ctx)
	if !b.Healthy() {
		t.Fatal("marked down after 2 failures; fall is 3 (hysteresis)")
	}
	p.CheckOnce(ctx)
	if b.Healthy() {
		t.Fatal("still up after 3 failures")
	}
}

func TestNoHealthyBackendIs503(t *testing.T) {
	p := newPool(Config{})
	p.Add(backend(t, "a", deadURL(t))) // never checked, so never healthy
	rec := httptest.NewRecorder()
	p.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/", nil))
	if rec.Code != http.StatusServiceUnavailable || rec.Header().Get("Retry-After") == "" {
		t.Fatalf("got %d, want 503 with Retry-After", rec.Code)
	}
}

// A GET that fails to connect is retried on the next backend and the dead
// backend is ejected by the passive check after EjectAfter failures.
func TestSafeRetryAndPassiveEjection(t *testing.T) {
	live := newApp(t, "live", 0)
	dead := backend(t, "dead", deadURL(t))
	ok := backend(t, "live", live.srv.URL)
	p := newPool(Config{Attempts: 2, EjectAfter: 2, EjectFor: time.Minute})
	p.Add(dead)
	p.Add(ok)
	dead.SetHealthy(true, time.Now()) // health check has not noticed yet
	ok.SetHealthy(true, time.Now())

	for i := 0; i < 6; i++ {
		rec := httptest.NewRecorder()
		p.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/cart", nil))
		if rec.Code != 200 || rec.Body.String() != "live" {
			t.Fatalf("request %d: %d %q", i, rec.Code, rec.Body.String())
		}
	}
	if dead.Eligible(time.Now()) {
		t.Fatal("dead backend was not ejected")
	}
}

// A POST is not retried: the client sees 502 and decides (idempotency key).
func TestPostNotRetried(t *testing.T) {
	live := newApp(t, "live", 0)
	dead := backend(t, "dead", deadURL(t))
	ok := backend(t, "live", live.srv.URL)
	p := newPool(Config{Attempts: 2})
	p.Add(dead)
	p.Add(ok)
	dead.SetHealthy(true, time.Now())
	ok.SetHealthy(true, time.Now())

	rec := httptest.NewRecorder()
	p.ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/orders", strings.NewReader(`{"sku":1}`)))
	if rec.Code != http.StatusBadGateway {
		t.Fatalf("got %d, want 502", rec.Code)
	}
	if live.hits.Load() != 0 {
		t.Fatal("POST was replayed on another backend")
	}
}

func TestSlowBackendIs504(t *testing.T) {
	slow := newApp(t, "slow", 300*time.Millisecond)
	b := backend(t, "slow", slow.srv.URL)
	tr := DefaultTransport()
	tr.ResponseHeaderTimeout = 50 * time.Millisecond
	p := newPool(Config{Transport: tr})
	p.Add(b)
	b.SetHealthy(true, time.Now())
	rec := httptest.NewRecorder()
	p.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/report", nil))
	if rec.Code != http.StatusGatewayTimeout {
		t.Fatalf("got %d, want 504", rec.Code)
	}
}

// Drain lets the in-flight request finish, sends nothing new to the
// draining backend, then removes it.
func TestDrainWaitsForInFlight(t *testing.T) {
	slow := newApp(t, "slow", 200*time.Millisecond)
	fast := newApp(t, "fast", 0)
	bs, bf := backend(t, "slow", slow.srv.URL), backend(t, "fast", fast.srv.URL)
	p := newPool(Config{})
	p.Add(bs)
	p.Add(bf)
	bs.SetHealthy(true, time.Now())
	bf.SetHealthy(true, time.Now())

	done := make(chan int)
	go func() { // RoundRobin sends the first request to "slow"
		rec := httptest.NewRecorder()
		p.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/long", nil))
		done <- rec.Code
	}()
	for bs.Active() == 0 {
		time.Sleep(time.Millisecond)
	}
	drained := make(chan error)
	go func() { drained <- p.Drain(context.Background(), "slow") }()
	for !bs.Draining() {
		time.Sleep(time.Millisecond)
	}
	for i := 0; i < 5; i++ {
		rec := httptest.NewRecorder()
		p.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/x", nil))
		if rec.Body.String() != "fast" {
			t.Fatalf("new request went to %q while draining", rec.Body.String())
		}
	}
	if code := <-done; code != 200 {
		t.Fatalf("in-flight request failed with %d", code)
	}
	if err := <-drained; err != nil {
		t.Fatal(err)
	}
	if slow.hits.Load() != 1 {
		t.Fatalf("slow got %d requests, want 1", slow.hits.Load())
	}
}

func TestDrainDeadlineExpires(t *testing.T) {
	slow := newApp(t, "slow", 300*time.Millisecond)
	b := backend(t, "slow", slow.srv.URL)
	p := newPool(Config{})
	p.Add(b)
	b.SetHealthy(true, time.Now())
	go p.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/long", nil))
	for b.Active() == 0 {
		time.Sleep(time.Millisecond)
	}
	ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
	defer cancel()
	if err := p.Drain(ctx, "slow"); err != context.DeadlineExceeded {
		t.Fatalf("got %v, want deadline exceeded", err)
	}
}

// Ring hash keyed by a header: one tenant always lands on one backend.
func TestHashKeyAffinity(t *testing.T) {
	apps := []*app{newApp(t, "a", 0), newApp(t, "b", 0), newApp(t, "c", 0)}
	p := newPool(Config{
		Picker: &balancer.RingHash{VNodes: 100},
		Key:    func(r *http.Request) string { return r.Header.Get("X-Tenant") },
	})
	for i, a := range apps {
		b := backend(t, string(rune('a'+i)), a.srv.URL)
		p.Add(b)
		b.SetHealthy(true, time.Now())
	}
	first := ""
	for i := 0; i < 10; i++ {
		req := httptest.NewRequest(http.MethodGet, "/", nil)
		req.Header.Set("X-Tenant", "acme")
		rec := httptest.NewRecorder()
		p.ServeHTTP(rec, req)
		if first == "" {
			first = rec.Body.String()
		}
		if rec.Body.String() != first {
			t.Fatalf("tenant moved from %s to %s", first, rec.Body.String())
		}
	}
}
go
// Command lb runs the lbproxy pool as a standalone L7 load balancer.
//
//	go run ./cmd/lb -listen 127.0.0.1:8080 -algo p2c \
//	  -backends a=http://127.0.0.1:9001,b=http://127.0.0.1:9002
//
// SIGHUP drains the backend named in the file given by -drain-file;
// SIGINT/SIGTERM stop accepting, finish in-flight requests, then exit.
package main

import (
	"context"
	"flag"
	"log"
	"net"
	"net/http"
	"net/url"
	"os"
	"os/signal"
	"strings"
	"syscall"
	"time"

	"academy/load-balancing/balancer"
	"academy/load-balancing/lbproxy"
)

func picker(name string) balancer.Picker {
	switch name {
	case "rr":
		return &balancer.RoundRobin{SlowStart: 30 * time.Second}
	case "lc":
		return &balancer.LeastConn{SlowStart: 30 * time.Second}
	case "p2c":
		return balancer.NewP2C(uint64(time.Now().UnixNano()))
	case "random":
		return balancer.NewRandom(uint64(time.Now().UnixNano()))
	case "ring":
		return &balancer.RingHash{VNodes: 160}
	case "maglev":
		return &balancer.Maglev{M: 65537}
	}
	log.Fatalf("unknown -algo %q", name)
	return nil
}

func clientIP(r *http.Request) string {
	host, _, err := net.SplitHostPort(r.RemoteAddr)
	if err != nil {
		return r.RemoteAddr
	}
	return host // source IP affinity; behind another proxy use a trusted resolver
}

func main() {
	listen := flag.String("listen", "127.0.0.1:8080", "listen address")
	algo := flag.String("algo", "p2c", "rr | lc | p2c | random | ring | maglev")
	list := flag.String("backends", "", "name=url,name=url")
	hashBy := flag.String("hash-by", "path", "path | ip | header:<name> | cookie:<name> (ring, maglev)")
	drainFile := flag.String("drain-file", "", "file holding a backend name to drain on SIGHUP")
	flag.Parse()

	cfg := lbproxy.Config{
		Picker:         picker(*algo),
		HealthPath:     "/up",
		HealthInterval: 2 * time.Second,
		HealthTimeout:  time.Second,
		Rise:           2,
		Fall:           3,
		EjectAfter:     5,
		EjectFor:       30 * time.Second,
		Attempts:       2,
	}
	switch {
	case *hashBy == "ip":
		cfg.Key = clientIP
	case strings.HasPrefix(*hashBy, "header:"):
		h := strings.TrimPrefix(*hashBy, "header:")
		cfg.Key = func(r *http.Request) string { return r.Header.Get(h) }
	case strings.HasPrefix(*hashBy, "cookie:"):
		n := strings.TrimPrefix(*hashBy, "cookie:")
		cfg.Key = func(r *http.Request) string {
			if c, err := r.Cookie(n); err == nil {
				return c.Value
			}
			return clientIP(r)
		}
	}
	pool := lbproxy.New(cfg)
	for _, item := range strings.Split(*list, ",") {
		name, raw, ok := strings.Cut(item, "=")
		if !ok {
			log.Fatalf("bad backend %q", item)
		}
		u, err := url.Parse(raw)
		if err != nil {
			log.Fatal(err)
		}
		pool.Add(balancer.NewBackend(name, u, 1))
	}

	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer stop()
	go pool.Run(ctx)

	hup := make(chan os.Signal, 1)
	signal.Notify(hup, syscall.SIGHUP)
	go func() {
		for range hup {
			b, err := os.ReadFile(*drainFile)
			if err != nil {
				log.Print(err)
				continue
			}
			name := strings.TrimSpace(string(b))
			dctx, cancel := context.WithTimeout(ctx, 30*time.Second) // deregistration delay
			err = pool.Drain(dctx, name)
			cancel()
			log.Printf("drain %s: err=%v", name, err)
		}
	}()

	srv := &http.Server{
		Addr:              *listen,
		Handler:           pool,
		ReadHeaderTimeout: 5 * time.Second,
		IdleTimeout:       60 * time.Second, // client-side idle timeout, like AWS ALB's default
	}
	go func() {
		<-ctx.Done()
		sctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
		defer cancel()
		_ = srv.Shutdown(sctx)
	}()
	log.Printf("lb %s on %s", *algo, *listen)
	if err := srv.ListenAndServe(); err != http.ErrServerClosed {
		log.Fatal(err)
	}
}

The Go angle ​

  • httputil.ReverseProxy is the standard building block. Use Rewrite (it receives ProxyRequest with In and Out, and strips forwarding headers from Out before calling you); SetURL points the request at the chosen backend and SetXForwarded writes X-Forwarded-For, X-Forwarded-Host and X-Forwarded-Proto. Trust rules for those headers are in the proxies chapter.
  • The per-attempt backend travels in the request context: Rewrite, ModifyResponse and ErrorHandler all read it. ErrorHandler runs before anything is written to the client, which is what makes a retry on another backend possible; lbproxy signals "retry" by recording the error instead of writing a response.
  • Classify errors with errors.As(err, &*net.OpError) and Op == "dial" (safe to retry: the request never reached the backend) and net.Error.Timeout() or context.DeadlineExceeded (504, outcome unknown, never retried here).
  • Tune http.Transport: MaxIdleConnsPerHost defaults to 2, far too low for a proxy; ResponseHeaderTimeout bounds the wait for headers (the 504 in TestSlowBackendIs504); IdleConnTimeout must be shorter than the backends' keepalive timeout to avoid the idle-race 502.
  • Counters are sync/atomic (atomic.Int64, atomic.Bool) so picking reads them without a lock; pickers with internal state (RoundRobin, P2C's RNG, the ring and Maglev table) use a mutex.
  • Hash functions must be stable across processes so every balancer instance maps a key the same way. hash/maphash is randomly seeded per process, so the code uses hash/fnv with a splitmix64 finaliser.
  • math/rand/v2 with rand.NewPCG(seed, ...) gives deterministic tests for P2C; in production seed from time or use the global functions.
  • Graceful shutdown: http.Server.Shutdown stops accepting and waits for in-flight requests; signal.NotifyContext ties SIGTERM to it. Drain the balancer's backends with Pool.Drain, the server-side equivalent of AWS deregistration delay.
  • gRPC in Go: grpc.NewClient("dns:///inventory.internal:50051", grpc.WithDefaultServiceConfig(cfg)) with cfg set to the JSON {"loadBalancingConfig": [ {"round_robin": {} } ]} gives client-side round robin over every resolved address; on the server, keepalive.ServerParameters{MaxConnectionAge: 5 * time.Minute} forces clients to reconnect periodically so new pods receive traffic.

Laravel ​

Example: an application that is easy to balance ​

A Laravel application behind AWS ALB or NGINX needs four things from this chapter: trust the balancer's forwarding headers, expose a cheap liveness endpoint and a readiness endpoint that includes drain state, keep sessions in a shared store so no affinity is needed, and drain before stopping.

php
<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Request;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up', // shallow liveness: 200 if the app boots, 500 otherwise
    )
    ->withMiddleware(function (Middleware $middleware): void {
        // Behind AWS ALB / NGINX: trust only the balancer subnets, never '*'
        // unless the app is unreachable except through the balancer.
        $middleware->trustProxies(
            at: explode(',', (string) env('TRUSTED_PROXIES', '10.0.0.0/8')),
            headers: Request::HEADER_X_FORWARDED_FOR
                | Request::HEADER_X_FORWARDED_HOST
                | Request::HEADER_X_FORWARDED_PORT
                | Request::HEADER_X_FORWARDED_PROTO
                | Request::HEADER_X_FORWARDED_AWS_ELB,
        );
        $middleware->trustHosts(at: ['^shop\.example$']); // regular expressions
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        //
    })
    ->create();
php
<?php

use App\Http\Controllers\ReadinessController;
use Illuminate\Support\Facades\Route;

// The load balancer target group / readinessProbe points here, not at /up.
// No session: a probe every 2 s from every balancer node must not create sessions.
Route::get('/ready', ReadinessController::class)
    ->withoutMiddleware([
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
    ]);
php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Throwable;

/**
 * Readiness for the load balancer: "may this instance receive new requests?"
 *
 * - 503 while draining, so the balancer's health check fails first and new
 *   requests go elsewhere while in-flight ones finish.
 * - A cheap dependency check, cached per instance for a few seconds so a
 *   fleet of balancers probing every 2 s does not become a database load.
 *   The result is cached in the local array/file store, not a shared one:
 *   each instance must answer for itself.
 */
class ReadinessController
{
    public function __invoke(): JsonResponse
    {
        if (is_file(storage_path('framework/draining'))) {
            return response()->json(['status' => 'draining'], 503)
                ->header('Connection', 'close');
        }

        $dbOk = Cache::store('file')->remember('ready:db:'.gethostname(), 5, function (): bool {
            try {
                DB::connection()->select('select 1');

                return true;
            } catch (Throwable) {
                return false;
            }
        });

        return $dbOk
            ? response()->json(['status' => 'ready'])
            : response()->json(['status' => 'degraded', 'db' => false], 503);
    }
}
php
<?php

namespace App\Console\Commands;

use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;

/**
 * preStop hook / deploy step: fail readiness, then wait long enough for every
 * load balancer to notice (interval x unhealthy threshold + margin) before the
 * process receives SIGTERM. Octane/FPM then finish in-flight requests.
 */
#[Signature('lb:drain {--wait=15 : Seconds to keep serving while balancers react} {--undo : Remove the drain flag}')]
#[Description('Mark this instance as draining for the load balancer')]
class DrainCommand extends Command
{
    public function handle(): int
    {
        $flag = storage_path('framework/draining');

        if ($this->option('undo')) {
            @unlink($flag);
            $this->info('Instance is accepting traffic again.');

            return self::SUCCESS;
        }

        touch($flag);
        $wait = max(0, (int) $this->option('wait'));
        $this->info("Draining: /ready returns 503; waiting {$wait}s for balancers to stop sending.");
        sleep($wait);

        return self::SUCCESS;
    }
}
php
<?php

// Excerpt of config/session.php: a shared store makes every instance able to
// serve every user, so the load balancer needs no session affinity.
return [
    'driver' => env('SESSION_DRIVER', 'redis'), // or 'database'; never 'file' behind a balancer
    'connection' => env('SESSION_CONNECTION'),
    'lifetime' => (int) env('SESSION_LIFETIME', 120),
    'secure' => env('SESSION_SECURE_COOKIE', true), // TLS ends at the balancer; trust X-Forwarded-Proto
    'same_site' => env('SESSION_SAME_SITE', 'lax'),
];
php
<?php

namespace Tests\Feature;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Cache;
use Tests\TestCase;

class ReadinessTest extends TestCase
{
    use RefreshDatabase;

    protected function tearDown(): void
    {
        @unlink(storage_path('framework/draining'));
        parent::tearDown();
    }

    public function test_ready_when_database_answers(): void
    {
        Cache::store('file')->flush();

        $this->get('/ready')->assertOk()->assertJson(['status' => 'ready']);
    }

    public function test_draining_instance_fails_readiness_but_stays_alive(): void
    {
        $this->artisan('lb:drain', ['--wait' => 0])->assertSuccessful();

        $this->get('/ready')->assertStatus(503)->assertJson(['status' => 'draining']);
        $this->get('/up')->assertOk(); // liveness stays green: do not restart a draining pod
    }

    public function test_client_ip_comes_from_trusted_balancer_only(): void
    {
        $this->withServerVariables(['REMOTE_ADDR' => '10.0.1.5'])
            ->withHeader('X-Forwarded-For', '198.51.100.7')
            ->get('/ready');

        $this->assertSame('198.51.100.7', request()->ip());
    }
}

The balancer configurations that go with it:

conf
# NGINX (open source) in front of three Laravel Octane servers.
upstream app {
    zone app 64k;                 # shared state across workers (counters, drain)
    least_conn;                   # or: random two least_conn; or: hash $cookie_tenant consistent (no backup then)
    server 10.0.1.11:8000 weight=2 max_fails=3 fail_timeout=10s;
    server 10.0.1.12:8000          max_fails=3 fail_timeout=10s;
    server 10.0.1.13:8000          max_fails=3 fail_timeout=10s drain;   # drain: 1.29.6+ in OSS
    server 10.0.1.19:8000 backup;  # only used when all primaries are unavailable
    keepalive 32;                  # idle upstream connections per worker
    keepalive_timeout 50s;         # shorter than the app's own idle timeout
}

server {
    listen 443 ssl;
    http2 on;
    server_name shop.example;
    ssl_certificate     /etc/nginx/tls/shop.example.crt;
    ssl_certificate_key /etc/nginx/tls/shop.example.key;   # TLS terminates here

    location / {
        proxy_pass http://app;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_connect_timeout 2s;
        proxy_read_timeout 30s;                       # fires as 504
        proxy_next_upstream error timeout http_502 http_503;
        proxy_next_upstream_tries 2;                  # POST/PATCH/LOCK not retried without non_idempotent
        proxy_next_upstream_timeout 5s;
    }

    location = /up { access_log off; proxy_pass http://app; }
}

# NGINX Plus only: active checks and slow start
# location / { proxy_pass http://app; health_check uri=/up interval=5 fails=3 passes=2; }
# server 10.0.1.11:8000 slow_start=30s;
cfg
# HAProxy: L7 for HTTP, L4 (mode tcp) for PostgreSQL, one config.
defaults
    mode http
    timeout connect 2s
    timeout client  60s
    timeout server  30s       # server silent for 30 s -> 504
    timeout queue   5s        # waited for a maxconn slot -> 503
    timeout check   2s
    option  redispatch        # on connection failure, retry another server
    retries 2

frontend https_in
    bind :443 ssl crt /etc/haproxy/tls/shop.example.pem alpn h2,http/1.1
    option forwardfor
    http-request set-header X-Forwarded-Proto https
    default_backend app

backend app
    balance random(2)                       # power of two random choices; or leastconn, roundrobin
    option httpchk
    http-check send meth GET uri /up
    http-check expect status 200
    cookie SRV insert indirect nocache httponly secure   # cookie affinity, only if you need it
    default-server check inter 2s fastinter 500ms fall 3 rise 2 slowstart 30s maxconn 200 observe layer7 error-limit 10 on-error mark-down
    server app1 10.0.1.11:8000 weight 100 cookie a1
    server app2 10.0.1.12:8000 weight 100 cookie a2
    server app3 10.0.1.13:8000 weight 100 cookie a3

backend cache_by_url
    balance uri path-only                   # URL hash for a cache tier
    hash-type consistent
    hash-balance-factor 150                 # bounded load: no server above 1.5x the average
    server c1 10.0.2.11:6081 check
    server c2 10.0.2.12:6081 check

listen postgres_ro
    mode tcp
    bind :5433
    balance leastconn                       # long-lived connections
    stick-table type ip size 200k expire 30m
    stick on src                            # source IP affinity at L4
    option tcp-check
    server pg1 10.0.3.11:5432 check inter 2s fall 3 rise 2
    server pg2 10.0.3.12:5432 check inter 2s fall 3 rise 2

# Runtime API: drain app2 before a deploy, then bring it back.
#   echo "set server app/app2 state drain" | socat stdio /run/haproxy/admin.sock
#   echo "set server app/app2 state ready" | socat stdio /run/haproxy/admin.sock
yaml
# Envoy cluster: least request (P2C), active health checks, outlier detection,
# slow start, panic threshold, and a ring hash variant keyed by a header.
clusters:
- name: app
  type: STRICT_DNS
  connect_timeout: 2s
  lb_policy: LEAST_REQUEST
  least_request_lb_config:
    choice_count: 2                  # P2C
    slow_start_config:
      slow_start_window: 30s
      aggression: { default_value: 1.0, runtime_key: app.slow_start.aggression }
  common_lb_config:
    healthy_panic_threshold: { value: 50.0 }   # below 50% healthy, balance across all
  health_checks:
  - timeout: 1s
    interval: 2s
    unhealthy_threshold: 3
    healthy_threshold: 2
    http_health_check: { path: /up }
  outlier_detection:
    consecutive_5xx: 5
    interval: 10s
    base_ejection_time: 30s
    max_ejection_percent: 10
  load_assignment:
    cluster_name: app
    endpoints:
    - lb_endpoints:
      - endpoint: { address: { socket_address: { address: app.internal, port_value: 8000 } } }
- name: sessions_by_user
  type: STRICT_DNS
  lb_policy: RING_HASH               # or MAGLEV
  ring_hash_lb_config: { minimum_ring_size: 1024, maximum_ring_size: 8388608 }
  load_assignment:
    cluster_name: sessions_by_user
    endpoints:
    - lb_endpoints:
      - endpoint: { address: { socket_address: { address: ws.internal, port_value: 8080 } } }
# On the route: hash_policy: [{ header: { header_name: x-user-id } }]
conf
# Active-passive pair of HAProxy nodes sharing one virtual IP (VRRP).
vrrp_script chk_haproxy {
    script "/usr/bin/pgrep -x haproxy"
    interval 1
    fall 2          # two failures -> KO
    rise 2
    weight -60      # 150 - 60 = 90 < 100: the backup takes over
}

vrrp_instance VI_1 {
    state MASTER            # BACKUP on the second node
    interface eth0
    virtual_router_id 51
    priority 150            # 100 on the second node
    advert_int 1
    unicast_peer {
        192.0.2.12          # the other node (clouds often block multicast)
    }
    virtual_ipaddress {
        192.0.2.10/24       # clients and DNS point here
    }
    track_script {
        chk_haproxy
    }
}
yaml
# Kubernetes: a Service (L4, kube-proxy), and Gateway API routing with a
# weighted canary. Ingress still works but the API is frozen.
apiVersion: v1
kind: Service
metadata:
  name: shop
spec:
  selector: { app: shop }
  ports: [{ port: 80, targetPort: 8000 }]
  # sessionAffinity: ClientIP          # source IP affinity, default timeout 10800 s
---
apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
  name: public
spec:
  gatewayClassName: example-lb         # provided by the controller (Envoy Gateway, NGINX Gateway Fabric, GKE...)
  listeners:
  - name: https
    protocol: HTTPS
    port: 443
    hostname: shop.example
    tls:
      mode: Terminate
      certificateRefs: [{ name: shop-example-tls }]
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: shop
spec:
  parentRefs: [{ name: public }]
  hostnames: [shop.example]
  rules:
  - matches: [{ path: { type: PathPrefix, value: / } }]
    backendRefs:
    - { name: shop, port: 80, weight: 90 }
    - { name: shop-canary, port: 80, weight: 10 }
---
# Pod spec fragment: fail readiness first, then let the LB drain, then stop.
# readinessProbe: { httpGet: { path: /ready, port: 8000 }, periodSeconds: 2, failureThreshold: 2 }
# lifecycle: { preStop: { exec: { command: ["php", "artisan", "lb:drain", "--wait=15"] } } }
# terminationGracePeriodSeconds: 45

The Laravel angle ​

  • withRouting(health: '/up') registers Laravel's built-in health route; the docs say it "will return a 200 HTTP response if the application has booted without exceptions. Otherwise, a 500 HTTP response will be returned". It also dispatches Illuminate\Foundation\Events\DiagnosingHealth, where you may check database or cache; doing so turns /up into a deep check, so keep that for monitors and point the balancer at a readiness route.
  • trustProxies(at: ..., headers: ...) is what makes $request->ip(), isSecure() and url() correct behind a balancer that terminates TLS. The docs name the symptom ("does not generate HTTPS links when using the url helper") and the AWS header set (Request::HEADER_X_FORWARDED_AWS_ELB). at: '*' is acceptable only when nothing but the balancer can reach the app.
  • trustHosts(at: [...]) takes regular expressions ("The hostname string is treated as a regular expression"), so escape dots.
  • Session drivers: file, cookie, database, memcached / redis, dynamodb, array. Behind a balancer file forces affinity (each server has its own disk); database or redis remove the need; cookie stores the session client-side (size-limited, encrypted).
  • Octane: the docs say to run Octane "behind a traditional web server such as Nginx or Apache" that serves static assets and handles "SSL certificate termination". Octane workers default to one per CPU core (--workers), are restarted after 500 requests (--max-requests), and octane:reload gracefully restarts workers after a deploy; HAProxy's per-server maxconn should not exceed what the workers can process concurrently.
  • Rate limiting by $request->ip() only works after TrustProxies; otherwise every user shares the balancer's address.
  • Queue workers and the scheduler are not behind the HTTP balancer; with several app servers, ->onOneServer() on scheduled tasks needs a shared cache lock.
  • The SQL below is the per-backend view of an access log imported into PostgreSQL (from NGINX $upstream_addr, $upstream_status, $upstream_response_time, or ALB access logs).
sql
CREATE TABLE lb_access_log (
  at             timestamptz NOT NULL,
  backend        text        NOT NULL,   -- NGINX $upstream_addr (last one if retried) / ALB target:port
  attempts       smallint    NOT NULL DEFAULT 1,
  status         smallint    NOT NULL,   -- status sent to the client
  backend_status smallint,               -- NGINX $upstream_status; NULL when no backend answered
  backend_ms     integer,                -- NGINX $upstream_response_time * 1000
  path           text        NOT NULL
);

-- Per-backend health over the last 15 minutes: find the hot or sick one.
SELECT backend,
       count(*)                                                        AS requests,
       round(100.0 * count(*) FILTER (WHERE backend_status >= 500) / count(*), 2) AS backend_5xx_pct,
       count(*) FILTER (WHERE status IN (502, 503, 504) AND backend_status IS NULL) AS lb_generated_errors,
       percentile_cont(0.99) WITHIN GROUP (ORDER BY backend_ms)        AS p99_ms,
       sum(attempts - 1)                                               AS retries
FROM lb_access_log
WHERE at > now() - interval '15 minutes'
GROUP BY backend
ORDER BY p99_ms DESC;

-- Imbalance: share of requests per backend vs the fair share.
SELECT backend,
       round(count(*)::numeric / sum(count(*)) OVER () * count(*) OVER (), 2) AS share_vs_fair  -- 1.00 = fair; count(*) OVER () = number of backends
FROM lb_access_log
WHERE at > now() - interval '15 minutes'
GROUP BY backend;

Solving the classic problems ​

A few 502s on every deploy ​

CauseFixAdvantageCost or limit
Process stopped before balancers stopped sendingFail readiness, wait interval x threshold + margin (lb:drain, preStop), then SIGTERMZero failed requestsSlower deploys
Deregistration delay shorter than the longest requestRaise it to just above p99.9 request time; bound long onesIn-flight work completesSlower scale-in
Backend keepalive shorter than balancer idle timeoutApp keepalive 65 s for ALB 60 s; Go IdleConnTimeout below backend'sNo idle-race RSTsMore idle sockets
No retry on connect failureproxy_next_upstream error, HAProxy option redispatch, Envoy retry_on: connect-failureHides the blip for safe requestsPOST still fails (correctly)

One server much hotter than the others ​

CauseFixAdvantageCost or limit
Round robin with uneven request costLeast outstanding requests or P2CLoad follows real workNeeds in-flight counters
Hash affinity on a skewed keyBounded-load consistent hashing, split hot keysKeeps locality for the restHot key loses locality
Long-lived L4 connections (gRPC, WebSocket)L7 or client-side balancing, max connection ageNew servers get trafficReconnect churn
Many balancers herding on least-connP2C (random(2), LEAST_REQUEST, random two)No herdingSlightly less optimal than global least-conn

Users logged out or carts emptied after a deploy or scale-in ​

CauseFixAdvantageCost or limit
Session in server memory or file driver plus sticky cookieSESSION_DRIVER=redis or database; drop affinityAny server serves any userRedis/DB round trip per request
Affinity needed for local cacheConsistent hashing on user id instead of a cookieSurvives resizes for most usersHot users still hot
Source IP affinity behind NATCookie or token based routingEven spreadRequires L7

The whole pool disappears when a dependency blips ​

CauseFixAdvantageCost or limit
Deep health check on shared databaseShallow or cached readiness for membership; deep checks for alertsNo self-inflicted outageDegraded responses instead of 503
Balancer without fail-openEnvoy panic threshold, cap ejection (max_ejection_percent), know ALB fail-openSome requests still succeedTraffic reaches unhealthy servers
Recovery takes minutesLower HealthyThresholdCount or intervalFaster returnMore probe traffic

New instances fall over as soon as they join ​

CauseFixAdvantageCost or limit
Cold caches, JIT, poolsSlow start (HAProxy slowstart, ALB, Envoy)Gradual loadNot with every algorithm (ALB: RR only)
Least-conn sends everything to the empty serverSlow start or P2CNo pile-on—
App reports ready before warmWarm up in the app before readiness turns greenWorks everywhereLonger startup

The load balancer is the single point of failure ​

CauseFixAdvantageCost or limit
One HAProxy/NGINX nodekeepalived VRRP pair with tracking scriptFailover in secondsStandby idle; flows lost on failover
Active-passive cannot scaleECMP or anycast to N balancers with consistent hashingHorizontal scaleRouting setup, BGP
Single regionGSLB / latency DNS + health, or anycastRegion failure survivableData replication is the hard part

Choosing ​

SituationChooseExtra techniqueReason
Stateless HTTP API, similar requestsL7 with round robinActive + passive checks, slow startSimple and good enough
HTTP with varying request costL7 least outstanding requests or P2COutlier detectionLoad follows work
Many independent balancers (mesh, sidecars)P2C on in-flight requestsOutlier detection, retry budgetsResists herding
Cache tier (Varnish, NGINX cache, Memcached)URL or key consistent hashingBounded loadHit ratio survives resizes
WebSocket / long connectionsLeast connections for new connectionsMax connection age, bounded drainConnections are the load
gRPC between servicesClient-side round_robin or meshServer MaxConnectionAgeL4 pins connections
Non-HTTP TCP/UDP (databases, MQTT, games)L4 (NLB, HAProxy mode tcp, IPVS)PROXY protocol or IP preservationNo HTTP to parse
Very high packet rates, big responsesL4 with DSR or Maglev-style ECMP fleetConsistent hashing + conntrackResponses bypass the balancer
Backend must own the TLS keyTLS passthrough with SNI routingPROXY protocol for client IPKey never leaves the backend
Multi-region active-activeGSLB/latency DNS + anycast or per-region L4/L7Short TTLs, regional healthDNS picks region, L7 picks server
Kubernetes HTTP ingress, new buildGateway API (HTTPRoute)Weighted backendRefs for canariesIngress API is frozen
Legacy app with in-memory sessionsCookie affinity as a stopgapPlan the move to a shared session storeAffinity breaks on failure

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

One Laravel application on two VMs behind one NGINX: upstream app { least_conn; server a; server b; }, passive checks with max_fails, sessions in the database. The first decisions already appear: where TLS ends (NGINX), which header carries the client IP (TrustProxies), where sessions live (not the local disk), and what NGINX does when both servers fail (no live upstreams, 502). The NGINX node itself is now the single point of failure; a keepalived pair or a managed balancer fixes that.

Modular monolith: boundaries without the network ​

Same codebase, several pools: the L7 balancer routes /api to an API pool, /admin to a small admin pool reachable only from the office network, and /reports to a pool with longer timeouts and least_conn, because one report must not occupy a worker that should be serving checkouts. This is load balancing used as a bulkhead (see Bulkheads & Graceful Degradation): per-pool timeouts, maxconn and queues keep one module's slowness from spreading.

Microservices: every arrow is a balancer ​

 1  browser -> Route 53 latency record -> eu-central-1 ALB (TLS, ACM)       DNS picks region
 2  ALB -> HTTPRoute via Envoy Gateway -> orders Service                    L7 picks pod, P2C
 3  orders (Go) -> inventory: gRPC client-side round_robin over headless Service   per-RPC
 4  orders -> payments: Envoy sidecar, outlier detection, retry_on connect-failure only
 5  payments -> PSP API: egress through forward proxy; Idempotency-Key on every capture
 6  orders -> PostgreSQL read pool: HAProxy mode tcp leastconn, writes to the primary only

Six hops, five balancers, each with its own algorithm, health signal and retry rule. The design questions that survive across services: who retries (one layer only, with budgets), which timeouts shrink inward, which calls are idempotent, and how draining is coordinated during deploys so each tier stops sending before the next tier stops listening. See Service Communication and Service Discovery.

Distributed data: replicas, caches, regions ​

Balancing in front of data is different because members are not interchangeable. Read replicas lag, so round robin across them breaks read-your-writes unless the app pins a user's reads to the primary for a while after a write (Replication & Failover). Caches and shards need key affinity, which means consistent hashing and planning for hot keys (Consistent Hashing, Caching). A connection-pooling proxy (PgBouncer) multiplexes connections but does not know which node is primary (Connection Pooling). Across regions, GSLB can move users in a minute but their data cannot follow that fast: active-active needs data that tolerates multi-region writes, otherwise failover is a data decision, not a DNS one.

Scaling path: 1x, 10x, 100x ​

LoadDesignWhat breaks firstFix
1x: hundreds of rpsOne NGINX or ALB, 2 to 4 app servers, RR or least_connDeploy 502s, balancer SPOF, file sessionsDraining, managed LB or keepalived, shared sessions
10x: thousands of rpsALB or HAProxy pair, autoscaling target groups, active + passive checks, slow startCold instances, hot backends, keepalive races, retry stormsSlow start, P2C/LOR, timer ordering, retry budgets
100x: tens of thousands of rps, multi-regionGSLB + anycast, L4 fleet (NLB/Maglev style) in front of L7 fleet (Envoy), mesh insideConfig sprawl, herding, connection counts, regional failover dataxDS control plane, P2C everywhere, subsetting, per-region capacity at N-1

Lab: algorithms, health checks and draining in one process ​

  1. Run the tests (single process, no network beyond localhost; this one was run):
cd docs/snippets/system-design/load-balancing/go
go test -count=1 -v ./...
--- PASS: TestSmoothWeightedRoundRobin (0.00s)
--- PASS: TestP2CAvoidsHotBackend (0.00s)
    balancer_test.go:123: ring hash moved 9.4% of keys
    balancer_test.go:153: maglev moved 0.19% of keys between surviving backends
    modhash_test.go:20: moved 90.4% of keys going from 10 to 9 backends
--- PASS: TestSafeRetryAndPassiveEjection (0.00s)
--- PASS: TestPostNotRetried (0.00s)
--- PASS: TestSlowBackendIs504 (0.30s)
--- PASS: TestDrainWaitsForInFlight (0.21s)
ok   academy/load-balancing/lbproxy
  1. Start two backends and the balancer (expected, not run). Any server with a /up route works; a Laravel app with php artisan serve --port=9001 and --port=9002 is enough.
go run ./cmd/lb -listen 127.0.0.1:8080 -algo rr \
  -backends a=http://127.0.0.1:9001,b=http://127.0.0.1:9002
2026/11/26 10:00:00 lb rr on 127.0.0.1:8080
for i in 1 2 3 4; do curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8080/; done
503      # first 2 s: no backend has passed rise=2 yet (Retry-After: 1)
200
200
200
  1. Kill backend b while sending GETs (expected, not run): requests keep returning 200 because the dial error is retried on a, and after 5 failures b is ejected for 30 s; after 3 failed probes it is marked down.

  2. Drain a backend (expected, not run):

echo a > /tmp/drain && kill -HUP $(pgrep -f 'cmd/lb')
2026/11/26 10:02:00 drain a: err=<nil>      # returned when a's in-flight requests reached 0
  1. Switch to -algo ring -hash-by header:X-Tenant and send curl -H 'X-Tenant: acme' repeatedly (expected, not run): every response comes from the same backend until that backend leaves the pool.

  2. Laravel side (expected, not run): php artisan lb:drain --wait=0 makes curl -i localhost:8000/ready return 503 {"status":"draining"} while /up stays 200; php artisan lb:drain --undo restores it.

Common misconceptions ​

BeliefReality
Round robin gives equal loadIt gives equal request counts; cost per request and server speed differ
Least connections is always bestWith many balancers or HTTP/2 it herds or misjudges; P2C on in-flight requests is the safer default
Hashing gives stable stickinessMod-N moves about (N-1)/N of keys on any resize; only consistent hashing moves about 1/N
An L4 balancer balances gRPCIt balances connections; one long-lived HTTP/2 connection pins a client to one server
A failed health check removes the server at onceDetection takes interval x threshold; ALB defaults are about a minute
Deep health checks are saferCorrelated failures remove the whole pool; keep membership checks shallow or cached
Retrying failed requests on another server is freeNon-idempotent requests may already have executed; retries multiply load
504 means the backend is downThe balancer's timer fired; the backend may still be doing the work
Sticky sessions are a scaling techniqueThey are a workaround for local state and break on deploys, failures and scale-in
DNS failover is instantResolvers cache for the TTL and some ignore it
Two balancers double capacityActive-passive has one node of capacity; active-active must survive N-1
TLS passthrough is strictly betterIt removes L7 features and the client IP; termination with re-encryption is usually the better trade
Kubernetes Ingress is deprecatedIt is frozen and supported; Gateway API is recommended for new work

Cheat sheet ​

TopicRemember
Default algorithmP2C or least outstanding requests at L7; round robin only for uniform requests
HashingNever mod-N for caches or shards; ring hash or Maglev, plus a bounded-load factor
L4 vs L7L4 balances flows (fast, protocol-agnostic); L7 balances requests (routing, retries, per-request metrics)
DNS / GSLBPicks a region, not a server; TTL bounds failover; keep TTLs short where it matters
Active checksInterval 2 to 10 s, fall 2 to 3, rise 2 to 3, cheap endpoint
Passive checksEject on consecutive errors, cap ejection (10%), un-eject on timer or active success
Deep vs shallowMembership: shallow or cached readiness; alerts: deep
DrainingFail readiness, wait detection time, SIGTERM; deregistration delay just above the longest request
Slow startLinear ramp 30 s for cold servers; HAProxy, ALB (RR only), Envoy, NGINX Plus
AffinityDesign it away (shared session store); if needed, hash a stable key consistently
TLSTerminate at L7, re-encrypt if the network is shared, pass through only when the backend must own the key
HAVRRP/keepalived pair or ECMP/anycast fleet; plan capacity for N-1
Timersclient > balancer > backend > dependency; backend keepalive > balancer idle timeout
502 / 503 / 504Bad response or connection / nowhere to send / timer fired
RetriesOnce, at one layer, connect failures and idempotent requests only; idempotency keys for the rest

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — Ten Envoy sidecars each use least connections against the same five backends. Why can that overload one backend, and what fixes it? Important ​

Answer

Answer: Each sidecar sees only its own in-flight requests, so all ten may simultaneously judge the same backend as least loaded and send it their next requests (herding). Power of two random choices on in-flight requests (Envoy LEAST_REQUEST with choice_count 2) avoids it, because each decision compares two random hosts and never converges on one.

2 — A cache tier of 10 servers uses hash $request_uri without consistent. You add an eleventh server. What happens to the hit ratio? Must-know ​

Answer

Answer: About 10/11 of URLs map to a different server, so most of the cache is effectively cold at once and the origin takes the miss storm. With hash $request_uri consistent (ketama) only about 1/11 of keys move.

3 — AWS ALB health checks use default settings. A target crashes. Roughly how long does it keep receiving requests, and how do you shorten that? Important ​

Answer

Answer: Interval 30 s and unhealthy threshold 2, plus the 5 s timeout: around a minute. Shorten the interval (down to 5 s) and threshold, and rely on retries or passive signals for the gap.

4 — Your health check runs SELECT 1 against the primary database. The database fails over for 20 seconds. What do HAProxy and ALB do? Important ​

Answer

Answer: Every server fails the check at once. HAProxy marks all servers down and returns 503 for every request until checks recover. ALB fails open (routes to all targets because all are unhealthy), but then recovery needs HealthyThresholdCount successes. The fix is a readiness check that does not depend on shared state, or caches it, with deep checks used for alerting.

5 — Put these in the right order for a zero-error deploy of one Pod: SIGTERM, readiness fails, endpoint removed from balancers, in-flight requests finish. Must-know ​

Answer

Answer: Readiness fails (or preStop starts the drain), balancers stop sending after their detection time, in-flight requests finish, then SIGTERM and exit. In Kubernetes endpoint removal and SIGTERM are concurrent, so a preStop sleep covers the gap.

6 — A client sends a POST, the balancer forwards it, the backend crashes before responding. What should NGINX do by default and why? Important ​

Answer

Answer: Return 502 without trying the next server: POST is non-idempotent and the request was already sent, so it may have executed. NGINX only passes it on with proxy_next_upstream non_idempotent. The client should retry with an idempotency key.

7 — Why do sporadic 502s appear when the backend's keepalive timeout is 5 s behind an ALB with a 60 s idle timeout? Must-know ​

Answer

Answer: The backend closes an idle pooled connection at 5 s; the ALB may send a new request on it just then and receive a RST or FIN, which it reports as 502. The backend's keepalive must be longer than the balancer's idle timeout.

8 — When is TLS passthrough the right choice, and what do you lose? Important ​

Answer

Answer: When the backend must hold the private key (regulation, tenants owning their certificates, client certificates validated by the app) or the protocol is not HTTP. You lose L7 routing, per-request balancing, retries, header insertion and WAF; the client IP needs PROXY protocol or IP preservation; routing is by SNI only.

9 — keepalived nodes have priorities 150 and 100 and a tracking script with weight -20. HAProxy dies on the master. Does the VIP move? Good to know ​

Answer

Answer: No. The master's priority drops to 130, still above 100, so it keeps the VIP while its HAProxy is dead. The weight must push it below the backup (for example -60), or use weight 0 so the instance enters FAULT state.

10 — A gRPC service behind a Kubernetes ClusterIP Service is scaled from 3 to 9 Pods, but the new Pods get no traffic. Why, and what are two fixes? Important ​

Answer

Answer: kube-proxy balances per connection and gRPC clients keep one long-lived HTTP/2 connection each, so they stay on the original Pods. Fixes: client-side round_robin over a headless Service (with server MaxConnectionAge to force periodic reconnects), or an L7 balancer or mesh sidecar that balances per request.

11 — Which status would you expect from HAProxy when every server's maxconn is reached and a request waits longer than timeout queue? Important ​

Answer

Answer: 503: HAProxy drops the queued request ("it is dropped and a 503 error is returned to the client"); the log shows termination state sQ.

Glossary ​

TermMeaning
Load balancerComponent that chooses, per connection or request, which of several equivalent servers handles it
Backend pool / upstream / target groupThe named set of servers behind one balancer route (NGINX upstream, HAProxy backend, Envoy cluster, AWS target group)
Round robinServers in turn
Weighted round robinRound robin where weight sets the share; smooth WRR interleaves picks
Least connectionsFewest open connections (or connections per weight) wins
Least outstanding requestsFewest in-flight requests wins (AWS ALB)
Least response timeLowest recent latency plus active connections (NGINX least_time, Traefik leasttime)
RandomUniformly random server
Power of two choices (P2C)Two random servers, keep the less loaded; resists herding
IP hash / source IP affinityClient address decides the server
URL hashRequest URI decides the server; maximises cache hit ratio
Consistent hashingMapping where resizing moves about 1/N of keys
Ring hash / KetamaConsistent hashing with servers at many points on a circle
Virtual nodeOne of many ring points for a server; evens out the ring
MaglevGoogle's L4 balancer and its lookup-table consistent hash (table size 65537 in Envoy)
Rendezvous hashing (HRW)Highest random weight per key-server pair wins (Traefik hrw)
Bounded loadConsistent hashing that caps any server at a factor of the average (HAProxy hash-balance-factor)
L4Transport-level balancing of TCP/UDP flows
L7Application-level balancing of HTTP/gRPC requests
NAT (load balancing)Balancer rewrites destination and source; replies return through it
DSR / direct server returnServer replies directly to the client; only inbound traffic crosses the balancer
IPVSLinux kernel L4 load balancer (LVS), managed by keepalived or kube-proxy
NLBAWS Network Load Balancer (L4, flow hash, static IPs)
ALBAWS Application Load Balancer (L7, target groups, listener rules)
HAProxyOpen source L4/L7 balancer with rich algorithms, stick tables and runtime API
NGINXWeb server and reverse proxy with upstream load balancing
EnvoyL4/L7 proxy with xDS dynamic configuration, used as sidecar and edge
TraefikReverse proxy with automatic discovery from Docker and Kubernetes
GSLBGlobal server load balancing: DNS answers chosen by location, latency and regional health
GeoDNS / latency routingDNS answers by resolver location or measured latency (Route 53)
AnycastMany sites announce the same IP; routing delivers to the nearest
ECMPEqual-cost multipath: routers hash flows across equal next hops (RFC 2992)
VIPVirtual IP shared by several machines, owned by whichever is active
Health checkTest of whether a server should receive traffic
Active health checkBalancer probes servers on a timer
Passive health checkBalancer judges servers by real traffic results
Outlier detectionEnvoy's passive check: eject hosts that behave unlike the others
EjectionTemporary removal of a host after passive failures
HysteresisDifferent thresholds to go down and come back, preventing flapping
Panic threshold / fail openWhen too few hosts are healthy, balance across all (Envoy 50%, ALB fail-open)
Liveness vs readinessShould it be restarted vs should it receive traffic
Draining / connection drainingNo new requests to a server, in-flight ones finish
Deregistration delayAWS ELB drain duration, default 300 s
Lame duckGoogle's term for a server that asks clients to stop sending while it finishes
Slow start / warm-upGradual ramp of a new server's share
Session affinity / sticky sessionSame client to same server
Cookie affinityStickiness via a balancer cookie (AWSALB, HAProxy cookie insert, NGINX sticky cookie)
Stick tableHAProxy in-memory table mapping keys (like source IP) to servers
TLS terminationBalancer decrypts TLS and holds the certificate
TLS passthroughBalancer relays encrypted bytes; backend decrypts
Re-encryptionBalancer decrypts, then opens new TLS to the backend
SNI routingChoosing a pool by the TLS ClientHello server name without decrypting
VRRPVirtual Router Redundancy Protocol (RFC 5798): election of the VIP owner
keepalivedLinux daemon implementing VRRP and IPVS health checking
Idle timeoutTime an idle connection is kept (ALB 60 s)
Max connections / queuePer-server concurrency limit and the wait line behind it (HAProxy maxconn, timeout queue)
502 / 503 / 504Bad gateway / service unavailable / gateway timeout, produced by the balancer
RetriesRe-sending a failed request to another server; safe only when idempotent or not yet sent
IdempotencyRepeating a request has the same effect as sending it once
Client-side load balancingThe caller picks the server per request (gRPC, libraries)
Service meshSidecar proxies doing client-side balancing, retries and mTLS for every service
SubsettingEach client uses only a subset of backends to bound connection counts
Hot backendOne server receiving disproportionate load
ORCAOpen Request Cost Aggregation: backend load reports for client-side weighting
xDS / EDSEnvoy's discovery APIs; EDS delivers endpoints and their health
Kubernetes ServiceStable virtual IP and L4 balancing to Ready Pods via kube-proxy
IngressFrozen Kubernetes L7 routing API
Gateway APIKubernetes routing API: GatewayClass, Gateway, HTTPRoute, TLSRoute, BackendTLSPolicy
PROXY protocolHeader that carries the original client address over an L4 hop

References ​

Built by Morteza Negahi