WebSockets: Real-Time Web Communication

WebSockets provide a persistent connection between client and server, allowing real-time data exchange without repeated HTTP requests.

WebSockets

WebSockets enable real-time, two-way communication between a browser and a server over a single persistent connection. Unlike HTTP, where the client must initiate every exchange, a WebSocket connection allows the server to push data to the client at any time without waiting to be asked, making it the foundation of live chat, multiplayer gaming, collaborative editing, and real-time dashboards.

What Are WebSockets

The WebSocket protocol establishes a persistent, full-duplex connection between a client and a server. It begins with a standard HTTP request that includes an upgrade header, and once the server accepts, the connection is promoted to the WebSocket protocol. From that point on, both sides can send messages to each other freely and instantly over the same open connection without the overhead of establishing a new connection for each exchange.

The key distinction from HTTP is that WebSocket communication is bidirectional. In a standard HTTP interaction, only the client can initiate a message and the server can only respond. With WebSockets, the server can send data to the client unprompted, the client can send data to the server unprompted, and both can do so simultaneously. This makes WebSockets fundamentally different in design and appropriate for a different class of problems.

WebSockets use the ws:// scheme for unencrypted connections and wss:// for encrypted connections over TLS, which is the WebSocket equivalent of HTTPS. In production, wss:// should always be used to protect the data in transit.

HTTP vs WebSocket

HTTP and WebSockets are complementary technologies that solve different problems. Understanding their differences helps you choose the right tool for each part of your application.

FeatureHTTP (Request-Response)WebSocket
Connection ModelA new connection is established for each request, or reused briefly via keep-aliveA single persistent connection is established once and held open for the duration of the session
Communication DirectionClient initiates every message. The server can only respond.Fully bidirectional. Either side can send a message at any time independently of the other.
Server PushNot natively supported. Requires polling, long-polling, or Server-Sent Events as workarounds.Native. The server can push data to the client whenever new information is available.
LatencyHigher. Each request incurs connection setup and header overhead.Very low. After the initial handshake, messages are exchanged with minimal frame headers.
Protocol OverheadFull HTTP headers are sent with every request and responseMinimal two-to-ten byte frame header per message after the handshake completes
StateStateless by design. Each request is independent.Stateful. The connection persists and both sides maintain awareness of the session.
Best Use CaseCRUD APIs, page loads, file downloads, any standard request-response interactionLive chat, real-time gaming, collaborative editing, live data dashboards, push notifications

How WebSockets Work

A WebSocket connection starts as a standard HTTP request. This design allows WebSockets to work through the same infrastructure as HTTP including load balancers, firewalls, and proxies, because the initial upgrade looks like a normal web request.

  1. The client sends an HTTP GET request to the server with an Upgrade: websocket header and a Sec-WebSocket-Key header containing a randomly generated Base64-encoded value
  2. The server validates the request, computes a response key by hashing the client's key with a fixed GUID, and responds with a 101 Switching Protocols status code
  3. The HTTP connection is promoted to the WebSocket protocol. From this point, the connection operates as a persistent TCP stream rather than an HTTP exchange.
  4. Both client and server can now send messages at any time in either direction without waiting for the other side to initiate
  5. Messages are sent as framed data units, which can carry text or binary data
  6. Either side can close the connection gracefully by sending a close frame, after which the underlying TCP connection is terminated
WebSocket upgrade request from client:
GET /chat HTTP/1.1
Host: example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZQ==
Sec-WebSocket-Version: 13
Server response confirming the upgrade:
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=

WebSocket Client API in JavaScript

The WebSocket API is built into all modern browsers and provides a simple event-driven interface for establishing and communicating over a WebSocket connection.

Full WebSocket client example:
const ws = new WebSocket('wss://example.com/chat');

// Connection opened successfully
ws.onopen = () => {
  console.log('Connected');
  ws.send(JSON.stringify({ type: 'join', room: 'general' }));
};

// Message received from server
ws.onmessage = (event) => {
  const data = JSON.parse(event.data);
  console.log('Message:', data);
};

// Connection closed
ws.onclose = (event) => {
  console.log('Disconnected. Code:', event.code);
};

// Connection error
ws.onerror = (error) => {
  console.error('WebSocket error:', error);
};

// Send a message to the server
ws.send(JSON.stringify({ type: 'message', text: 'Hello everyone' }));

// Close the connection gracefully
ws.close();

The readyState property on the WebSocket object reflects the current state of the connection: 0 is CONNECTING, 1 is OPEN, 2 is CLOSING, and 3 is CLOSED. Always check that the connection is in the OPEN state before calling send() to avoid errors when the connection has dropped.

Real-World Use Cases for WebSockets

WebSockets are appropriate whenever your application needs data to flow in real time without the client polling for updates. These are the most common scenarios where the WebSocket model provides a clear advantage over HTTP.

  • Live chat applications: Messaging platforms like WhatsApp Web, Slack, and Discord use WebSockets to deliver messages to recipients instantly as they are sent, without any polling delay.
  • Real-time dashboards: Financial platforms displaying live stock prices, trading volumes, and market data push updates through WebSockets the moment new data is available from the exchange.
  • Online multiplayer gaming: Player positions, actions, game state updates, and score changes are exchanged at high frequency between clients and game servers over persistent WebSocket connections.
  • Collaborative editing tools: Applications like Google Docs propagate every keystroke, cursor position, and formatting change to all connected collaborators in real time, creating the appearance of simultaneous editing.
  • Live sports and event feeds: Sports data platforms push score updates, play-by-play commentary, and statistics to browser clients the moment events occur during a game.
  • Real-time notifications: Applications push alerts, mentions, and system events to connected users without requiring the user to refresh or poll an endpoint.
  • IoT device monitoring: Dashboards displaying data from connected sensors, devices, or industrial equipment receive continuous telemetry streams through WebSocket connections.

WebSocket vs Server-Sent Events

Server-Sent Events (SSE) is a simpler alternative to WebSockets for cases where data only needs to flow in one direction, from server to client. Choosing between them depends on whether your application needs to send data from the client to the server over the same real-time channel.

FeatureWebSocketServer-Sent Events (SSE)
Communication DirectionFully bidirectional. Both client and server can send messages at any time.Server to client only. The client cannot send messages over the SSE connection.
ProtocolDedicated WebSocket protocol using ws:// or wss:// schemeStandard HTTP using the EventSource API. No protocol upgrade required.
ReconnectionManual. Your code must implement reconnection logic when the connection drops.Automatic. The browser reconnects to the event stream automatically after a disconnection.
Data FormatText or binary frames of any structureText only, structured as named events with optional ID and retry fields
Browser SupportAll modern browsersAll modern browsers. Not supported in Internet Explorer.
ComplexityHigher. Requires WebSocket server infrastructure and connection management.Lower. Works over standard HTTP and is easier to implement and proxy.
Best ForChat, gaming, collaborative editing, any scenario requiring messages from client to server in real timeLive news feeds, social media timelines, server log streaming, one-way notification systems

Scaling WebSockets

WebSockets introduce architectural challenges that do not exist with stateless HTTP APIs. Because each connection is persistent and stateful, horizontal scaling requires careful design.

  • Sticky sessions: A load balancer must route all connections from a given client to the same server instance for the duration of the WebSocket session, because connection state lives on a specific server. This is called sticky sessions or session affinity.
  • Pub/sub messaging: When a message sent by one client must be delivered to clients connected to different server instances, a shared message broker such as Redis Pub/Sub or Apache Kafka is used. Each server subscribes to relevant channels and broadcasts received messages to its locally connected clients.
  • Connection limits: Each open WebSocket connection consumes server memory and a file descriptor. A single server can handle thousands of concurrent connections, but planning for connection limits and implementing graceful degradation is important at large scale.
  • Managed WebSocket services: Platforms like Pusher, Ably, and AWS API Gateway WebSocket API handle connection management, scaling, and message routing as managed services, removing the infrastructure burden from your application team.

Frequently Asked Questions

  1. Are WebSockets secure?
    Yes, when using the wss:// scheme, which runs the WebSocket protocol over TLS in the same way that HTTPS runs HTTP over TLS. All data transmitted over a wss:// connection is encrypted and protected from interception. In production, you should always use wss:// rather than the unencrypted ws:// scheme. WebSocket connections are also subject to the same origin policy, and CORS-like origin checking can be implemented on the server to restrict which domains are allowed to establish connections.
  2. Do WebSockets work through firewalls and proxies?
    Usually yes. Because the WebSocket handshake begins as a standard HTTP request on port 80 or 443, most firewalls and corporate proxies allow the initial connection. However, some older or misconfigured proxies do not understand the Upgrade header and may terminate the connection or buffer responses in a way that breaks the WebSocket protocol. Using wss:// on port 443 is the most compatible option because encrypted HTTPS traffic is rarely inspected or modified by proxies.
  3. Should I always use WebSockets instead of REST APIs?
    No. REST is simpler, more cacheable, easier to scale horizontally, and better supported by standard infrastructure like CDNs and API gateways. WebSockets are appropriate only when you genuinely need real-time bidirectional communication. For standard data retrieval, form submission, and CRUD operations, HTTP and REST remain the right choice. A common pattern is to use REST APIs for most operations and WebSockets only for the specific real-time features that require them, such as a chat feature or a live notification system within a larger application.
  4. How do I handle WebSocket reconnection?
    Unlike Server-Sent Events, WebSockets do not reconnect automatically when a connection drops. Your client code must detect the closure via the onclose event and implement a reconnection strategy. A common approach is exponential backoff, where the client waits an increasing amount of time between reconnection attempts, for example one second, two seconds, four seconds, up to a maximum interval. This prevents clients from overwhelming a server that has just recovered from an outage with simultaneous reconnection attempts.
  5. What is the difference between WebSockets and HTTP long-polling?
    Long-polling is an older technique for achieving near-real-time server push over HTTP. The client sends a request to the server, which holds the connection open rather than responding immediately. When new data is available, the server sends the response and the client immediately sends a new request to wait for the next update. This creates a continuous cycle that simulates real-time updates but carries the full overhead of an HTTP request and response for every message, including headers. WebSockets eliminate this overhead entirely by maintaining a single open connection with minimal per-message framing, resulting in lower latency and significantly less bandwidth consumption at scale.

Conclusion

WebSockets unlock real-time capabilities that HTTP cannot provide natively, enabling persistent bidirectional communication with minimal overhead. They are the right choice for live chat, multiplayer gaming, collaborative editing, real-time dashboards, and any application where data must flow from server to client without waiting for a client request. For simpler one-way server push use cases, Server-Sent Events offer a lower-complexity alternative that works over standard HTTP. Combining WebSockets for real-time features with REST APIs for standard data operations gives you the most pragmatic and maintainable architecture for most applications. Together with REST APIs, HTTP methods, and HTTPS, WebSockets complete your understanding of modern web communication protocols.