Skip to content

Note WebSockets

All posts
Nov 01, 20269 min readWebSockets · real-time · HTTP · web development · networkingRead in:ENID

WebSockets Explained: How Real-Time Apps Actually Work

WebSockets turn an HTTP request into a persistent two-way channel, so chat, games, and live dashboards update the moment data changes.

A glowing neon digital tunnel with streams of light, suggesting real-time data flowing both ways.

Most of the web works like ordering at a counter: you ask, you wait, you get an answer, and the conversation ends. That model is fine for loading a page, but it breaks down for a chat app, a live stock ticker, or a multiplayer game, where new information can arrive at any moment. WebSockets solve that problem by keeping one connection open so either side can send a message the instant it has one.

A WebSocket starts life as an ordinary HTTP request, then upgrades into a persistent, full-duplex channel over a single TCP connection (IETF). Once that upgrade succeeds, client and server can exchange messages in both directions without repeating the request and response dance. That is the whole idea, and everything else in this article is a consequence of it.

Key Takeaways

A WebSocket is a persistent, full-duplex connection: either side can send at any time, over one TCP connection.

It starts with an HTTP upgrade handshake and switches to lightweight message framing once the server answers 101 Switching Protocols.

Compared with polling, WebSockets remove most of the repeated request overhead, with frames as small as 2 to 14 bytes.

Server-Sent Events are a simpler fit when data only flows from server to client; WebSockets win when both sides must talk.

WebSockets are stateful, so scaling them takes more planning than scaling stateless HTTP requests.

What Is a WebSocket?

The WebSocket protocol, standardized as RFC 6455 in December 2011, defines an opening handshake followed by basic message framing, layered over TCP (IETF). The browser's WebSocket API describes it in plain terms: it makes it possible to open a two-way interactive communication session between a browser and a server, and to send messages and receive responses without having to poll the server for a reply (MDN Web Docs).

Three words carry most of the meaning:

  • Persistent. The connection stays open after the handshake instead of closing after each exchange.

  • Full-duplex. Messages can travel in both directions at the same time, independently. The client does not have to wait for a reply before sending again, and the server does not have to wait to be asked.

  • Lightweight. Once the connection is open, each message is wrapped in a small frame rather than a full HTTP request with headers. That framing is about 2 to 14 bytes per message, against typically 200 to 2000 bytes of HTTP header overhead per exchange (Render).

WebSockets run over TCP on port 80 or 443, the same ports as ordinary web traffic, which helps them pass through networks that would block an unfamiliar port (Ably). The secure variant uses the `wss://` scheme, just as HTTPS uses `https://`.

If you have read our guide to REST APIs, the contrast is the point: REST is a clean request and response model for fetching and changing resources, while WebSockets are a conversation model for data that keeps changing.

How the Handshake Works

A WebSocket connection does not start from scratch. It borrows HTTP for the introduction, then switches protocols. The lifecycle has four phases: handshake, open, message exchange, and termination (Render).

  1. The client asks to upgrade. The browser sends an HTTP request with `Upgrade: websocket`, a `Sec-WebSocket-Key` nonce, and `Sec-WebSocket-Version: 13` (IETF). In the browser, the key is added automatically, so application code never has to generate it (MDN Web Docs).

  2. The server accepts. A server that supports WebSockets answers `HTTP/1.1 101 Switching Protocols` with a `Sec-WebSocket-Accept` value calculated from the client's key (IETF). That calculation proves the server understood the handshake rather than answering blindly.

  3. The connection is open. From here on, HTTP semantics are gone. Both sides exchange WebSocket frames: text frames, binary frames, and small control frames such as ping, pong, and close.

  4. Either side can close. A close frame ends the exchange cleanly, and the underlying TCP connection is released.

Because the handshake is HTTP, a WebSocket URL starts with `ws://` or `wss://`, and the first request looks familiar to proxies and load balancers. That familiarity is deliberate: the protocol was designed to work over the web's existing infrastructure rather than demanding a new one.

WebSockets vs Polling vs Server-Sent Events

Before WebSockets, developers faked real-time behavior with polling. Understanding those older tricks makes the WebSocket advantage concrete.

Aspect

Short polling

Long polling

Server-Sent Events (SSE)

WebSockets

Direction

Client asks, server answers

Client asks, server answers

Server to client only

Both directions

How it works

Client asks on a timer

Server holds the request until data arrives or a timeout is reached

One HTTP stream of text events

One persistent full-duplex socket

Overhead per update

A full HTTP request each time

A full HTTP request per update

Low, one stream

Very low, frames of about 2 to 14 bytes

Reconnect

Manual, next poll

Manual, next request

Built in, with Last-Event-ID replay

Manual, you implement it

Best for

Data that changes rarely

Occasional updates on old infrastructure

Live feeds, notifications, progress

Chat, games, collaboration

Short polling asks on a timer, long polling holds the request until data arrives, SSE is one HTTP stream for server to client text events with auto-reconnect built in, and WebSockets are one full-duplex socket that is binary capable (Back4app). The cost of polling scales badly: 1,000 clients polling every 2 seconds means 500 requests per second even when nothing has changed, while a push connection at rest makes zero requests (Back4app).

SSE deserves a closer look because it is often the right answer. Compared with WebSocket, `EventSource` is one-directional, only the server sends data, and it carries only text over regular HTTP, while WebSocket is bidirectional and carries binary and text data (javascript.info). SSE also reconnects automatically and sends `Last-Event-ID` so the server can resend missed messages, something WebSocket code must implement by hand (javascript.info).

The rule of thumb is simple. If only the server has news, SSE is simpler and it is ordinary HTTP, so it fits CDNs, proxies, and stateless servers more easily. If the client also sends frequent updates, like keystrokes, cursor positions, or game moves, WebSockets are the natural fit. If updates are rare and latency does not matter, plain polling or a normal API call is fine, and adding a persistent connection is overengineering.

Long polling is worth knowing about because you will still meet it in older systems. It holds a client connection open for as long as possible, delivers a response only after data becomes available or a timeout is reached, and then the client usually issues another request immediately (WebSocket.org). It reduces empty replies compared with short polling, but each update still costs a new HTTP request.

Where WebSockets Are Used

WebSocket use cases cluster wherever latency matters and both sides talk. Listed realtime uses include live chat, multiplayer gaming, collaborative document editing, IoT device updates, and financial dashboards (Ably). Chat, collaborative editing, live dashboards, and multiplayer games are cases needing sub-100ms message delivery (Render).

A few concrete examples make the pattern clear:

  • Chat and support. A message sent by one user appears for others without anyone refreshing. Typing indicators and read receipts are just more messages on the same connection.

  • Collaborative editing. When several people edit one document, each keystroke or cursor move is a small message. WebSocket.org lists multiple people editing the same document simultaneously among the classic use cases (WebSocket.org).

  • Live dashboards and trading. Prices, scores, and sensor readings stream in as they change. Live sports updates and realtime dashboards appear in the same list (WebSocket.org).

  • Multiplayer games. Player positions and actions must travel both ways with minimal delay, which is exactly what a full-duplex socket provides.

  • IoT and device control. A dashboard can both receive sensor data and send commands back over one connection.

The common thread is not the industry, it is the shape of the data: frequent, small, bidirectional, and time sensitive.

The Trade-Offs Nobody Mentions

WebSockets are not free, and the costs show up in production rather than in demos.

Statefulness changes scaling. An HTTP request can be handled by any server behind a load balancer. A WebSocket connection lives on one specific server for its whole lifetime, so scaling out means tracking which server holds which connection, and a server restart drops its connections. Clients must reconnect, and your code must handle that.

Reconnect and state recovery are your job. Unlike SSE, WebSockets have no built-in replay of missed messages. If a connection drops, the client reconnects and must ask what it missed, or the server must resend it. Design that recovery path early, not after users report missing messages.

Proxies and firewalls can interfere. Because the handshake upgrades an HTTP connection, most modern proxies handle it, but older or strictly configured ones may close idle connections or refuse the upgrade. Heartbeat ping and pong frames keep idle connections alive and detect dead ones.

Security works like the rest of the web, with one extra step. Use `wss://` in production so frames are encrypted like HTTPS traffic. Authentication still matters: the handshake is an HTTP request, so cookies and tokens can be checked there, but the server must verify them before answering 101, not after the socket is open. And like any input channel, message contents must be validated, because a persistent socket is a persistent attack surface.

Not every problem is real-time. A blog, a product page, or a settings form gains nothing from a socket. The decision question is always: does new data arrive unpredictably, and does the user need it within a second or two? If the answer is no, a normal request is simpler, cheaper, and easier to cache.

When to Choose What

Use this short decision guide when you are picking a transport:

  • Need instant updates in both directions? Choose WebSockets. Chat, games, and collaborative tools live here.

  • Only the server sends updates? Choose Server-Sent Events. Live feeds, notifications, and build progress are simpler over SSE.

  • Updates are rare or latency tolerant? Choose plain HTTP requests, or polling on a generous interval. Do not pay the stateful scaling cost for data that changes once an hour.

  • Building on infrastructure that cannot hold long connections? Stick with HTTP and polling, or put a managed realtime service in front of your app.

WebSockets earned their place because they match how interactive apps actually behave: people type, move, react, and expect the other side to see it now. The protocol is old enough to be boring, standardized in 2011 via RFC 6455 (WebSocket.org), and supported everywhere modern browsers run. That boring reliability is the point. You are not adopting an experiment, you are using the web's standard answer to the question of how two sides keep talking.

Baca juga versi Bahasa Indonesia dari artikel ini: WebSockets Dijelaskan: Cara Kerja Aplikasi Realtime.

Frequently Asked Questions

Are WebSockets faster than HTTP?

For repeated updates, yes, dramatically. An established WebSocket frame costs about 2 to 14 bytes, while each HTTP exchange carries typically 200 to 2000 bytes of headers (Render). For a single request, HTTP is just as fast, and simpler.

Do WebSockets replace REST APIs?

No. They complement them. Use REST, explained in our REST API guide, for fetching and changing resources, and WebSockets for streams of live updates. Most real apps use both.

What happens when a WebSocket connection drops?

The socket closes and the client must reconnect, usually with a backoff delay. Because WebSockets do not replay missed messages automatically, your app should resynchronize state after reconnecting, for example by refetching the latest data over HTTP.

Are WebSockets secure?

They can be. Use `wss://` for encryption, authenticate during the HTTP handshake before accepting the upgrade, and validate every incoming message. An unencrypted `ws://` connection exposes message contents like plain HTTP does.

When should I pick SSE instead of WebSockets?

When data flows one way, from server to client, and you want automatic reconnection with message replay. SSE is plain HTTP text, so it is easier to operate, and it covers live feeds and notifications well.

Tags: WebSockets · real-time · HTTP · web development · networking

All posts