WebSockets enable full-duplex, persistent connections between client and server — enabling real-time features like chat, live feeds, and collaborative editing without the overhead of repeated HTTP requests.
HTTP is a request-response protocol. To get updates, the client must ask. For real-time apps (chat, live scores, collaborative docs), this creates a dilemma:
WebSockets solve this properly.
WebSockets establish a single, persistent TCP connection that both the client and server can use to send messages at any time.
Client → Server: HTTP Upgrade request
Server → Client: 101 Switching Protocols
[Connection is now a WebSocket — bidirectional, persistent]
Pros:
Cons:
Best for: Chat, collaborative tools, live dashboards, multiplayer games, trading platforms
SSE is a simpler alternative for one-way server-to-client streaming over HTTP.
const source = new EventSource('/api/stream');
source.onmessage = (event) => console.log(event.data);
Pros:
Cons:
Best for: Live feeds, notifications, progress updates — where the client only needs to listen
This is the key challenge. Because WebSocket connections are persistent and stateful:
User A and User B are connected to different servers. User A sends a message — it arrives at Server 1, but User B is on Server 2.
Sticky Sessions: Route each user to the same server consistently (via load balancer IP hash). Simple but limits load balancing flexibility.
Pub/Sub Backplane: Servers publish messages to a shared channel (Redis Pub/Sub, Kafka). All servers subscribe and forward messages to their connected clients.
Server 1 (User A) → publish("room:chat", msg) → Redis
Redis → broadcast → Server 2 (User B) → User B receives msg
Dedicated WebSocket Service: Separate the WebSocket layer from business logic. Stateless WebSocket servers only handle connection management; business logic runs elsewhere.
| Need | Solution | |---|---| | Server-to-client updates | SSE | | Bidirectional real-time | WebSockets | | Infrequent updates, simple setup | Long polling | | Push notifications (mobile) | APNS / FCM |