WebSocket Communication: Real-Time Data for Web Apps
WebSockets enable real-time, two-way communication in web apps. Covers the handshake, message framing, heartbeats, reconnection, and comparison with SSE.
A WebSocket is a persistent, full-duplex connection between browser and server that lets either side send data at any time, without the request-response cycle HTTP requires. Standard HTTP is request-response — the client asks, the server answers, and the connection is done — which works for loading pages and fetching data but fails for real-time features like chat messages, live notifications, stock tickers, collaborative editing, and multiplayer games, where the server needs to push data without waiting for a request.
WebSockets solve this by upgrading a regular HTTP connection into that persistent, full-duplex channel. Both the client and server can send messages at any time, with minimal overhead. This guide covers how WebSockets work, how to use them effectively, and when to choose alternatives.
The WebSocket Handshake
A WebSocket connection starts as a regular HTTP request. The client sends an Upgrade header, and the server agrees to switch protocols.
Client Request
GET /ws/chat HTTP/1.1
Host: example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
Server Response
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
The 101 Switching Protocols response means the connection is now a WebSocket. The HTTP overhead is gone — from this point on, both sides send lightweight WebSocket frames.
The Sec-WebSocket-Key and Sec-WebSocket-Accept headers provide a basic handshake verification. The server takes the key, appends a fixed GUID, SHA-1 hashes it, and base64 encodes the result. This is not security — it is a sanity check that both sides intend to speak WebSocket.
Using WebSockets in the Browser
The browser provides a simple WebSocket API:
const ws = new WebSocket('wss://example.com/ws/chat');
// Connection opened
ws.addEventListener('open', () => {
console.log('Connected');
ws.send(JSON.stringify({ type: 'join', room: 'general' }));
});
// Receiving messages
ws.addEventListener('message', (event) => {
const data = JSON.parse(event.data);
console.log('Received:', data);
});
// Connection closed
ws.addEventListener('close', (event) => {
console.log(`Disconnected: ${event.code} ${event.reason}`);
});
// Error handling
ws.addEventListener('error', (event) => {
console.error('WebSocket error:', event);
});
Always use wss:// (WebSocket Secure) in production. It is WebSocket over TLS, just as https:// is HTTP over TLS.
Message Framing
WebSocket messages are transmitted in frames. Unlike HTTP, there are no headers for each message — frames are compact binary structures.
Text vs Binary
WebSocket supports two data types:
// Text frame — typically JSON
ws.send(JSON.stringify({ action: 'move', x: 10, y: 20 }));
// Binary frame — for files, images, or custom protocols
ws.send(new ArrayBuffer(8));
ws.send(new Blob(['binary data']));
For most web applications, JSON text messages are the standard. When formatting your message payloads during development, the JSON formatter can help you inspect and validate message structures.
Message Size
WebSocket frames can be up to 2^63 bytes, but practical limits apply:
- Most servers and proxies limit frame size to 1-16 MB
- Large messages block the connection — other messages must wait
- For large data transfers, consider chunking or using HTTP instead
Structuring Messages
Define a consistent message format. A common pattern:
{
"type": "chat.message",
"payload": {
"room": "general",
"text": "Hello everyone",
"timestamp": "2026-09-15T14:30:00Z"
},
"id": "msg_abc123"
}
Message Types
Organize messages by type to make handling straightforward:
ws.addEventListener('message', (event) => {
const msg = JSON.parse(event.data);
switch (msg.type) {
case 'chat.message':
displayMessage(msg.payload);
break;
case 'user.joined':
addUser(msg.payload);
break;
case 'user.left':
removeUser(msg.payload);
break;
case 'error':
handleError(msg.payload);
break;
case 'pong':
// Heartbeat response
break;
}
});
Heartbeats and Keep-Alive
WebSocket connections can silently die. The TCP connection might still exist from the operating system’s perspective, but no data is flowing — the remote end may have crashed, a proxy may have timed out, or the network may have changed.
Application-Level Heartbeats
Implement ping-pong messages at the application level:
class WebSocketClient {
constructor(url) {
this.url = url;
this.heartbeatInterval = 30000; // 30 seconds
this.heartbeatTimeout = 10000; // 10 seconds to respond
this.connect();
}
connect() {
this.ws = new WebSocket(this.url);
this.ws.addEventListener('open', () => this.startHeartbeat());
this.ws.addEventListener('message', (e) => this.handleMessage(e));
this.ws.addEventListener('close', () => this.handleClose());
}
startHeartbeat() {
this.pingTimer = setInterval(() => {
if (this.ws.readyState === WebSocket.OPEN) {
this.ws.send(JSON.stringify({ type: 'ping' }));
this.pongTimer = setTimeout(() => {
console.log('Heartbeat timeout — closing connection');
this.ws.close();
}, this.heartbeatTimeout);
}
}, this.heartbeatInterval);
}
handleMessage(event) {
const msg = JSON.parse(event.data);
if (msg.type === 'pong') {
clearTimeout(this.pongTimer);
return;
}
// Handle other messages
}
handleClose() {
clearInterval(this.pingTimer);
clearTimeout(this.pongTimer);
this.reconnect();
}
}
WebSocket Protocol Pings
The WebSocket protocol has built-in ping and pong frames (opcodes 0x9 and 0xA). Browsers handle pong responses automatically, but the browser API does not expose ping frames to JavaScript. Use them server-side:
// Node.js with 'ws' library
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', (ws) => {
ws.isAlive = true;
ws.on('pong', () => { ws.isAlive = true; });
});
setInterval(() => {
wss.clients.forEach((ws) => {
if (!ws.isAlive) return ws.terminate();
ws.isAlive = false;
ws.ping();
});
}, 30000);
Reconnection Strategies
Connections will drop. Your client needs to handle this gracefully.
Exponential Backoff
Do not reconnect immediately and repeatedly — you will overwhelm the server if it is already under load:
class ReconnectingWebSocket {
constructor(url) {
this.url = url;
this.reconnectAttempts = 0;
this.maxReconnectDelay = 30000; // 30 seconds max
this.connect();
}
connect() {
this.ws = new WebSocket(this.url);
this.ws.addEventListener('open', () => {
this.reconnectAttempts = 0; // Reset on successful connection
});
this.ws.addEventListener('close', (event) => {
if (event.code !== 1000) { // 1000 = normal closure
this.scheduleReconnect();
}
});
}
scheduleReconnect() {
const delay = Math.min(
1000 * Math.pow(2, this.reconnectAttempts) + Math.random() * 1000,
this.maxReconnectDelay
);
console.log(`Reconnecting in ${Math.round(delay / 1000)}s...`);
setTimeout(() => {
this.reconnectAttempts++;
this.connect();
}, delay);
}
}
The jitter (random component) prevents the thundering herd problem — if the server goes down and 10,000 clients all reconnect at the exact same exponential intervals, they will hit the server simultaneously.
State Recovery
After reconnecting, you need to recover the state you missed. Common approaches:
- Last event ID: Send the ID of the last message you received, and the server replays everything after it
- Timestamp-based: Request all events since a timestamp
- Full state sync: Request the complete current state after reconnecting
ws.addEventListener('open', () => {
ws.send(JSON.stringify({
type: 'sync',
lastEventId: this.lastEventId,
}));
});
WebSocket Close Codes
When a connection closes, a numeric code indicates why:
| Code | Meaning |
|---|---|
| 1000 | Normal closure |
| 1001 | Going away (page navigation, server shutdown) |
| 1002 | Protocol error |
| 1003 | Unsupported data type |
| 1006 | Abnormal closure (no close frame received) |
| 1008 | Policy violation |
| 1009 | Message too big |
| 1011 | Server error |
| 4000-4999 | Application-defined codes |
Use custom close codes (4000-4999) for application-specific reasons:
// Server-side
ws.close(4001, 'Authentication expired');
ws.close(4002, 'Rate limit exceeded');
// Client-side
ws.addEventListener('close', (event) => {
if (event.code === 4001) {
redirectToLogin();
}
});
WebSockets vs Server-Sent Events (SSE)
SSE is a simpler alternative for when you only need server-to-client communication.
| Feature | WebSocket | SSE |
|---|---|---|
| Direction | Bidirectional | Server to client only |
| Protocol | Custom (ws://) | HTTP (text/event-stream) |
| Reconnection | Manual | Automatic (built-in) |
| Binary data | Yes | No (text only) |
| HTTP/2 multiplexing | No (separate TCP) | Yes |
| Browser support | Universal | Universal (except IE) |
| Proxy compatibility | Can be problematic | Works everywhere |
| Complexity | Higher | Lower |
When to Use SSE Instead
- Live feeds: News, stock tickers, social media updates
- Notifications: Server pushes alerts to the client
- Progress updates: File upload progress, job status
- Any server-to-client streaming: Where the client does not need to send data back over the same channel
SSE is simpler to implement, works through HTTP proxies without issues, and automatically reconnects:
const source = new EventSource('/api/events');
source.addEventListener('notification', (event) => {
const data = JSON.parse(event.data);
showNotification(data);
});
When You Need WebSockets
- Chat applications: Both sides send messages
- Collaborative editing: Cursor positions, text changes from multiple users
- Multiplayer games: Real-time input and state
- Interactive protocols: Where the client’s messages affect the server’s responses in real time
Server-Side Considerations
Scaling WebSockets
WebSocket connections are long-lived, which creates scaling challenges:
- Connection limits: Each connection uses a file descriptor. A server might handle 10,000-100,000 concurrent connections depending on the hardware and framework.
- Sticky sessions: If you have multiple servers behind a load balancer, a WebSocket must stay connected to the same server. Use sticky sessions or a pub/sub system (Redis Pub/Sub, NATS) to broadcast across servers.
- Memory: Each connection holds state in memory. Plan for the memory cost of your peak concurrent connections.
Authentication
Authenticate during the handshake, not after:
// Client: pass token as a query parameter or subprotocol
const ws = new WebSocket('wss://example.com/ws?token=jwt_token_here');
// Or use a cookie-based approach
// (cookies are sent automatically with the handshake request)
Some applications authenticate over HTTP first, receive a short-lived ticket, and use that ticket in the WebSocket handshake. This avoids putting long-lived tokens in URLs.
For encoding tokens or data that needs to be transmitted in WebSocket messages, the Base64 encoder can help with binary-to-text encoding when working with authentication payloads.
Summary
WebSockets provide full-duplex, real-time communication over a single TCP connection. Use them when you need bidirectional messaging — chat, collaboration, gaming, or interactive protocols. Implement heartbeats to detect dead connections, use exponential backoff with jitter for reconnection, and structure your messages with clear types for maintainable code. For server-to-client-only streaming, consider SSE as a simpler alternative that works within standard HTTP infrastructure.
Turn a click-through into an interactive demo
AtriumKit records your web app once in Chrome and turns every click into a step of a demo you can embed or share. There’s a free plan.
Try AtriumKit free
Comments