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.

Intermediate 2 min readLesson 12 of 15

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

TechniqueDirectionHowBest for
Short pollingClient → serverAsk every N secondsRarely-changing data; simplest
Long pollingServer → client (emulated)The server holds the request open until there's data, then the client immediately re-requestsFallback where nothing else works
Server-Sent Events (SSE)Server → clientOne long-lived HTTP response streaming text/event-streamFeeds, notifications, live logs, LLM token streaming
WebSocketBoth waysHTTP upgrade to a persistent, full-duplex framed connectionChat, games, collaboration, trading
WebRTCPeer ↔ peerUDP-based media and data channels with NAT traversalVideo and voice calls, P2P file transfer
ClientServerGET /chat Upgrade: websocket, Sec-WebSocket-Key101 Switching Protocolsframe: {"msg":"hi"}frame: {"from":"bob","msg":"hey"}frame: ping / pong (keep-alive)
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;
}

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
    }
}

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.
clientsclientsWS server 1WS server 2Pub/SubRedis / NATS / Kafka

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.