For real-time communication between client and server, there are three main approaches, each with its own advantages and ideal use case. The choice depends on whether you need bidirectional communication, a unidirectional data stream, or just compatibility with older infrastructure. The right choice affects latency, scalability, and implementation complexity.
WebSocket¶
A fully duplex protocol — client and server can send data at any time over a single persistent TCP connection. After the initial HTTP handshake, the connection upgrades to WebSocket and remains open.
const ws = new WebSocket('wss://api.example.com/ws');
ws.onmessage = (e) => console.log(e.data);
ws.send('Hello');
WebSocket is ideal for scenarios with high-frequency messages in both directions — chat, multiplayer games, collaborative editors. Downside: more complex scaling (sticky sessions or Redis pub/sub for message distribution), reconnect logic must be handled explicitly, and load balancers must support WebSocket upgrade.
SSE¶
Server-Sent Events provide a unidirectional stream from server to client over standard HTTP. Simpler than WebSocket with automatic reconnect and native browser support.
const es = new EventSource('/events');
es.onmessage = (e) => console.log(e.data);
SSE is suitable for notifications, live feeds, dashboards, and streaming AI responses (LLM token streaming). It works over HTTP/2, requiring no special infrastructure. Limitations: server-to-client only and a maximum of 6 connections per domain in HTTP/1.1 (HTTP/2 resolves this with multiplexing).
Long Polling¶
Request -> server holds the connection until it has new data -> response -> client immediately sends a new request. Simulates push over standard HTTP.
The simplest to implement, works everywhere without special infrastructure. Higher latency and overhead from repeated HTTP requests. Suitable only as a fallback when neither WebSocket nor SSE are available.
When to Use What¶
- WebSocket — chat, games, collaboration, real-time trading (bidirectional, high frequency)
- SSE — notifications, feeds, dashboards, LLM streaming (unidirectional, server push)
- Long Polling — fallback for legacy environments
WebSocket for Duplex, SSE for Streaming¶
Long polling only as a fallback. For most modern applications, SSE is sufficient and simpler to implement than WebSocket.