What are WebSockets?

Building real-time applications: WebSockets vs SSE vs Long Polling.

The HTTP protocol was built for document retrieval: a client asks for a page, and the server sends it. This request-response cycle works perfectly for reading articles, but it falls apart when trying to build real-time applications like chat rooms, multiplayer games, or live financial dashboards.

If you need the server to push new data to the client immediately when it happens, you need a different protocol. Enter WebSockets.

The Problem with HTTP for Real-Time

Before WebSockets, developers used "hacks" to simulate real-time behavior over HTTP:

  • Short Polling: The client sends an HTTP request every 3 seconds asking, "Is there new data?". This is incredibly inefficient, wasting server resources and battery life on empty responses.
  • Long Polling: The client sends an HTTP request. If the server has no new data, it holds the connection open until data arrives. Once data is sent, the client immediately opens a new long-polling connection. While better than short polling, it still incurs HTTP overhead for every message.

How WebSockets Work

WebSocket is a distinct computer communications protocol, providing full-duplex (two-way) communication channels over a single TCP connection.

It starts with an HTTP request. The client sends a standard HTTP GET request with an Upgrade: websocket header. If the server supports it, it responds with an HTTP 101 Switching Protocols status. The HTTP connection is then "upgraded" to a WebSocket connection.

From that point on, the connection remains open. Both the client and the server can send lightweight message frames to each other at any time, with almost zero overhead.

// Client-side JavaScript
const socket = new WebSocket('wss://api.example.com/chat');

// Listen for messages from the server
socket.addEventListener('message', (event) => {
  console.log('Message from server:', event.data);
});

// Send a message to the server
socket.send(JSON.stringify({ text: "Hello server!" }));

WebSockets vs. Server-Sent Events (SSE)

While WebSockets are powerful, they are often overkill. If you are building a live dashboard, stock ticker, or streaming text from an AI model (like ChatGPT), the client rarely needs to send high-frequency data back to the server. The server just needs to push data to the client.

In these cases, Server-Sent Events (SSE) is often a better choice.

Feature WebSockets SSE
Direction Bidirectional (Two-way) Unidirectional (Server to Client)
Protocol ws:// or wss:// Standard HTTP/HTTPS
Data Format Text or Binary Text (UTF-8) only
Reconnection Must be implemented manually Built-in automatic reconnection
Best For Chat, multiplayer games, collaborative editing News feeds, stock tickers, AI text streaming

Challenges of WebSockets

Implementing WebSockets at scale introduces significant architectural challenges:

  • State Management: HTTP is stateless. Any server can handle any request. WebSockets are stateful. The server must keep the TCP connection open in memory. If you have 100,000 active chat users, you must maintain 100,000 open connections.
  • Load Balancing: Because connections are persistent, traditional HTTP load balancers struggle. You must use specialized tools or Layer 4 (TCP) load balancing.
  • Scaling Horizontally: If User A is connected to Server 1, and User B is connected to Server 2, how do they chat? Your servers must communicate with each other, typically using a Pub/Sub system like Redis to broadcast messages across the cluster.

Because of these complexities, many developers opt for managed real-time services like Pusher, Ably, or Socket.io (which provides fallbacks and reconnection logic automatically).