Implementing Load Balancing

1. Understanding WebSocket Load Balancing Challenges

ChallengeDetail
Long-livedConn pinned to backend; round-robin once
Upgrade requiredLB must support HTTP/1.1 Upgrade
Idle timeoutsLB may drop "idle" sockets
Uneven loadOld nodes accumulate connections

2. Using Sticky Sessions

Use CaseDetail
Local in-memory stateRequired
Redis-backed stateNot required
Auth-cookie basedCookie hash for pinning

3. Configuring Layer 4 Load Balancers

LBNotes
AWS NLBTCP/TLS passthrough; preserves source IP via PROXY proto
GCP NLBSimilar to NLB
HAProxy mode tcpFast, simple
Envoy TCP proxyModern, configurable

4. Configuring Layer 7 Load Balancers

Example: Nginx upstream

upstream ws_backend {
  ip_hash;
  server 10.0.0.1:8080;
  server 10.0.0.2:8080;
}
server {
  listen 443 ssl;
  location /ws {
    proxy_pass http://ws_backend;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_read_timeout 3600s;
    proxy_send_timeout 3600s;
  }
}
DirectivePurpose
proxy_http_version 1.1Required for Upgrade
Upgrade / ConnectionForward upgrade
proxy_read_timeoutAvoid idle drop

5. Implementing Client-Side Load Balancing

ApproachDetail
DNS round-robinMultiple A records
Discovery endpointHTTP returns WS host list
Geo-pickClosest edge
Failover listTry N hosts on connect failure

6. Using Connection Draining

PhaseDetail
Drain startLB stops sending new conns
Notify clientsClose 1001 in waves
Grace periode.g. 30s
Forced closeTerminate after grace

7. Handling Load Balancer Health Checks

TypeDetail
HTTP /healthzLiveness + readiness
TCP connectBasic; doesn't test app
WS ping endpointFull path validation

8. Implementing Geographic Routing

ToolDetail
AWS Route 53 latencyDNS-based geo
CloudflareAnycast + edge WS
Fly.io / regionsClosest region routing

9. Monitoring Connection Distribution

MetricThreshold
Conns / node±20% from mean
CPU / node< 70% sustained
FD usage< 80% ulimit
Conn age histogramDetect old-node accumulation

10. Testing Failover Scenarios

TestDetail
Drain one nodeVerify graceful reconnect to others
Kill node1006 + reconnect distribution
LB restartBrief outage tolerance
DNS failureCache TTL behavior