Skip to content

// glossary

What is WebSocket?

WebSocket is a communication protocol that provides full-duplex, bidirectional communication between a client and server over a single, persistent TCP connection.

WebSocket is a communication protocol that provides full-duplex, bidirectional communication between a client and server over a single, persistent TCP connection. Unlike HTTP’s request-response model, WebSocket allows both sides to send messages at any time without polling.

How WebSocket connections work

A WebSocket connection starts as an HTTP request with an upgrade header:

GET /chat HTTP/1.1
Host: example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=

After this handshake, the HTTP connection upgrades to WebSocket. The TCP connection stays open, and both client and server can send frames (messages) at will.

WebSocket vs. HTTP polling

Before WebSocket, real-time updates required workarounds:

  • Short polling: Client requests data every N seconds. Wastes bandwidth and adds latency.
  • Long polling: Client opens a request; server holds it until new data is available. Better, but still creates overhead per message cycle.
  • Server-Sent Events (SSE): Server pushes data to the client over HTTP. Unidirectional only.

WebSocket eliminates these workarounds. Once connected, messages are lightweight frames with minimal overhead (as little as 2 bytes per frame header), compared to HTTP’s repeated headers on every request.

Common use cases

  • Chat applications: Real-time messaging between users
  • Live dashboards: Stock tickers, analytics, monitoring tools
  • Collaborative editing: Google Docs-style simultaneous editing
  • Online gaming: Low-latency game state synchronization
  • Notifications: Push alerts without polling
  • Live feeds: Sports scores, social media streams, auction bidding

Client-side usage

const ws = new WebSocket('wss://example.com/socket');

ws.onopen = () => ws.send(JSON.stringify({ type: 'subscribe', channel: 'updates' }));
ws.onmessage = (event) => console.log(JSON.parse(event.data));
ws.onclose = (event) => console.log('Closed:', event.code, event.reason);
ws.onerror = (error) => console.error('Error:', error);

Use wss:// (WebSocket Secure) for encrypted connections — the equivalent of HTTPS.

Connection management

WebSocket connections need more care than stateless HTTP requests:

  • Reconnection logic: Connections drop. Implement exponential backoff for automatic reconnection.
  • Heartbeats: Send periodic ping/pong frames to detect dead connections.
  • Scaling: Each connection holds a persistent TCP socket. A server handling 100K concurrent connections needs careful resource management. Solutions like Redis pub/sub or message brokers help distribute messages across multiple server instances.

When not to use WebSocket

For simple request-response interactions, REST APIs are simpler and benefit from HTTP caching, CDN support, and stateless scaling. Use WebSocket only when you genuinely need persistent bidirectional communication. SSE is a lighter alternative when you only need server-to-client push.

Debug HTTP status codes involved in WebSocket handshakes with the HTTP Status Codes reference and format JSON message payloads with the JSON Formatter.

#Related Tools

#Related Terms

#Learn More