Sticky sessions and load balancing for WebSocket servers
sticky session definition, IP hash load balancing, cookie-based affinity, Nginx upstream hash, AWS ALB stickiness, session affinity limitations, failover behavior
What Sticky Sessions Actually Do
Sticky sessions ensure a client always reconnects to the same backend server. The load balancer routes based on IP or a cookie. Configure Nginx:
upstream websocket_backend { ip_hash; # route same IP to same server server 10.0.0.1:3000; server 10.0.0.2:3000; server 10.0.0.3:3000; } server { listen 80; location /ws { proxy_pass http://websocket_backend; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "Upgrade"; proxy_set_header Host $host; proxy_read_timeout 3600s; # keep alive for 1 hour } }
Limitations of Sticky Sessions Alone
If a server crashes, all its clients lose their sticky affinity and reconnect to other servers โ losing in-memory state. Sticky sessions are not a substitute for a shared state layer (Redis). Use both: sticky sessions as the primary routing strategy to minimize cross-server traffic, Redis for broadcast and state recovery after failover. On AWS, use Application Load Balancer with duration-based stickiness and set the timeout longer than your WebSocket idle timeout.
