WebSockets & Real-Time Communication
Polling, long polling, Server-Sent Events, WebSockets and WebRTC — how each works, when to use which, and how to scale real-time connections.
Plain HTTP is client-initiated: the server can only answer requests. Chat, live dashboards, notifications, multiplayer games and collaborative editors need the server to push data the moment something happens. There are several ways to do it.
The options
| Technique | Direction | How | Best for |
|---|---|---|---|
| Short polling | Client → server | Ask every N seconds | Rarely-changing data; simplest |
| Long polling | Server → client (emulated) | The server holds the request open until there's data, then the client immediately re-requests | Fallback where nothing else works |
| Server-Sent Events (SSE) | Server → client | One long-lived HTTP response streaming text/event-stream | Feeds, notifications, live logs, LLM token streaming |
| WebSocket | Both ways | HTTP upgrade to a persistent, full-duplex framed connection | Chat, games, collaboration, trading |
| WebRTC | Peer ↔ peer | UDP-based media and data channels with NAT traversal | Video and voice calls, P2P file transfer |
A WebSocket starts as HTTP, then both sides send frames at any time.
Server-Sent Events
SSE is just HTTP: the response never ends, and each event is a few lines of text. The browser's EventSource reconnects automatically and resumes from Last-Event-ID.
// Spring MVC
@GetMapping(path = "/events", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
SseEmitter events() {
SseEmitter emitter = new SseEmitter(0L); // no timeout
broadcaster.register(emitter); // send later with emitter.send(...)
return emitter;
}# FastAPI
from fastapi.responses import StreamingResponse
async def event_stream():
async for update in updates():
yield f"id: {update.id}\ndata: {update.json()}\n\n"
@app.get("/events")
async def events():
return StreamingResponse(event_stream(), media_type="text/event-stream")// Browser
const es = new EventSource("/events");
es.onmessage = (e) => render(JSON.parse(e.data));
// Node server
res.writeHead(200, { "Content-Type": "text/event-stream", "Cache-Control": "no-cache" });
setInterval(() => res.write(`data: ${JSON.stringify({ t: Date.now() })}\n\n`), 1000);WebSockets
// Jakarta WebSocket
@ServerEndpoint("/chat")
public class ChatEndpoint {
private static final Set<Session> sessions = ConcurrentHashMap.newKeySet();
@OnOpen public void open(Session s) { sessions.add(s); }
@OnClose public void close(Session s) { sessions.remove(s); }
@OnMessage public void message(String msg) {
for (Session s : sessions) s.getAsyncRemote().sendText(msg); // broadcast
}
}# websockets library (asyncio)
import asyncio, websockets
clients = set()
async def handler(ws):
clients.add(ws)
try:
async for msg in ws:
websockets.broadcast(clients, msg)
finally:
clients.discard(ws)
async def main():
async with websockets.serve(handler, "0.0.0.0", 8765):
await asyncio.Future()// Browser client with reconnect
function connect() {
const ws = new WebSocket("wss://example.com/chat");
ws.onmessage = (e) => show(JSON.parse(e.data));
ws.onclose = () => setTimeout(connect, 1000 + Math.random() * 2000); // backoff + jitter
return ws;
}Choosing
Scaling real-time systems
Persistent connections change how you scale:
- Connections are stateful: each server holds thousands of open sockets. Use event-driven servers (Node, Netty, Go, asyncio) rather than a thread per connection; one machine can hold hundreds of thousands of idle connections.
- Fan-out across servers: if Alice is connected to server 1 and Bob to server 2, server 1 must forward Alice's message. Use a pub/sub backbone (Redis Pub/Sub, NATS, Kafka) that every server subscribes to.
- Load balancers must support upgrades and long-lived connections; tune idle timeouts and send heartbeats (ping/pong) so dead connections are detected.
- Reconnection storms: when a server restarts, all its clients reconnect at once. Add jittered backoff, and drain connections gradually on deploys.
- Delivery guarantees: a socket drop loses in-flight messages. Use sequence numbers or message IDs so clients can resume, and persist messages that must not be lost.
A full example: Design a chat system.
Key takeaways
- HTTP alone can't push; polling, long polling, SSE, WebSockets and WebRTC fill the gap.
- SSE: simple one-way server push over HTTP with automatic reconnects.
- WebSockets: full-duplex frames after an HTTP 101 upgrade.
- WebRTC: peer-to-peer media and data over UDP with NAT traversal.
- Scale with event-driven servers, a pub/sub backbone, heartbeats and jittered reconnects.