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 for | Go to |
|---|---|
| The whole page in four tables | Everything in one minute |
| Why a balancer exists and the trade it makes | Why it exists |
| Karger, Mitzenmacher, ECMP, VRRP, Maglev history | Where it comes from |
| Pool, upstream, target group vocabulary | Backend pool |
| Round robin and weights | Round robin |
| Least connections, least outstanding requests | Least connections |
| Least response time, least_time | Least response time |
| Random and power of two choices | P2C |
| IP hash, URL hash, ring hash, Maglev | Hash-based balancing |
| NAT, DSR, IPVS, NLB | L4 load balancing |
| Host and path routing, ALB, Envoy | L7 load balancing |
| GSLB, GeoDNS, latency routing, anycast | DNS and global |
| Probes, intervals, thresholds | Active health checks |
| Outlier detection, ejection | Passive health checks |
| Deep vs shallow, panic threshold, fail open | What a health check should test |
| Deploys without errors | Draining |
| New servers that fall over | Slow start |
| Sticky sessions | Session affinity |
| Who holds the certificate | TLS at the balancer |
| The balancer as a single point of failure | High availability |
| 502 vs 503 vs 504, queues, idle timeout | Timeouts and limits |
| Safe retries | Retries and idempotency |
| gRPC, mesh, subsetting | Client-side load balancing |
| One server much hotter than the others | Hot backends |
| What to graph per backend | Observability |
| Service, Ingress, Gateway API | Kubernetes |
| NGINX, HAProxy, Envoy, Traefik, ALB, NLB, Cloudflare | Products |
| Knobs, defaults, status codes, log lines | Mechanics |
| Code | Go, Laravel |
| Production failures and their fixes | Solving the classic problems |
| Which balancer for which job | Choosing |
| Monolith to distributed system | In architecture |
| Something to run | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
Algorithms. What the balancer knows decides what it can do.
| Algorithm | In plain words | Wins when | Where you find it |
|---|---|---|---|
| Round robin | Next server in turn | Requests cost about the same, servers are equal | Default in NGINX, HAProxy roundrobin, AWS ALB, Envoy ROUND_ROBIN |
| Weighted round robin | In turn, but bigger servers get more turns | Mixed instance sizes, canary at 5% | NGINX weight=, HAProxy weight, IPVS wrr, Gateway API backendRefs.weight |
| Least connections | Server with the fewest open connections or requests | Request cost varies; long sessions | NGINX least_conn, HAProxy leastconn, ALB least_outstanding_requests, IPVS lc/wlc |
| Least response time | Fastest recent server with few active requests | Heterogeneous latency, one slow zone | NGINX least_time (open source since 1.31.0), Traefik leasttime |
| Random | Any server, uniformly | Many balancers, no health checks, no shared state | Envoy RANDOM, NGINX random, ALB weighted_random |
| Power of two choices (P2C) | Pick two at random, keep the less busy one | Many independent balancers; avoid herding | Envoy LEAST_REQUEST, HAProxy random(2), NGINX random two least_conn, Traefik p2c |
| IP hash / source hash | Same client IP, same server | L4 stickiness without cookies | NGINX ip_hash, HAProxy balance source, IPVS sh, Kubernetes sessionAffinity: ClientIP |
| URL hash | Same URL, same server | Cache tiers: maximise hit ratio | HAProxy balance uri, NGINX hash $request_uri consistent |
| Consistent hashing (ring hash) | Keys and servers on a circle; key goes clockwise | Caches, shards, sticky keys that must survive resizes | Envoy RING_HASH, NGINX hash ... consistent (ketama), HAProxy hash-type consistent |
| Maglev | Consistent hashing with a fixed lookup table | Very fast L4 balancing with minimal disruption | Google Maglev, Envoy MAGLEV, IPVS mh |
Layers. The layer decides the unit being balanced.
| Tier | Balances | Sees | Typical products |
|---|---|---|---|
| DNS / GSLB | Answers to name lookups (minutes, TTL bound) | Resolver address, EDNS client subnet, region health | AWS Route 53, Cloudflare Load Balancing, NS1, GeoDNS |
| Anycast + ECMP | Packets to the nearest site, flows to equal paths | IP routes, 5-tuple hash | Cloudflare, Google front ends, routers with BGP |
| L4 | TCP/UDP flows for their whole life | IPs, ports, sometimes TLS SNI | AWS NLB, Maglev, IPVS with keepalived, HAProxy mode tcp, NGINX stream |
| L7 | Individual HTTP/gRPC requests | Method, host, path, headers, cookies, status codes | AWS ALB, NGINX, HAProxy mode http, Envoy, Traefik, GCP external Application LB |
| Client-side | Requests from inside the caller | Full per-backend latency and errors | gRPC round_robin, Envoy sidecars in Istio, Finagle-style libraries |
Health, drain and warm-up knobs (defaults from each product's documentation).
| Concern | AWS ALB | HAProxy | Envoy | NGINX |
|---|---|---|---|---|
| Probe interval | 30 s (HealthCheckIntervalSeconds, instance/ip targets) | 2 s (inter) | interval (required) | 5 s (health_check, NGINX Plus) |
| Down after | 2 failures (UnhealthyThresholdCount) | 3 (fall) | unhealthy_threshold | 1 (fails) |
| Up after | 5 successes (HealthyThresholdCount) | 2 (rise) | healthy_threshold | 1 (passes) |
| Passive ejection | Automatic Target Weights anomaly mitigation (weighted random) | observe layer7, on-error | outlier_detection: 5 consecutive 5xx, 30 s base ejection, at most 10% | max_fails=1 fail_timeout=10s |
| Draining | Deregistration delay 300 s | set server ... state drain | Drain via EDS health status | drain (open source since 1.29.6) |
| Slow start | slow_start.duration_seconds (round robin only) | slowstart | slow_start_config | slow_start= (NGINX Plus) |
Who says what when it fails.
| Status | Produced by | Means | First check |
|---|---|---|---|
| 502 Bad Gateway | The balancer | Connection refused or reset, malformed response, backend closed a kept-alive connection, TLS handshake to the target failed | Backend crash or restart, keepalive timeout of the app shorter than the balancer's |
| 503 Service Unavailable | The balancer (or the app shedding) | No healthy or registered backend, queue full or queue timeout | Health check path, empty target group, HAProxy timeout queue |
| 504 Gateway Timeout | The balancer | Backend did not answer within the balancer's timer | Slow query, read timeout vs real work time, ALB idle timeout |
| 499 (NGINX log only) | Client side | Client gave up before the response | Client 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 only | Load-balanced pool |
|---|---|
| Capacity of one machine | Capacity grows by adding servers, if the app is stateless |
| A crash is an outage | A crash removes one server; the balancer routes around it |
| A deploy is downtime or a risky restart | Drain one server at a time, health-check, re-add |
| No per-request choice | Choice by load, latency, key, path, header |
| Nothing new to run | A new tier with its own HA, config, certificates, timers and failure modes |
| Client sees the real server | Client 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".
Three common misunderstandings, up front
- "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.
- "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.
- "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
| Date | Milestone | Source |
|---|---|---|
| 1997 | Consistent 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 2000 | RFC 2992 analyses ECMP next-hop selection; "hash-threshold" maps a flow hash to N regions of the key space | RFC 2992 |
| October 2001 | Mitzenmacher, The Power of Two Choices in Randomized Load Balancing: two choices give exponential improvement over one; three are only a constant factor better | IEEE TPDS 12(10) |
| March 2010 | RFC 5798, VRRP version 3 for IPv4 and IPv6, "designed to eliminate the single point of failure" of a static default router | RFC 5798 |
| 2016 | Google publishes Maglev (NSDI '16): ECMP to a fleet of software L4 balancers, consistent hashing plus connection tracking, DSR for responses | Eisenbud et al., NSDI 2016 |
| 2016 | The SRE Book documents Google's DNS + VIP front-end balancing, lame duck state, deterministic subsetting and weighted round robin | Google SRE Book, ch. 19 and 20 |
| Kubernetes v1.35 | kube-proxy ipvs mode deprecated; nftables mode recommended; the Ingress API frozen, Gateway API recommended | Kubernetes docs |
| NGINX 1.29.6 / 1.31.0 | sticky 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, removedReal 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.
| Product | Pool | Member | Membership source |
|---|---|---|---|
| NGINX | upstream block | server | Static, resolve (DNS, open source since 1.27.3) |
| HAProxy | backend | server | Static, server-template + DNS, Runtime API |
| Envoy | cluster | endpoint / host | Static, DNS, EDS (xDS) |
| AWS ELB | target group | target (instance, IP, Lambda, ALB) | Registration API, Auto Scaling, ECS/EKS controllers |
| Kubernetes | Service | EndpointSlice endpoint | Pod readiness |
| Traefik | service with loadBalancer.servers | server | Providers (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".
| Product | Plain | Weighted | Notes |
|---|---|---|---|
| NGINX | default | server ... weight=N | Smooth WRR; default weight 1 |
| HAProxy | balance roundrobin | weight 0..256 | static-rr for unlimited servers |
| Envoy | ROUND_ROBIN | endpoint load_balancing_weight | Locality-weighted variants |
| AWS ALB | round_robin (default) | Weighted target groups on the listener rule | Per-target weights via ATW only |
| IPVS | rr | wrr | Per connection, not per request |
| Kubernetes Gateway API | — | backendRefs[].weight | Split 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 detectionReal 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.
| Product | Directive | Counts | Caveat |
|---|---|---|---|
| NGINX | least_conn | Active connections per worker group (shared with zone) | Without zone each worker counts alone |
| HAProxy | balance leastconn | Established + queued connections | Dynamic weights, slow start works |
| AWS ALB | least_outstanding_requests | In-progress requests | Not combinable with slow start |
| Envoy | LEAST_REQUEST | Active requests; P2C when weights are equal | See P2C |
| IPVS | lc, wlc, sed, nq | Connections in the kernel table | Per 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 slowReal 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.
| Product | Mechanism | Availability |
|---|---|---|
| NGINX | least_time header / last_byte / inflight | Open source since 1.31.0, NGINX Plus before |
| NGINX | random two least_time=header | least_time method of random is NGINX Plus |
| Traefik | strategy: leasttime | Traefik service load balancer |
| Envoy | ClientSideWeightedRoundRobin with ORCA | Extension policy |
| IPVS | sed, nq | Kernel 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 serverReal 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".
| Product | P2C | Plain random |
|---|---|---|
| Envoy | LEAST_REQUEST with choice_count: 2 (default) | RANDOM |
| HAProxy | balance random(2) (2 is the default draw count) | balance random(1) |
| NGINX | random two least_conn | random |
| Traefik | strategy: p2c | — |
| AWS ALB | — | weighted_random (with ATW anomaly mitigation) |
| gRPC | Library-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 survivorsReal 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)".
| Product | Mod-N hash | Consistent hash | Bounded load |
|---|---|---|---|
| NGINX | hash $key, ip_hash | hash $key consistent (ketama) | — |
| HAProxy | hash-type map-based (default) | hash-type consistent | hash-balance-factor 150 |
| Envoy | — | RING_HASH, MAGLEV + route hash_policy | — |
| IPVS | sh, dh | mh (Maglev; kube-proxy sets mh-port) | — |
| Traefik | — | hrw (rendezvous) | — |
| AWS NLB | 5-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.
| Mode | Return path | Balancer state | Client IP at server | Limits |
|---|---|---|---|---|
| NAT | Through the balancer | Connection table | Yes (source untouched) | Balancer carries both directions |
| DR / DSR | Server to client | Optional | Yes | Same L2 segment; VIP on every server; no TLS or HTTP features |
| TUN / GRE | Server to client | Optional | Yes | MTU overhead; server must decapsulate |
| Full proxy (two TCP connections) | Through the balancer | Two sockets per flow | No, unless PROXY protocol or IP preservation | Most 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 configuredReal 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.
| Capability | AWS ALB | NGINX | HAProxy mode http | Envoy | Traefik |
|---|---|---|---|---|---|
| Host/path/header routing | Listener rules | server_name, location, map | ACLs, use_backend | Route table | Routers and rules |
| Per-request algorithm | RR, LOR, weighted random | RR, least_conn, random two, least_time, hash | All balance algorithms | RR, least request, ring hash, Maglev, random | wrr, p2c, hrw, leasttime |
| Retries | No configurable policy | proxy_next_upstream | retries, option redispatch, retry-on | Route retry_policy | retry middleware |
| Cookie affinity | AWSALB duration-based or application-based | sticky cookie (open source 1.29.6+) | cookie ... insert | Stateful session filter or hash on cookie | sticky.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 tooReal 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.
| Technique | Granularity | Failover speed | Knows user location | Products |
|---|---|---|---|---|
| DNS round robin (several A records) | Per resolver, random | TTL plus resolver behaviour | No | Any DNS |
| GeoDNS | Per resolver region | TTL | Approximate (resolver or ECS) | Route 53 geolocation, NS1, Cloudflare |
| Latency-based routing | Per resolver, measured latency | TTL | Via resolver | Route 53 latency, Azure Traffic Manager |
| GSLB with health | Per region pool | TTL plus probe interval | Yes, with steering | Cloudflare Load Balancing, F5 DNS |
| Anycast | Per packet to nearest site | BGP convergence (seconds) | Network topology | Cloudflare, 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 errorsReal 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.
| Product | Probe | Interval | Fall / rise | Timeout |
|---|---|---|---|---|
| AWS ALB | HTTP/HTTPS path, matcher codes | 30 s default (5..300) | 2 / 5 | 5 s |
| AWS NLB | TCP, HTTP, HTTPS | See NLB target group docs | Configurable | Configurable |
| HAProxy | check, option httpchk, tcp-check, agent-check | 2 s (inter) | 3 / 2 | timeout check, else inter |
| Envoy | HTTP, gRPC, TCP, Redis, Thrift | interval | unhealthy_threshold / healthy_threshold | timeout |
| NGINX Plus | health_check uri= interval= fails= passes= | 5 s | 1 / 1 | — |
| keepalived | HTTP_GET, SSL_GET, TCP_CHECK | delay_loop | Retries per checker | connect_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 everyoneReal 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.
| Product | Knob | Default | Unit |
|---|---|---|---|
| NGINX | max_fails / fail_timeout | 1 / 10 s | Failures in window, window = ejection |
| HAProxy | observe layer7 + error-limit + on-error | error-limit 10, on-error fail-check | Consecutive errors |
| Envoy | consecutive_5xx / base_ejection_time / max_ejection_percent | 5 / 30 s / 10% | Consecutive errors, growing ejection |
| Traefik | passiveHealthCheck | See Traefik docs | Failed requests |
| AWS ALB | ATW anomaly detection | Always on; mitigation opt-in | Deviation 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.
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 againReal 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 type | Tests | Use for | Risk |
|---|---|---|---|
| TCP connect | Port open | L4 pools, databases | Process accepting but wedged |
Shallow HTTP (/up) | App boots and answers | Liveness, LB default | Misses broken dependencies |
Readiness (/ready) | Not draining, local resources, cached dependency status | LB target health, Kubernetes readinessProbe | Must not fail fleet-wide together |
| Deep HTTP | Every dependency live | Dashboards and alerts, not LB membership | Correlated failure removes the whole pool |
Agent check (HAProxy agent-check) | Server reports its own weight or state | Load-aware weights, drain | Agent 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 terminatedReal 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.
| Product | Mechanism | Default | Bound |
|---|---|---|---|
| AWS ALB/NLB | deregistration_delay.timeout_seconds | 300 s | Completes early when the target has nothing in flight |
| HAProxy | Runtime API set server b/s state drain, agent-check "drain" | — | Until maint or removal |
| NGINX | server ... drain | — | Open source since 1.29.6 |
| Envoy | Endpoint health status DRAINING via EDS; listener drain on hot restart | — | drain_timeout |
| Kubernetes | Endpoint removed when Pod terminating; preStop; terminationGracePeriodSeconds | 30 s grace | Grace 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 againReal 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.
| Product | Knob | Curve | Restrictions |
|---|---|---|---|
| HAProxy | slowstart <time> | Linear, weight and maxconn | Not on startup; set inter smaller than slowstart |
| AWS ALB | slow_start.duration_seconds | Linear | Round robin only |
| Envoy | slow_start_config (window, aggression, min weight percent) | Configurable exponent | RR and least request |
| NGINX Plus | server ... slow_start=30s | From zero to nominal | Not with hash, ip_hash, random |
| Traefik / Kubernetes | Readiness gates, warm-up in the app | App-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 neededReal 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.
| Product | Cookie affinity | Source IP affinity | Caveats |
|---|---|---|---|
| AWS ALB | AWSALB (duration) or application cookie | — | Not with weighted_random; AWSALBCORS for CORS |
| AWS NLB | — | Target group sticky sessions by source IP | Docs warn: clients behind one NAT share a target |
| NGINX | sticky cookie, sticky route, sticky learn | ip_hash, hash $remote_addr consistent | sticky open source since 1.29.6 |
| HAProxy | cookie <name> insert | balance source, stick on src | Stick tables can sync between peers |
| Kubernetes Service | — | sessionAffinity: ClientIP | Default 10800 s |
| Envoy | Stateful session filter, hash_policy cookie | hash_policy source IP | Hash-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.
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.
| Mode | Balancer can | Balancer cannot | Certificates |
|---|---|---|---|
| Termination, HTTP upstream | Route, retry, WAF, compress, add headers | Prove encryption inside the network | Public cert on balancer |
| Re-encryption (HTTPS/mTLS upstream) | Everything above, plus encryption in transit | Avoid the second handshake cost | Public cert + internal CA on both |
| Passthrough with SNI routing | Choose pool by SNI, L4 balancing | See paths, headers, status codes | Cert on every backend |
| TLS offload at L4 (NLB TLS listener) | Decrypt non-HTTP protocols, balance flows | Route by HTTP content | Public 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).
| Model | Capacity | Failover | Connection survival | Example |
|---|---|---|---|---|
| Active-passive VRRP | One node | 1 to 3 advertisement intervals | Lost unless state synced | keepalived + HAProxy |
| Active-active ECMP | N nodes, plan N-1 | Route withdrawal (BFD/BGP, seconds) | Consistent hashing + conntrack | Maglev, IPVS fleets |
| Anycast multi-site | Global | BGP convergence | Lost for that site's flows | Cloudflare, Google front end |
| DNS across balancer nodes | N nodes | TTL | New connections only | AWS ALB node IPs |
| Managed | Provider-scaled | Provider-handled | Provider-specific | ALB, 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' timeoutReal 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.
| Status | AWS ALB cause | HAProxy cause | NGINX cause | Retry? |
|---|---|---|---|---|
| 502 | RST on connect, target closed during request, malformed response, deregistration delay elapsed | Empty, invalid or incomplete response (SH, SD flags) | Refused, reset, upstream prematurely closed, Plus queue full | Safe methods only |
| 503 | No registered or healthy-routable targets | No server available, connection refused after retries (SC), timeout queue (sQ) | no live upstreams reported as 502 by NGINX; 503 from limit_req or app | With backoff and Retry-After |
| 504 | Connect timeout 10 s, idle timeout while waiting for response | timeout server (sH) | proxy_read_timeout, proxy_connect_timeout | Outcome unknown: only idempotent |
| 460 / 499 | ALB 460: client closed before idle timeout | CD flags | 499 client closed | No |
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).
| Product | Retries what | Non-idempotent | Limit |
|---|---|---|---|
| NGINX | error timeout (+ listed codes) | Only with non_idempotent | proxy_next_upstream_tries, _timeout |
| HAProxy | Connection failures (retries, redispatch); retry-on for more | Only if configured in retry-on | retries count |
| Envoy | retry_on: connect-failure, 5xx, reset, retriable-status-codes ... | Per route decision | num_retries, retry budget, per_try_timeout |
| AWS ALB | No configurable retry policy | No | — |
Go lbproxy | Dial errors on idempotent body-less requests | Only with Idempotency-Key and no body | Attempts |
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 EDSReal 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.
| Approach | Where the algorithm runs | Pros | Cons |
|---|---|---|---|
| Proxy (central L4/L7) | Balancer fleet | Untrusted clients, one place for policy | Extra hop, balancer capacity |
| Thick client | Caller library | No hop, per-request decisions | Every language needs the library |
| Lookaside | External LB service + client | Central policy, no data hop | Extra protocol |
| Sidecar mesh | Per-pod proxy | Uniform policy, no library code | A proxy per pod, control plane |
| Subsetting | Client to a subset | Fewer connections | Uneven 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 onlyReal 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.
| Symptom | Likely cause | Fix |
|---|---|---|
| One server hot, its requests normal | Hot key under hash affinity | Bounded load, split key, replicate hot items |
| New servers idle after scale-out | Long-lived connections at L4 | Max connection age, L7 or client-side balancing |
| Failing server gets more traffic | Least-conn sinkhole | Outlier detection, count errors as load |
| Hot servers in one zone | Cross-zone disabled with uneven targets per zone | Enable cross-zone load balancing or balance targets per zone |
| Uneven with many balancers | Each balancer's own view, herding | P2C, 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, replaceReal 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.
| Signal | NGINX | HAProxy | Envoy | AWS ALB |
|---|---|---|---|---|
| Which backend served | $upstream_addr | %s server name in log | %UPSTREAM_HOST% | Access log target:port |
| Backend latency | $upstream_response_time, $upstream_header_time | Tc/Tr/Td timers | upstream_rq_time histogram | TargetResponseTime |
| Errors by origin | $upstream_status vs $status | Termination flags | Response flags UF, UT, UH | HTTPCode_Target_5XX vs HTTPCode_ELB_5XX |
| Health | Plus API / status | Stats page, show servers state | /clusters admin, membership_healthy | HealthyHostCount, 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 splitReal 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.
| Object | Layer | Balances | Notes |
|---|---|---|---|
| Service ClusterIP | L4 in-cluster | Connections to Ready Pods | iptables/nftables random; IPVS schedulers |
| Service LoadBalancer | L4 external | Cloud LB to nodes or Pods | externalTrafficPolicy: Local routes only to node-local endpoints |
| Ingress | L7 | Requests by host/path | Frozen API, controller-specific annotations |
| Gateway + HTTPRoute | L7 | Requests by host/path/header, weights | Role-oriented, portable |
| TLSRoute / Passthrough | L4 with SNI | Connections by SNI | Backend holds the key |
| Headless Service | DNS only | Nothing; clients balance | For 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
| Product | Layer | Algorithms | Health | Strength | Watch out |
|---|---|---|---|---|---|
| NGINX (open source) | L7, L4 via stream | RR, least_conn, ip_hash, hash [consistent], random [two], least_time (1.31.0+) | Passive only (max_fails) | Ubiquitous, fast, static files, TLS | Active checks, slow start, queue need NGINX Plus |
| NGINX Plus | L7, L4 | As above + least_time with random | Active health_check, mandatory | API reconfiguration, slow start | Licence |
| HAProxy | L4 (mode tcp) and L7 (mode http) | roundrobin, static-rr, leastconn, first, source, uri, url_param, hdr, random(n), hash | Active, agent, passive (observe) | Richest knobs, stick tables, runtime API | Config is code: review it |
| Envoy | L4 and L7, sidecar or edge | RR, least request (P2C), ring hash, Maglev, random, client-side WRR | Active, outlier detection, panic threshold | xDS dynamic config, mesh data plane | Complex config; use a control plane |
| Traefik | L7, L4 | wrr, p2c, hrw, leasttime | Active, passive | Auto-discovery from Docker/Kubernetes | Less fine-grained timers |
| AWS ALB | L7 | Round robin, least outstanding requests, weighted random | Target group checks, ATW | Managed, ACM certificates, Lambda targets | DNS-only addresses, 60 s idle timeout, no configurable retries |
| AWS NLB | L4 (TCP, UDP, TLS, QUIC) | Flow hash | TCP/HTTP/HTTPS checks | Static IPs, millions of requests per second, client IP preservation | Per-connection balancing |
| GCP / Azure LBs | L4 and L7, global and regional | Provider-specific | Provider checks | Global anycast front ends (GCP) | Provider semantics differ |
| Cloudflare Load Balancing | DNS/anycast GSLB + proxy | Steering policies, weights | Monitors per pool | Global health-based steering | Origin must trust Cloudflare ranges |
| IPVS + keepalived | L4 in kernel | rr, wrr, lc, wlc, sh, dh, lblc, mh ... | keepalived checkers | Very fast, NAT/DR/TUN | Operations burden, no L7 |
| Kubernetes kube-proxy | L4 per node | Random (iptables/nftables), IPVS schedulers | Pod readiness | Built in | Per connection |
Mechanics
The exact knobs
| Knob | Product | Default | What it controls |
|---|---|---|---|
weight= | NGINX server | 1 | Share in WRR, least_conn, hash |
max_fails / fail_timeout | NGINX server | 1 / 10 s | Passive check: failures in window; also the ejection time |
backup / down / drain | NGINX server | — | Spare server; permanently off; only bound requests (drain open source since 1.29.6) |
keepalive | NGINX upstream | 32 (local) since 1.29.7 | Idle upstream connections cached per worker |
hash $key consistent | NGINX upstream | — | Ketama ring (160 points per server, Cache::Memcached::Fast compatible) |
random two least_conn | NGINX upstream | — | P2C on connections |
proxy_next_upstream | NGINX | error timeout | Which failures pass the request to the next server |
balance | HAProxy backend | roundrobin | Algorithm |
inter / fall / rise | HAProxy server | 2000 ms / 3 / 2 | Active check pace and hysteresis |
slowstart | HAProxy server | off | Linear ramp of weight and maxconn after recovery |
maxconn + timeout queue | HAProxy | queue timeout = timeout connect if unset | Per-server concurrency; queued requests get 503 when it expires |
hash-type / hash-balance-factor | HAProxy | map-based / 0 | Consistent vs mod-N; bounded load |
lb_policy | Envoy cluster | ROUND_ROBIN | LEAST_REQUEST, RING_HASH, MAGLEV, RANDOM |
choice_count | Envoy least request | 2 | P2C draws |
consecutive_5xx / base_ejection_time / max_ejection_percent | Envoy outlier detection | 5 / 30 s / 10% | Passive ejection |
healthy_panic_threshold | Envoy | 50% | Below it, ignore health and use all hosts (or none) |
load_balancing.algorithm.type | AWS ALB target group | round_robin | least_outstanding_requests, weighted_random |
deregistration_delay.timeout_seconds | AWS ELB | 300 | Draining time |
slow_start.duration_seconds | AWS ALB | 0 (off) | Linear ramp |
| idle timeout | AWS ALB | 60 s | Close idle connections; backend keepalive must be longer |
sessionAffinityConfig.clientIP.timeoutSeconds | Kubernetes Service | 10800 | Source IP affinity lifetime |
advert_int / priority | keepalived VRRP | 1 s / per node | Failover pace and election |
Status codes and log lines
| Where | You see | Meaning |
|---|---|---|
| NGINX error log | no live upstreams while connecting to upstream | Every server in the group is marked failed: the client gets 502 |
| NGINX error log | connect() failed (111: Connection refused) while connecting to upstream | Nothing listening: 502, retried if proxy_next_upstream error |
| NGINX error log | upstream timed out (110: Connection timed out) while reading response header from upstream | proxy_read_timeout: 504 |
| NGINX access log | $upstream_addr = 10.0.1.11:8000, 10.0.1.12:8000 | The request was retried on a second server |
| HAProxy log | termination state sQ / SC / sH | Expired in queue (503) / server refused the connection (503 after retries) / timeout server before headers (504) |
| HAProxy stats | DRAIN, MAINT, DOWN 1/3 | Admin drain, maintenance, health transition (1 of 3 failures) |
| Envoy access log | UH, UF, UT, UO | No healthy upstream (503), connection failure, upstream timeout, overflow (circuit breaker) |
| AWS ALB metrics | HTTPCode_ELB_5XX_Count vs HTTPCode_Target_5XX_Count | Balancer-generated vs backend-generated errors |
| AWS ALB | HTTP 460 | Client closed the connection before the idle timeout |
Go httputil.ReverseProxy | http: proxy error: dial tcp ...: connect: connection refused | Default 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.
// 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))
}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.
// 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
}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
}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
}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))]
}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
}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))]
}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.
// 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
}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())
}
}
}// 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.ReverseProxyis the standard building block. UseRewrite(it receivesProxyRequestwithInandOut, and strips forwarding headers fromOutbefore calling you);SetURLpoints the request at the chosen backend andSetXForwardedwritesX-Forwarded-For,X-Forwarded-HostandX-Forwarded-Proto. Trust rules for those headers are in the proxies chapter.- The per-attempt backend travels in the request context:
Rewrite,ModifyResponseandErrorHandlerall read it.ErrorHandlerruns before anything is written to the client, which is what makes a retry on another backend possible;lbproxysignals "retry" by recording the error instead of writing a response. - Classify errors with
errors.As(err, &*net.OpError)andOp == "dial"(safe to retry: the request never reached the backend) andnet.Error.Timeout()orcontext.DeadlineExceeded(504, outcome unknown, never retried here). - Tune
http.Transport:MaxIdleConnsPerHostdefaults to 2, far too low for a proxy;ResponseHeaderTimeoutbounds the wait for headers (the 504 inTestSlowBackendIs504);IdleConnTimeoutmust 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/maphashis randomly seeded per process, so the code useshash/fnvwith a splitmix64 finaliser. math/rand/v2withrand.NewPCG(seed, ...)gives deterministic tests for P2C; in production seed from time or use the global functions.- Graceful shutdown:
http.Server.Shutdownstops accepting and waits for in-flight requests;signal.NotifyContextties SIGTERM to it. Drain the balancer's backends withPool.Drain, the server-side equivalent of AWS deregistration delay. - gRPC in Go:
grpc.NewClient("dns:///inventory.internal:50051", grpc.WithDefaultServiceConfig(cfg))withcfgset 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
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
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
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
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
// 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
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:
# 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;# 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# 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 } }]# 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
}
}# 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: 45The 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 dispatchesIlluminate\Foundation\Events\DiagnosingHealth, where you may check database or cache; doing so turns/upinto 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()andurl()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 balancerfileforces affinity (each server has its own disk);databaseorredisremove the need;cookiestores 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), andoctane:reloadgracefully restarts workers after a deploy; HAProxy's per-servermaxconnshould 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).
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
| Cause | Fix | Advantage | Cost or limit |
|---|---|---|---|
| Process stopped before balancers stopped sending | Fail readiness, wait interval x threshold + margin (lb:drain, preStop), then SIGTERM | Zero failed requests | Slower deploys |
| Deregistration delay shorter than the longest request | Raise it to just above p99.9 request time; bound long ones | In-flight work completes | Slower scale-in |
| Backend keepalive shorter than balancer idle timeout | App keepalive 65 s for ALB 60 s; Go IdleConnTimeout below backend's | No idle-race RSTs | More idle sockets |
| No retry on connect failure | proxy_next_upstream error, HAProxy option redispatch, Envoy retry_on: connect-failure | Hides the blip for safe requests | POST still fails (correctly) |
One server much hotter than the others
| Cause | Fix | Advantage | Cost or limit |
|---|---|---|---|
| Round robin with uneven request cost | Least outstanding requests or P2C | Load follows real work | Needs in-flight counters |
| Hash affinity on a skewed key | Bounded-load consistent hashing, split hot keys | Keeps locality for the rest | Hot key loses locality |
| Long-lived L4 connections (gRPC, WebSocket) | L7 or client-side balancing, max connection age | New servers get traffic | Reconnect churn |
| Many balancers herding on least-conn | P2C (random(2), LEAST_REQUEST, random two) | No herding | Slightly less optimal than global least-conn |
Users logged out or carts emptied after a deploy or scale-in
| Cause | Fix | Advantage | Cost or limit |
|---|---|---|---|
Session in server memory or file driver plus sticky cookie | SESSION_DRIVER=redis or database; drop affinity | Any server serves any user | Redis/DB round trip per request |
| Affinity needed for local cache | Consistent hashing on user id instead of a cookie | Survives resizes for most users | Hot users still hot |
| Source IP affinity behind NAT | Cookie or token based routing | Even spread | Requires L7 |
The whole pool disappears when a dependency blips
| Cause | Fix | Advantage | Cost or limit |
|---|---|---|---|
| Deep health check on shared database | Shallow or cached readiness for membership; deep checks for alerts | No self-inflicted outage | Degraded responses instead of 503 |
| Balancer without fail-open | Envoy panic threshold, cap ejection (max_ejection_percent), know ALB fail-open | Some requests still succeed | Traffic reaches unhealthy servers |
| Recovery takes minutes | Lower HealthyThresholdCount or interval | Faster return | More probe traffic |
New instances fall over as soon as they join
| Cause | Fix | Advantage | Cost or limit |
|---|---|---|---|
| Cold caches, JIT, pools | Slow start (HAProxy slowstart, ALB, Envoy) | Gradual load | Not with every algorithm (ALB: RR only) |
| Least-conn sends everything to the empty server | Slow start or P2C | No pile-on | — |
| App reports ready before warm | Warm up in the app before readiness turns green | Works everywhere | Longer startup |
The load balancer is the single point of failure
| Cause | Fix | Advantage | Cost or limit |
|---|---|---|---|
| One HAProxy/NGINX node | keepalived VRRP pair with tracking script | Failover in seconds | Standby idle; flows lost on failover |
| Active-passive cannot scale | ECMP or anycast to N balancers with consistent hashing | Horizontal scale | Routing setup, BGP |
| Single region | GSLB / latency DNS + health, or anycast | Region failure survivable | Data replication is the hard part |
Choosing
| Situation | Choose | Extra technique | Reason |
|---|---|---|---|
| Stateless HTTP API, similar requests | L7 with round robin | Active + passive checks, slow start | Simple and good enough |
| HTTP with varying request cost | L7 least outstanding requests or P2C | Outlier detection | Load follows work |
| Many independent balancers (mesh, sidecars) | P2C on in-flight requests | Outlier detection, retry budgets | Resists herding |
| Cache tier (Varnish, NGINX cache, Memcached) | URL or key consistent hashing | Bounded load | Hit ratio survives resizes |
| WebSocket / long connections | Least connections for new connections | Max connection age, bounded drain | Connections are the load |
| gRPC between services | Client-side round_robin or mesh | Server MaxConnectionAge | L4 pins connections |
| Non-HTTP TCP/UDP (databases, MQTT, games) | L4 (NLB, HAProxy mode tcp, IPVS) | PROXY protocol or IP preservation | No HTTP to parse |
| Very high packet rates, big responses | L4 with DSR or Maglev-style ECMP fleet | Consistent hashing + conntrack | Responses bypass the balancer |
| Backend must own the TLS key | TLS passthrough with SNI routing | PROXY protocol for client IP | Key never leaves the backend |
| Multi-region active-active | GSLB/latency DNS + anycast or per-region L4/L7 | Short TTLs, regional health | DNS picks region, L7 picks server |
| Kubernetes HTTP ingress, new build | Gateway API (HTTPRoute) | Weighted backendRefs for canaries | Ingress API is frozen |
| Legacy app with in-memory sessions | Cookie affinity as a stopgap | Plan the move to a shared session store | Affinity 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 onlySix 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
| Load | Design | What breaks first | Fix |
|---|---|---|---|
| 1x: hundreds of rps | One NGINX or ALB, 2 to 4 app servers, RR or least_conn | Deploy 502s, balancer SPOF, file sessions | Draining, managed LB or keepalived, shared sessions |
| 10x: thousands of rps | ALB or HAProxy pair, autoscaling target groups, active + passive checks, slow start | Cold instances, hot backends, keepalive races, retry storms | Slow start, P2C/LOR, timer ordering, retry budgets |
| 100x: tens of thousands of rps, multi-region | GSLB + anycast, L4 fleet (NLB/Maglev style) in front of L7 fleet (Envoy), mesh inside | Config sprawl, herding, connection counts, regional failover data | xDS control plane, P2C everywhere, subsetting, per-region capacity at N-1 |
Lab: algorithms, health checks and draining in one process
- 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- Start two backends and the balancer (expected, not run). Any server with a
/uproute works; a Laravel app withphp artisan serve --port=9001and--port=9002is 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
200Kill 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.
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 0Switch to
-algo ring -hash-by header:X-Tenantand sendcurl -H 'X-Tenant: acme'repeatedly (expected, not run): every response comes from the same backend until that backend leaves the pool.Laravel side (expected, not run):
php artisan lb:drain --wait=0makescurl -i localhost:8000/readyreturn503 {"status":"draining"}while/upstays 200;php artisan lb:drain --undorestores it.
Common misconceptions
| Belief | Reality |
|---|---|
| Round robin gives equal load | It gives equal request counts; cost per request and server speed differ |
| Least connections is always best | With many balancers or HTTP/2 it herds or misjudges; P2C on in-flight requests is the safer default |
| Hashing gives stable stickiness | Mod-N moves about (N-1)/N of keys on any resize; only consistent hashing moves about 1/N |
| An L4 balancer balances gRPC | It balances connections; one long-lived HTTP/2 connection pins a client to one server |
| A failed health check removes the server at once | Detection takes interval x threshold; ALB defaults are about a minute |
| Deep health checks are safer | Correlated failures remove the whole pool; keep membership checks shallow or cached |
| Retrying failed requests on another server is free | Non-idempotent requests may already have executed; retries multiply load |
| 504 means the backend is down | The balancer's timer fired; the backend may still be doing the work |
| Sticky sessions are a scaling technique | They are a workaround for local state and break on deploys, failures and scale-in |
| DNS failover is instant | Resolvers cache for the TTL and some ignore it |
| Two balancers double capacity | Active-passive has one node of capacity; active-active must survive N-1 |
| TLS passthrough is strictly better | It removes L7 features and the client IP; termination with re-encryption is usually the better trade |
| Kubernetes Ingress is deprecated | It is frozen and supported; Gateway API is recommended for new work |
Cheat sheet
| Topic | Remember |
|---|---|
| Default algorithm | P2C or least outstanding requests at L7; round robin only for uniform requests |
| Hashing | Never mod-N for caches or shards; ring hash or Maglev, plus a bounded-load factor |
| L4 vs L7 | L4 balances flows (fast, protocol-agnostic); L7 balances requests (routing, retries, per-request metrics) |
| DNS / GSLB | Picks a region, not a server; TTL bounds failover; keep TTLs short where it matters |
| Active checks | Interval 2 to 10 s, fall 2 to 3, rise 2 to 3, cheap endpoint |
| Passive checks | Eject on consecutive errors, cap ejection (10%), un-eject on timer or active success |
| Deep vs shallow | Membership: shallow or cached readiness; alerts: deep |
| Draining | Fail readiness, wait detection time, SIGTERM; deregistration delay just above the longest request |
| Slow start | Linear ramp 30 s for cold servers; HAProxy, ALB (RR only), Envoy, NGINX Plus |
| Affinity | Design it away (shared session store); if needed, hash a stable key consistently |
| TLS | Terminate at L7, re-encrypt if the network is shared, pass through only when the backend must own the key |
| HA | VRRP/keepalived pair or ECMP/anycast fleet; plan capacity for N-1 |
| Timers | client > balancer > backend > dependency; backend keepalive > balancer idle timeout |
| 502 / 503 / 504 | Bad response or connection / nowhere to send / timer fired |
| Retries | Once, at one layer, connect failures and idempotent requests only; idempotency keys for the rest |
Self-check: questions & answers
- 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
| Term | Meaning |
|---|---|
| Load balancer | Component that chooses, per connection or request, which of several equivalent servers handles it |
| Backend pool / upstream / target group | The named set of servers behind one balancer route (NGINX upstream, HAProxy backend, Envoy cluster, AWS target group) |
| Round robin | Servers in turn |
| Weighted round robin | Round robin where weight sets the share; smooth WRR interleaves picks |
| Least connections | Fewest open connections (or connections per weight) wins |
| Least outstanding requests | Fewest in-flight requests wins (AWS ALB) |
| Least response time | Lowest recent latency plus active connections (NGINX least_time, Traefik leasttime) |
| Random | Uniformly random server |
| Power of two choices (P2C) | Two random servers, keep the less loaded; resists herding |
| IP hash / source IP affinity | Client address decides the server |
| URL hash | Request URI decides the server; maximises cache hit ratio |
| Consistent hashing | Mapping where resizing moves about 1/N of keys |
| Ring hash / Ketama | Consistent hashing with servers at many points on a circle |
| Virtual node | One of many ring points for a server; evens out the ring |
| Maglev | Google'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 load | Consistent hashing that caps any server at a factor of the average (HAProxy hash-balance-factor) |
| L4 | Transport-level balancing of TCP/UDP flows |
| L7 | Application-level balancing of HTTP/gRPC requests |
| NAT (load balancing) | Balancer rewrites destination and source; replies return through it |
| DSR / direct server return | Server replies directly to the client; only inbound traffic crosses the balancer |
| IPVS | Linux kernel L4 load balancer (LVS), managed by keepalived or kube-proxy |
| NLB | AWS Network Load Balancer (L4, flow hash, static IPs) |
| ALB | AWS Application Load Balancer (L7, target groups, listener rules) |
| HAProxy | Open source L4/L7 balancer with rich algorithms, stick tables and runtime API |
| NGINX | Web server and reverse proxy with upstream load balancing |
| Envoy | L4/L7 proxy with xDS dynamic configuration, used as sidecar and edge |
| Traefik | Reverse proxy with automatic discovery from Docker and Kubernetes |
| GSLB | Global server load balancing: DNS answers chosen by location, latency and regional health |
| GeoDNS / latency routing | DNS answers by resolver location or measured latency (Route 53) |
| Anycast | Many sites announce the same IP; routing delivers to the nearest |
| ECMP | Equal-cost multipath: routers hash flows across equal next hops (RFC 2992) |
| VIP | Virtual IP shared by several machines, owned by whichever is active |
| Health check | Test of whether a server should receive traffic |
| Active health check | Balancer probes servers on a timer |
| Passive health check | Balancer judges servers by real traffic results |
| Outlier detection | Envoy's passive check: eject hosts that behave unlike the others |
| Ejection | Temporary removal of a host after passive failures |
| Hysteresis | Different thresholds to go down and come back, preventing flapping |
| Panic threshold / fail open | When too few hosts are healthy, balance across all (Envoy 50%, ALB fail-open) |
| Liveness vs readiness | Should it be restarted vs should it receive traffic |
| Draining / connection draining | No new requests to a server, in-flight ones finish |
| Deregistration delay | AWS ELB drain duration, default 300 s |
| Lame duck | Google's term for a server that asks clients to stop sending while it finishes |
| Slow start / warm-up | Gradual ramp of a new server's share |
| Session affinity / sticky session | Same client to same server |
| Cookie affinity | Stickiness via a balancer cookie (AWSALB, HAProxy cookie insert, NGINX sticky cookie) |
| Stick table | HAProxy in-memory table mapping keys (like source IP) to servers |
| TLS termination | Balancer decrypts TLS and holds the certificate |
| TLS passthrough | Balancer relays encrypted bytes; backend decrypts |
| Re-encryption | Balancer decrypts, then opens new TLS to the backend |
| SNI routing | Choosing a pool by the TLS ClientHello server name without decrypting |
| VRRP | Virtual Router Redundancy Protocol (RFC 5798): election of the VIP owner |
| keepalived | Linux daemon implementing VRRP and IPVS health checking |
| Idle timeout | Time an idle connection is kept (ALB 60 s) |
| Max connections / queue | Per-server concurrency limit and the wait line behind it (HAProxy maxconn, timeout queue) |
| 502 / 503 / 504 | Bad gateway / service unavailable / gateway timeout, produced by the balancer |
| Retries | Re-sending a failed request to another server; safe only when idempotent or not yet sent |
| Idempotency | Repeating a request has the same effect as sending it once |
| Client-side load balancing | The caller picks the server per request (gRPC, libraries) |
| Service mesh | Sidecar proxies doing client-side balancing, retries and mTLS for every service |
| Subsetting | Each client uses only a subset of backends to bound connection counts |
| Hot backend | One server receiving disproportionate load |
| ORCA | Open Request Cost Aggregation: backend load reports for client-side weighting |
| xDS / EDS | Envoy's discovery APIs; EDS delivers endpoints and their health |
| Kubernetes Service | Stable virtual IP and L4 balancing to Ready Pods via kube-proxy |
| Ingress | Frozen Kubernetes L7 routing API |
| Gateway API | Kubernetes routing API: GatewayClass, Gateway, HTTPRoute, TLSRoute, BackendTLSPolicy |
| PROXY protocol | Header that carries the original client address over an L4 hop |
References
- NGINX, Using nginx as HTTP load balancer: https://nginx.org/en/docs/http/load_balancing.html
- NGINX, Module ngx_http_upstream_module: https://nginx.org/en/docs/http/ngx_http_upstream_module.html
- NGINX, Module ngx_http_proxy_module (
proxy_next_upstream): https://nginx.org/en/docs/http/ngx_http_proxy_module.html - NGINX, HTTP Health Checks (NGINX Plus, slow start): https://docs.nginx.com/nginx/admin-guide/load-balancer/http-health-check/
- HAProxy 3.2, Configuration Manual (
balance,hash-type,hash-balance-factor,fall,rise,inter,slowstart,timeout queue,cookie,stick on,on-error): https://docs.haproxy.org/3.2/configuration.html - HAProxy, The PROXY protocol: https://www.haproxy.org/download/1.8/doc/proxy-protocol.txt
- Envoy, Supported load balancers: https://www.envoyproxy.io/docs/envoy/latest/intro/arch_overview/upstream/load_balancing/load_balancers
- Envoy, Outlier detection: https://www.envoyproxy.io/docs/envoy/latest/intro/arch_overview/upstream/outlier
- Envoy, OutlierDetection API (defaults): https://www.envoyproxy.io/docs/envoy/latest/api-v3/config/cluster/v3/outlier_detection.proto
- Envoy, Health checking: https://www.envoyproxy.io/docs/envoy/latest/intro/arch_overview/upstream/health_checking
- Envoy, HealthCheck API: https://www.envoyproxy.io/docs/envoy/latest/api-v3/config/core/v3/health_check.proto
- Envoy, Slow start mode: https://www.envoyproxy.io/docs/envoy/latest/intro/arch_overview/upstream/load_balancing/slow_start
- Envoy, Panic threshold: https://www.envoyproxy.io/docs/envoy/latest/intro/arch_overview/upstream/load_balancing/panic_threshold
- Traefik, Service load balancing: https://doc.traefik.io/traefik/reference/routing-configuration/http/load-balancing/service/
- Eisenbud et al., Maglev: A Fast and Reliable Software Network Load Balancer, NSDI 2016: https://www.usenix.org/system/files/conference/nsdi16/nsdi16-paper-eisenbud.pdf (abstract: https://research.google/pubs/maglev-a-fast-and-reliable-software-network-load-balancer/)
- Mitzenmacher, The Power of Two Choices in Randomized Load Balancing, IEEE TPDS 12(10), 2001: https://www.eecs.harvard.edu/~michaelm/postscripts/tpds2001.pdf
- Google SRE Book, ch. 19 Load Balancing at the Frontend: https://sre.google/sre-book/load-balancing-frontend/
- Google SRE Book, ch. 20 Load Balancing in the Datacenter: https://sre.google/sre-book/load-balancing-datacenter/
- AWS, Edit target group attributes for your Application Load Balancer (deregistration delay, routing algorithm, slow start, sticky sessions, ATW): https://docs.aws.amazon.com/elasticloadbalancing/latest/application/edit-target-group-attributes.html
- AWS, Health checks for Application Load Balancer target groups: https://docs.aws.amazon.com/elasticloadbalancing/latest/application/target-group-health-checks.html
- AWS, Troubleshoot your Application Load Balancers (HTTP 460, 502, 503, 504): https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-troubleshooting.html
- AWS, Application Load Balancers (idle timeout): https://docs.aws.amazon.com/elasticloadbalancing/latest/application/application-load-balancers.html
- AWS, What is a Network Load Balancer? (flow hash): https://docs.aws.amazon.com/elasticloadbalancing/latest/network/introduction.html
- AWS, Edit target group attributes for your Network Load Balancer (client IP preservation, sticky sessions): https://docs.aws.amazon.com/elasticloadbalancing/latest/network/edit-target-group-attributes.html
- AWS, Health checks for Network Load Balancer target groups: https://docs.aws.amazon.com/elasticloadbalancing/latest/network/target-group-health-checks.html
- AWS, Latency-based routing (Route 53): https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/routing-policy-latency.html
- Cloudflare, Load Balancing: https://developers.cloudflare.com/load-balancing/
- Kubernetes, Service: https://kubernetes.io/docs/concepts/services-networking/service/
- Kubernetes, Virtual IPs and Service Proxies (kube-proxy modes, IPVS schedulers, session affinity): https://kubernetes.io/docs/reference/networking/virtual-ips/
- Kubernetes, Ingress (API frozen): https://kubernetes.io/docs/concepts/services-networking/ingress/
- Kubernetes, Gateway API: https://kubernetes.io/docs/concepts/services-networking/gateway/
- Gateway API, TLS configuration (Terminate, Passthrough, BackendTLSPolicy): https://gateway-api.sigs.k8s.io/guides/tls/
- keepalived, Introduction: https://keepalived.readthedocs.io/en/latest/introduction.html
- keepalived, Configuration synopsis (
lb_algo,lb_kind,vrrp_instance): https://keepalived.readthedocs.io/en/latest/configuration_synopsis.html - keepalived, keepalived.conf(5) source (
vrrp_script,weight,rise,fall): https://raw.githubusercontent.com/acassen/keepalived/master/doc/man/man5/keepalived.conf.5.in - RFC 5798, Virtual Router Redundancy Protocol (VRRP) Version 3: https://www.rfc-editor.org/rfc/rfc5798.html
- RFC 2992, Analysis of an Equal-Cost Multi-Path Algorithm: https://www.rfc-editor.org/rfc/rfc2992.html
- gRPC, gRPC Load Balancing: https://grpc.io/blog/grpc-load-balancing/
- Go, package net/http/httputil: https://pkg.go.dev/net/http/httputil
- Laravel 13, HTTP Requests (trusted proxies, trusted hosts): https://laravel.com/docs/13.x/requests
- Laravel 13, Deployment (health route): https://laravel.com/docs/13.x/deployment
- Laravel 13, HTTP Session (drivers): https://laravel.com/docs/13.x/session
- Laravel 13, Octane: https://laravel.com/docs/13.x/octane
- Laravel 13, Artisan Console (command attributes): https://laravel.com/docs/13.x/artisan