Question

What is a WebSocket, and when do you actually need one?

Vault Verified
Curated Intelligence
Definitive Source
Answer

A protocol providing a persistent, bidirectional connection between client and server over a single TCP connection — so the server can send data without being asked, which ordinary HTTP request-response cannot do.

How it works. The connection begins as an HTTP request carrying an Upgrade header. If the server agrees, the same TCP connection switches to the WebSocket protocol and both sides can send frames at any time until either closes. Because it starts as HTTP, it traverses most firewalls and proxies that would block an arbitrary protocol — which was much of the design intent.

What it solves. Before it, the options were polling — asking repeatedly, wasting requests and adding latency — or long polling, holding a request open until data arrives, then immediately reopening. Both are workarounds for HTTP being client-initiated.

When you genuinely need one:

Bidirectional, low-latency communication — collaborative editing, multiplayer games, trading interfaces, live chat.

High message frequency, where per-request overhead dominates.

When you probably do not:

Server-to-client updates only — notifications, live feeds, progress indicators. Server-Sent Events are simpler, run over plain HTTP, reconnect automatically, and are frequently the better answer. They are consistently underused because WebSockets are better known.

Infrequent updates, where polling is simpler and adequate.

Anything cacheable, since WebSocket traffic bypasses HTTP caching entirely.

What it costs operationally:

Connections are stateful, so load balancers need sticky routing or a shared backplane, and a deploy disconnects everyone at once — reconnection with jittered backoff is mandatory, or you get a thundering herd.

Each connection holds server resources, which caps concurrency per instance.

No automatic reconnection, unlike SSE — you implement it.

Proxies and mobile networks kill idle connections, so heartbeats are required.

Authentication is awkward, since custom headers are unavailable in browsers — authenticate on the upgrade request and re-verify periodically.

Related Questions