How do WebSockets work behind a load balancer?
Answer
WebSockets behind a load balancer require sticky sessions (session affinity) because the connection is persistent — once established with a specific server instance, all messages must go to the same instance. Standard round-robin load balancing breaks WebSocket connections. Solutions: (1) Sticky sessions by IP or cookie — NGINX (ip_hash), HAProxy (balance source), or AWS ALB (cookie-based stickiness) route the same client to the same backend. Requires configuring the load balancer. (2) Shared state via Redis — instead of sticky sessions, use a Redis pub/sub layer: each server instance subscribes to Redis channels and forwards relevant messages to its local clients. This is the recommended scalable approach. Socket.IO provides socket.io-redis adapter that handles this automatically. (3) WebSocket-aware proxies — NGINX and HAProxy support WebSocket proxying with the Upgrade header.
Previous
How do you authenticate WebSocket connections?
Next
What is Redis Pub/Sub and how does it help with WebSocket scaling?
More WebSockets & Real-time Questions
View all →- Intermediate How do you implement a WebSocket server in Node.js using the `ws` library?
- Intermediate What are Socket.IO rooms and namespaces?
- Intermediate How do you handle WebSocket reconnection logic?
- Intermediate What is the difference between Socket.IO and raw WebSockets?
- Intermediate How do you authenticate WebSocket connections?