WebSockets: Bidirectional Messages and Reconnection
HTTP is a request-response protocol: the client asks, the server answers, the connection's usefulness ends with the response. Real-time features β chat, live scores, collaborative cursors, notification feeds β need a channel where either side can speak first and messages arrive in milliseconds rather than on the next poll. WebSockets provide exactly that: a single full-duplex connection, established with an HTTP upgrade handshake, that stays open until one side closes it.
The browser API itself is small: construct a WebSocket, assign handlers, call send. Everything difficult lives around the API β protocols for message framing, heartbeats that detect half-open connections, reconnection with backoff, and the server infrastructure that makes one connection per browser tab economically sane. This lesson covers the client surface completely and the surrounding engineering that separates a demo chat from something users can trust.
The Lifecycle and Its Four Handlers
const socket = new WebSocket('wss://realtime.example.com/v1');
socket.addEventListener('open', () => {
console.log('Connected');
socket.send(JSON.stringify({ type: 'subscribe', channel: 'prices:BTC-USD' }));
});
socket.addEventListener('message', (event) => {
// event.data is a string for text frames, an ArrayBuffer for binary
const message = JSON.parse(event.data);
handleUpdate(message);
});
socket.addEventListener('close', (event) => {
console.log('Closed', event.code, event.reason);
});
socket.addEventListener('error', () => {
// Followed by a close event; log only, no recovery here
});
Three details about this surface trip people up. First, the error handler never receives an error object β it signals that something failed, and the close event that follows carries the code you actually diagnose with. Second, message data arrives as a string by default; for binary payloads set socket.binaryType to arraybuffer before messages arrive. Third, a connection that fails during the HTTP upgrade fires error and close but never open, so any state you assumed at open time must be re-established after every successful reconnect rather than once at startup.
Close codes are meaningful. Code 1000 means a normal closure initiated by the page. Code 1006 is an abnormal closure β the network dropped without a close frame β and is the code your reconnect logic should treat as "try again." Code 1008 signals a policy violation on the server and 1011 an unexpected server error; repeated 1008s mean stop reconnecting and surface the problem, because retrying will only get you blocked faster.
A Client That Survives Real Networks
Production-grade connection handling adds three things: an exponential backoff for reconnects, a heartbeat that detects dead connections before a send does, and application-level acknowledgement for messages that must not be lost:
class RealtimeClient {
constructor(url) {
this.url = url;
this.handlers = new Map();
this.retry = 0;
this.connect();
}
connect() {
this.socket = new WebSocket(this.url);
this.socket.addEventListener('open', () => {
this.retry = 0;
this.heartbeat = setInterval(() => {
if (this.socket.readyState === WebSocket.OPEN) {
this.socket.send(JSON.stringify({ type: 'ping' }));
}
}, 25000);
this.emit('open');
});
this.socket.addEventListener('message', (event) => {
const message = JSON.parse(event.data);
if (message.type === 'pong') return;
this.emit('message', message);
});
this.socket.addEventListener('close', (event) => {
clearInterval(this.heartbeat);
this.emit('close', event);
if (event.code === 1008) return;
const delay = Math.min(1000 * 2 ** this.retry, 30000);
const jitter = delay * (0.5 + Math.random() * 0.5);
this.retry += 1;
setTimeout(() => this.connect(), jitter);
});
}
on(type, handler) {
if (!this.handlers.has(type)) this.handlers.set(type, []);
this.handlers.get(type).push(handler);
}
emit(type, payload) {
for (const handler of this.handlers.get(type) || []) handler(payload);
}
send(message) {
if (this.socket.readyState === WebSocket.OPEN) {
this.socket.send(JSON.stringify(message));
return true;
}
return false;
}
}
const client = new RealtimeClient('wss://realtime.example.com/v1');
client.on('open', () => showStatus('Live'));
client.on('close', () => showStatus('Reconnectingβ¦'));
client.on('message', (message) => {
if (message.type === 'price') updateTicker(message.payload);
});
The jitter on the backoff is not decoration: without it, a server restart brings every client back at the same instant in a thundering herd. The twenty-five-second heartbeat sits under the sixty-to-hundred-twenty-second idle timeouts that proxies and load balancers commonly enforce β send more often than the idle window and the connection is never cut mid-thought. Queue or persist messages that arrive while disconnected, and replay them after open rather than pretending the gap did not happen.
Framing Messages: A Convention, Not a Spec
WebSocket carries frames; the shape of your messages is entirely up to you. The convention that scales is a type field plus a payload, serialized as JSON for text messages:
| Message type | Direction | Purpose |
|---|---|---|
| subscribe, unsubscribe | Client to server | Channel membership |
| ping, pong | Both | Liveness heartbeat |
| event | Server to client | Domain update for a channel |
| ack | Server to client | Confirmation of a numbered client message |
| error | Server to client | Structured failure with a code |
Give every client-originated event a sequence number, and have the server acknowledge it. On reconnect, re-send any event without an acknowledgement. That tiny protocol is what makes a WebSocket layer survive mobile networks, where connections die silently every time an elevator doors close. For binary data β sensor streams, audio, game state β prefer a compact encoding and send ArrayBuffer frames rather than base64 inside JSON, which inflates payloads by a third.
The Server You Are Not Writing in This Lesson
The browser half of WebSockets is only half a system. Every connected tab holds a socket and a slice of server memory, so real deployments front the sockets with a process that can broadcast cheaply β Node with a ws library, Elixir with Phoenix Channels, Go with gorilla β and often a message broker such as Redis so that application servers can fan out across instances. Design the server to assume clients reconnect constantly: resubscribe them by channel on open, tolerate duplicate subscriptions, and never treat a single connection as the source of truth for session state.
The constructor accepts a second argument for subprotocols β strings both sides must agree on during the handshake β which is how standards like STOMP or custom versioned protocols declare themselves without inventing an ad hoc hello message. More practically, instrument the connection count and message rate on the server from day one. A WebSocket fleet fails quietly: the page keeps rendering the last known data while sockets sit dead behind a load balancer that dropped long-lived connections during a deploy, and without metrics the first report arrives from a user, not a dashboard.
WebSocket Versus Server-Sent Events Versus Polling
| Criterion | WebSocket | SSE | Long polling |
|---|---|---|---|
| Direction | Full duplex | Server to client only | Client request, server reply |
| Protocol | ws or wss | Ordinary HTTP | Ordinary HTTP |
| Reconnection | Manual, yours to build | Automatic built in | Manual or library |
| Proxy friendliness | Upgrade sometimes blocked | Works over normal HTTP | Works everywhere |
| Best for | Chat, collaboration, games | Feeds, notifications, live scores | Legacy fallback only |
If your data flows one way, SSE is usually the simpler choice: it reconnects for you, uses plain HTTP that corporate proxies do not mangle, and carries event ids for resume. Reach for WebSockets when the client must send at interactive rates β every keystroke in a shared editor, every move in a multiplayer game β and accept the reconnection machinery as the price.
Security: WSS, Origins, and Authentication
Always use wss β the encrypted scheme β in production; browsers refuse insecure ws from https pages anyway, and plaintext frames on public networks are a gift to packet sniffers. Authenticate during the handshake with a short-lived token in the connection URL or a cookie, not with a long-lived credential the client must store. Validate the Origin header server-side so a hostile page cannot open sockets to your infrastructure using the victim's ambient credentials, and rate-limit subscriptions per connection so one client cannot ask for every channel at once.
Common Mistakes
Assuming the connection stays alive through proxies and mobile networks
Fix: Send heartbeats under the idle timeout and treat every open as a fresh session.
Reconnecting with a fixed one-second interval
Fix: Use exponential backoff with jitter to avoid thundering herds after a server restart.
Putting recovery logic in the error handler
Fix: Diagnose from the close event's code; error only signals that a failure occurred.
Losing messages sent while disconnected
Fix: Queue them client-side and re-send after open, with sequence numbers and server acks.
Skipping the Origin check on the server
Fix: Validate origins and authenticate during the handshake, not on the first message.
Best Practices
- Prefer SSE when updates are one-directional; reserve WebSockets for genuinely interactive traffic.
- Frame every message with a type field and version the protocol from the first release.
- Surface connection state in the UI so users know when data may be stale.
- Keep payloads small and prefer binary frames for non-JSON data.
Key Takeaways
- A WebSocket is one full-duplex connection established by an HTTP upgrade; either side can speak first.
- Errors do not carry details β the close code is what your reconnect policy should key off.
- Heartbeats, exponential backoff with jitter, and queued re-sends are the three pillars of a reliable client.
- Message framing is your protocol: type fields, sequence numbers, and acknowledgements make it trustworthy.
- For one-way feeds, SSE is simpler and reconnects for itself; WebSockets earn their complexity with interactive traffic.
- Use wss, authenticate at handshake, validate Origin, and rate-limit subscriptions.