What Is WebSocket?

Run a Speed Test

WebSocket provides a persistent, full-duplex communication channel between a browser and server over a single TCP connection — enabling real-time features like chat, live scores, collaborative editing, and financial tickers without the overhead of repeated HTTP requests.

The Problem WebSocket Solves

HTTP was designed as a request/response protocol: the client asks, the server answers, and the transaction is complete. This model works well for loading web pages but is a poor fit for applications that need the server to push data to the client on its own schedule — a chat message arriving, a stock price changing, a collaborator's cursor moving.

Before WebSocket, developers worked around this with polling: the browser repeatedly asks the server "is there anything new?" every few seconds. This wastes bandwidth and server resources when nothing has changed, and introduces latency equal to the polling interval. Long-polling improved things slightly — the server holds the request open until it has something to say, then responds and the client immediately reconnects — but the constant cycle of HTTP overhead remained. WebSocket was standardized (RFC 6455, 2011) to eliminate this pattern entirely.

The WebSocket Handshake

A WebSocket connection starts as a normal HTTP/1.1 GET request with two special headers: Upgrade: websocket and Connection: Upgrade. The client also sends a Sec-WebSocket-Key header containing a random base64-encoded value. The server responds with HTTP status 101 Switching Protocols and a Sec-WebSocket-Accept header computed from the client's key. After this exchange, the HTTP framing is discarded and both sides speak the WebSocket wire format on the same TCP connection indefinitely.

The handshake's use of standard HTTP headers means WebSocket connections pass through the same port 80 (ws://) or 443 (wss://) as regular web traffic and are treated as HTTP upgrades by load balancers and proxies that understand the protocol.

WebSocket Frames

Once the connection is established, data is exchanged as frames. Each frame has a small header (2–10 bytes) containing an opcode, a payload length, and a masking key. The opcodes define the message type: 0x1 for text (UTF-8), 0x2 for binary, 0x8 for close, 0x9 for ping, and 0xA for pong. Ping/pong frames allow either side to check that the connection is still alive and reset timeout timers. Messages larger than a single frame are split into continuation frames and reassembled by the receiver.

Client-to-server frames are always masked with a 32-bit random key to prevent cache-poisoning attacks through intermediaries. Server-to-client frames are not masked. This asymmetry is a deliberate protocol design decision.

WebSocket vs Server-Sent Events

Server-Sent Events (SSE) is a simpler alternative for one-directional server-to-client streaming. SSE uses a standard HTTP response with Content-Type: text/event-stream — the server writes newline-delimited event objects and the browser's EventSource API reads them. SSE reconnects automatically if the connection drops, and it works natively over HTTP/2 multiplexing. For dashboards, news feeds, live notifications, and progress bars — any pattern where the server pushes and the client only reads — SSE is simpler to deploy and requires no special proxy configuration.

WebSocket is the right choice when the client also sends frequent messages: chat applications, collaborative text editors, multiplayer games, trading platforms, and IoT device control panels. If you find yourself using WebSocket only to receive server updates while the client sends infrequently, SSE is likely the simpler and more robust choice.

WebSocket and Load Balancers

WebSocket connections are long-lived, which creates a challenge for load balancers. A standard HTTP load balancer distributes each request independently — but a WebSocket connection must reach the same backend server for its entire lifetime. This requires either sticky sessions (routing all requests from a client to the same backend based on a cookie or IP hash) or a WebSocket-aware message broker that allows any backend to handle any WebSocket message.

Socket.io, a popular WebSocket library for Node.js, provides an adapter layer for Redis or other pub/sub systems so that a WebSocket message received by server A can be broadcast to clients connected to server B. This decouples the WebSocket connection from the specific backend instance and enables horizontal scaling.

Comparison: WebSocket vs Alternatives

Method Direction Protocol Latency Connection overhead Browser support Best use case
HTTP polling Client → Server → Client HTTP/1.1+ High (interval-bound) High (new request each poll) Universal Legacy fallback only
Long-polling Client → Server → Client HTTP/1.1+ Medium Medium (reconnect per event) Universal Simple push where WebSocket unavailable
Server-Sent Events Server → Client HTTP/1.1+ (HTTP/2 native) Low Low (persistent stream) All modern browsers Live feeds, notifications, dashboards
WebSocket Bidirectional WebSocket (over TCP) Very low Low (single persistent connection) All modern browsers Chat, gaming, collaborative tools
HTTP/2 server push Server → Client HTTP/2 Low Low Most modern browsers (deprecated) Preloading assets (now mostly deprecated)

Use Cases and Libraries

WebSocket powers the real-time features in a wide variety of applications. Chat systems like Slack and Discord use WebSocket to deliver messages instantly without polling. Collaborative editing tools like Figma and Notion use WebSocket to synchronize cursor positions, selections, and edits across connected users. Financial trading platforms use WebSocket to stream live order book updates and price ticks with sub-second latency. Online multiplayer games use WebSocket for game state synchronization. IoT dashboards use WebSocket to display sensor readings as they arrive.

The native browser WebSocket API is available in all modern browsers and requires no library. For Node.js servers, the ws package is the most widely used minimal implementation. Socket.io adds automatic reconnection, room management, event namespacing, and fallback to long-polling for older environments, at the cost of a custom framing protocol on top of WebSocket.

Frequently Asked Questions

How is WebSocket different from HTTP?

HTTP is a request/response protocol — the client always initiates, the server responds, and the connection is closed or returned to a pool. The server cannot push data to the client unsolicited. WebSocket starts as an HTTP request but upgrades to a persistent, bidirectional channel where either side can send a message at any time. Once the WebSocket connection is open, there is no request/response cycle — messages flow freely in both directions over the same TCP connection until one side sends a Close frame.

Does WebSocket use TCP or UDP?

WebSocket uses TCP. It begins as an HTTP/1.1 connection (which is TCP-based) and upgrades the same TCP connection to WebSocket framing. Because it relies on TCP, WebSocket inherits TCP's reliability and ordering guarantees — every message is delivered in order without loss. This also means WebSocket is subject to TCP head-of-line blocking, which is one reason some real-time applications on modern networks are exploring WebTransport over QUIC as a future alternative.

What is wss://?

wss:// (WebSocket Secure) is the encrypted variant of WebSocket, analogous to https:// for HTTP. A wss:// connection upgrades an HTTPS connection to a WebSocket connection, meaning the entire WebSocket session is protected by TLS. Any WebSocket connection over the public internet should use wss:// to prevent eavesdropping and man-in-the-middle attacks. The unencrypted ws:// scheme is only appropriate for connections on localhost or trusted private networks.

Can WebSockets pass through firewalls and proxies?

WebSocket connections on port 443 (wss://) generally pass through firewalls because they look like HTTPS traffic during the initial handshake. However, some HTTP proxies do not support the Upgrade mechanism and will drop the connection. Corporate proxies that perform SSL inspection may interfere with WebSocket connections. Using wss:// on port 443 gives the best chance of traversal. Some environments require a WebSocket-aware proxy such as nginx with proxy_pass and proxy_http_version 1.1 configured.

When should I use WebSocket vs Server-Sent Events?

Use Server-Sent Events (SSE) when data flows only from server to client — live feeds, notifications, progress updates, dashboards. SSE is simpler to implement, works over standard HTTP/2, reconnects automatically, and does not require special proxy configuration. Use WebSocket when you need bidirectional communication — chat, collaborative editing, multiplayer games, trading platforms where the client also sends frequent messages. If you only need the server to push updates and the client rarely sends data, SSE is the simpler and more robust choice.

Do WebSockets work with HTTP/2 or HTTP/3?

WebSocket was designed for HTTP/1.1 and uses its Upgrade mechanism. HTTP/2 does not support the same Upgrade header, so traditional WebSocket connections run on HTTP/1.1 even when the server supports HTTP/2. RFC 8441 defines a way to tunnel WebSocket over HTTP/2 streams (using the CONNECT method and :protocol pseudo-header), but browser support is still limited. HTTP/3 has a similar extension in progress. For HTTP/2 and HTTP/3 environments, WebTransport is emerging as a more native alternative for bidirectional streaming.

Related Guides

More From This Section