Implementing Load Balancing

1. Understanding Load Balancing Algorithms

AlgorithmBehaviorBest For
Round RobinSequential rotationHomogeneous backends
Least ConnectionsPick lowest active countLong-lived connections
Least Response TimePick fastest avg latencyHeterogeneous capacity
Weighted RRStatic weightsMixed capacity
IP / HashSticky by sourceCache locality
Random + 2-choicePick 2 random, choose lighterAvoids herd; near-optimal
EWMA / P2CExponentially-weighted moving avgLatency-aware (Finagle)

2. Implementing Weighted Load Balancing

Use CaseDetail
Heterogeneous nodesLarger instance gets higher weight
Canary release5% to new version, 95% to old
Cross-AZ preferenceSame-AZ weight higher

3. Implementing Consistent Hash Load Balancing

PropertyDetail
MechanismHash(key) → ring → node
Use caseCache affinity, session affinity
Bounded loadsBound max load via overflow
ExamplesEnvoy ring_hash, Maglev

4. Implementing Session Affinity (sticky sessions)

MethodDetail
CookieLB sets AWSALB / SERVERID
Source IP hashSame client → same backend
Token-basedHash header (e.g., user id)
Trade-offHot backends; complicates rolling deploys

5. Understanding Layer 4 vs Layer 7 Load Balancing

Layer 4 (TCP/UDP)

  • Routes by IP/port
  • No payload inspection
  • Faster, lower CPU
  • Examples: AWS NLB, IPVS, HAProxy TCP

Layer 7 (HTTP)

  • Routes by URL/headers/method
  • TLS termination
  • Retries, rewriting, auth
  • Examples: ALB, Envoy, NGINX, Traefik

6. Implementing Client-Side Load Balancing

LibraryDetail
gRPC name resolverPluggable; round-robin / pick-first
Spring Cloud LoadBalancerReplaces Ribbon
FinagleP2C, EWMA
Service mesh sidecarEnvoy applies LB locally

7. Implementing Server-Side Load Balancing

TypeExamples
HardwareF5, Citrix NetScaler
SoftwareNGINX, HAProxy, Envoy, Traefik
Cloud-managedALB, NLB, GCLB, Azure LB
Anycast (DNS/BGP)Cloudflare, Fastly

8. Handling Load Balancer Health Checks

KnobTuning
Interval5-30s
Timeout2-5s
Healthy threshold2-3 consecutive successes
Unhealthy threshold2-3 consecutive failures
PathLightweight, no deps

9. Implementing Dynamic Load Balancing

SignalAdjustment
Backend latencyReduce weight on slow nodes
Active connectionsSpread to lighter nodes
Auto-scaling eventsUpdate pool, drain old
Outlier detectionEject + retry (Envoy)

10. Understanding Load Shedding Strategies

StrategyDetail
Reject new requestsHTTP 503 + Retry-After
Priority sheddingDrop low-priority first
Adaptive concurrencyLimit based on observed latency (Netflix concurrency-limits)
Load-aware routingRoute around saturated nodes