WebSockets and real-time communication

Context

HTTP is request and response. That is the right default. WebSockets are a fit when both sides need to push data over one long-lived TCP connection without polling.

Typical cases: a browser UI that must reflect live state, a chat pane, a progress stream. They are not a substitute for a server-side event log. A broker such as Kafka solves a different problem (durable pub/sub between services). Do not collapse the two.

Why not always WebSockets

A persistent connection has cost: idle sockets, reconnect storms, proxy timeouts, and sticky routing. Older clients and some corporate proxies still break the upgrade. You then need a fallback (long-polling or Server-Sent Events) or you accept that those clients will not get the live path.

Security is not free. Use WSS. Authenticate the upgrade. Treat the socket as an API: validate payloads, enforce size limits, and do not trust origin headers alone.

Server-Sent Events are simpler when the server only pushes and the client never sends on that channel. HTTP/2 multiplexing makes many small requests cheaper than they were, which removes some of the old polling pain.

A minimal Java endpoint

The sketch below is a Java EE-style endpoint from 2023 (javax.websocket). It is a teaching example, not production code. A real service needs auth, backpressure, and a plan for fan-out.

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint("/chat")
public class ChatEndpoint {

    @OnOpen
    public void onOpen(Session session) {
        // register session
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        for (Session open : session.getOpenSessions()) {
            open.getAsyncRemote().sendText(message);
        }
    }

    @OnClose
    public void onClose(Session session) {
        // drop session
    }
}

The browser side is a WebSocket object, send on user action, append on onmessage, and handle onclose / onerror. That is the whole protocol surface most apps need.

Rule of thumb

Start with HTTP. Move to WebSockets when polling is measurable waste or the UX needs a push channel. Keep durable work on the server on an event log, not on a browser socket.

all blogs