Open a chat app, a live sports score page or a stock ticker in your browser, and new information appears without you clicking refresh. Behind many of these experiences is a protocol called WebSocket. It lets a browser and a server keep a single connection open and send messages to each other whenever they want. In this guide you will learn why WebSockets exist, how they work under the hood, and when they are (and are not) the right tool for your backend.
Why plain HTTP struggles with real-time data
HTTP was designed around a simple pattern: the client sends a request, the server sends back a response, and the exchange is over. The server cannot start a conversation on its own. That is perfect for loading pages and calling APIs, but awkward when the server learns something new and needs to tell the client right away.
Developers came up with several workarounds before WebSockets became widely available:
- Short polling: the client asks “anything new?” every few seconds. Easy to build, but most requests return nothing, wasting bandwidth and server time.
- Long polling: the client sends a request and the server holds it open until there is new data or a timeout. Fewer empty responses, but every message still requires a fresh request.
- Server-Sent Events (SSE): the server streams events over a long-lived HTTP response. It works well, but data only flows from server to client.
What a WebSocket actually is
WebSocket is a communication protocol standardized by the IETF as RFC 6455 in 2011 and supported by every modern browser. It provides a full-duplex channel over a single TCP connection: both sides can send messages at any time, independently of each other, without the overhead of new HTTP requests.
WebSocket URLs use two schemes: ws:// for unencrypted connections and wss:// for connections secured with TLS. Just as you would use HTTPS rather than HTTP in production, you should use wss:// for any real application.
The opening handshake, step by step
A WebSocket connection begins life as an ordinary HTTP request. This clever design lets it pass through infrastructure that already understands HTTP.
- The client sends a GET request with the headers
Upgrade: websocketandConnection: Upgrade, plus a random, base64-encoded value inSec-WebSocket-Key. - If the server supports WebSockets and accepts the request, it replies with status code 101 Switching Protocols and a
Sec-WebSocket-Acceptheader derived from the client’s key. This proves the server really understood the WebSocket request. - From that moment on, the connection stops speaking HTTP. Both sides exchange small units called frames, which can carry text (UTF-8) or binary data.
- Either side can close the connection by sending a close frame. Special ping and pong frames can be used to check that the other side is still alive.
Comparing the options
| Approach | Direction | Connection | Best for |
|---|---|---|---|
| Short polling | Client asks repeatedly | New request each time | Rare updates, simple prototypes |
| Long polling | Client asks, server waits | New request per message | Fallback when other options fail |
| Server-Sent Events | Server to client only | Long-lived HTTP response | Live feeds, notifications |
| WebSocket | Both directions | Single persistent connection | Chat, games, collaboration |
A minimal example
Browsers expose WebSockets through a built-in JavaScript API. Here is a small client that connects, joins a room, and logs incoming messages:
const socket = new WebSocket("wss://example.com/live");
socket.onopen = () => {
socket.send(JSON.stringify({ type: "join", room: "general" }));
};
socket.onmessage = (event) => {
const data = JSON.parse(event.data);
console.log("Received:", data);
};
socket.onclose = () => console.log("Disconnected");
On the server side, nearly every backend language has a mature WebSocket library. In the Node.js world, the ws package is a lightweight choice, while Socket.IO adds features such as rooms, automatic reconnection and fallbacks. Keep in mind that Socket.IO uses its own protocol on top of WebSockets, so a plain WebSocket client cannot talk to a Socket.IO server directly.
Designing your message format
The WebSocket protocol only moves text or bytes; it says nothing about what those messages mean. Your application has to define that. A common approach is to send JSON objects with a type field, such as {"type": "chat", "text": "Hello"} or {"type": "typing", "user": "ana"}. Both client and server can then route each message to the right handler. Some teams add a version number or a request ID so they can match replies to specific requests.
Good use cases
- Chat and messaging apps, where users send and receive messages constantly.
- Multiplayer browser games that need low-latency updates in both directions.
- Collaborative editors, whiteboards and design tools.
- Live dashboards for monitoring servers, deliveries or financial data.
- In-app notifications that should appear instantly.
When to choose something else
WebSockets add complexity, so they are not a default choice. For ordinary CRUD operations, forms and page loads, regular HTTP is simpler, works naturally with caching and CDNs, and is easier to debug and scale. If your server only needs to push updates and the client rarely talks back, Server-Sent Events may be lighter. If updates happen once every few minutes, simple polling can be perfectly acceptable.
Backend challenges to plan for
- Many open connections: each connected client holds a socket open, which uses memory and file descriptors. Event-driven servers handle this well, but you still need to plan capacity.
- Horizontal scaling: if users are connected to different server instances, a message from one user must reach the others. A shared message broker, such as Redis Pub/Sub, is a common solution.
- Load balancers and proxies: they must be configured to allow the upgrade and to keep idle connections open long enough.
- Reconnection: mobile networks drop often. Clients should reconnect automatically, ideally with increasing delays between attempts.
- Security: authenticate users during the handshake, check the
Originheader, limit message size and rate, and validate every incoming message as untrusted input.
Conclusion
WebSockets turn the web’s request-and-response model into an open, two-way conversation. A connection starts as an HTTP request, upgrades with a 101 response, and then carries lightweight frames in both directions for as long as it stays open. Used for the right problems, they make applications feel instant and alive. If you want to go deeper into servers, APIs and real-time systems, take a look at the free Backend Development courses available on Cursa.