Last year I was paged at 2:13 AM because a real-time collaboration feature that had passed load testing with 5,000 concurrent users collapsed at 18,000. The culprit wasn't CPU or memory — it was file descriptor exhaustion on our WebSocket edge nodes, compounded by a reconnection storm that multiplied traffic 40x in under 90 seconds. If you've only built REST APIs where each request is isolated and stateless, persistent connections will force you to rethink everything from load balancing to deployment strategy. WebSockets are deceptively simple to prototype and surprisingly difficult to scale without careful architecture.
Beyond Request-Response: Where Polling and Long-Polling Fall Apart
In my experience, most teams adopt WebSockets for the wrong reason first — they want to avoid polling. A client polling every two seconds seems harmless until you multiply it. With 50,000 active clients, that's 25,000 requests per second, and 99% of those responses are empty 304 Not Modified or { "hasUpdate": false }. You're paying for connection setup, TLS termination, header parsing, authentication, and logging for nothing.
Long-polling tries to paper over this by holding the request open until data arrives. It reduces empty responses but introduces its own pathology: it holds server threads or event loop slots hostage, it breaks with aggressive mobile network timeouts, and it still pays the full HTTP overhead on every cycle. I once maintained a long-polling notification system that worked fine until we put it behind an AWS ALB with a 60-second idle timeout — the ALB killed held connections before our application did, creating a constant churn of re-establishes that looked like a DDoS from our own clients.
WebSockets solve this by upgrading a single HTTP request into a persistent, full-duplex TCP connection with a lightweight framing protocol. After the handshake, there are no headers, no cookies, no re-authentication per message. A minimal frame is just 2-14 bytes of overhead. That efficiency is what lets you push 100,000 messages per second from a single node, but it comes at a cost: the server now holds state. The connection itself is state, and state is what makes distributed systems hard.
This is a fundamental shift from the stateless philosophy I detail in REST API Design: Principles That Stand the Test of Time. With REST, any server can handle any request. With WebSockets, the server that holds the socket is the server that must deliver the message. Your architecture has to account for routing messages to the right process on the right machine.
When Not to Reach for WebSockets
Not every real-time requirement needs a persistent socket. I've found that Server-Sent Events (SSE) are superior for one-way server-to-client streams like live dashboards or log tailing — they're just HTTP, they auto-reconnect, and they work through corporate proxies that block Upgrade headers. If you need bidirectional streaming between services rather than browsers, gRPC for Microservice Communication: Protocol Buffers and Streaming gives you backpressure and strongly typed contracts that WebSockets lack. Use WebSockets when you need low-latency, bidirectional communication with browsers or mobile clients and you can justify managing connection state.
The WebSocket Handshake and Frame Protocol Under the Hood
Understanding the wire protocol prevents a class of bugs that are impossible to diagnose from application logs alone. The handshake is defined in IETF RFC 6455 and starts as a normal HTTP/1.1 GET with two critical headers:
GET /realtime HTTP/1.1
Host: api.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
Origin: https://app.example.com
Authorization: Bearer eyJhbGciOiJIUzI1NiIs...
The server validates the Origin, authenticates the request, and if it agrees to upgrade, responds with 101 Switching Protocols and a Sec-WebSocket-Accept hash derived from the client's key. From that point forward, the protocol is no longer HTTP. Both sides speak WebSocket frames. This is why you cannot authenticate subsequent messages with HTTP middleware — there is no HTTP.
I see teams make the mistake of putting the auth token in the query string because the browser WebSocket API doesn't allow custom headers. Don't do this — URLs get logged in proxies and access logs. In production I use a ticket pattern: the client first calls a REST endpoint over HTTPS with its Bearer token, receives a one-time, short-lived ticket (e.g., 10 seconds, single-use, stored in Redis), and then presents that ticket as the first message or subprotocol after connecting. The server validates and immediately invalidates the ticket. This keeps tokens out of logs and still works with the browser API.
Frame Anatomy and Why It Matters for Performance
Each WebSocket frame has a minimal header: FIN bit, opcode (text, binary, close, ping, pong), mask bit, payload length, and masking key if client-to-server. The payload is not encrypted by the WebSocket protocol itself — you rely on wss:// (TLS). According to MDN Web Docs, the browser will automatically handle ping/pong frames, but in Node.js, Python, or Go you must handle them explicitly. I've debugged memory leaks where a server never responded to pings and the client kept buffering messages until it OOMed.
Use binary frames (opcode 0x2) with MessagePack or Protobuf when throughput matters. JSON over text frames is fine for 100 messages per second, but at 10k messages per second the serialization cost dominates. One trading platform I worked on cut CPU usage by 31% simply by switching from JSON text frames to binary frames with a compact schema. The trade-off is debuggability, so I recommend supporting both via content negotiation during handshake — a custom Sec-WebSocket-Protocol: json, msgpack header works well.
Designing a Stateful Connection Layer Behind a Stateless Load Balancer
The single most important architectural decision is to separate your connection tier from your application tier. Do not put WebSocket handling inside your monolithic API server. Instead, deploy a dedicated fleet of edge gateways whose only job is to hold connections and translate between sockets and your internal message bus.
My preferred topology looks like this: Layer 4 load balancer (NLB or HAProxy in TCP mode) -> Stateless connection gateways (Go or Node.js) -> Redis / NATS / Kafka -> Stateless application services. The L4 balancer is critical. Layer 7 balancers that understand HTTP can interfere with the Upgrade. I've watched an ALB silently buffer small WebSocket frames for 40ms trying to coalesce them, adding jitter that destroyed our latency SLA. Use TCP passthrough so the gateway terminates the WebSocket itself.
Each gateway maintains an in-memory map of connectionId -> socket and subscribes to the internal pub/sub only for topics its connected clients care about. This is a fan-out pattern. When an application service publishes order:4821:updated, the message bus delivers it to all gateways, but only the gateway holding the user subscribed to order 4821 forwards it down the socket.
// Node.js connection gateway with authentication via ticket
import { WebSocketServer } from 'ws';
import Redis from 'ioredis';
const wss = new WebSocketServer({ port: 8080 });
const pub = new Redis(process.env.REDIS_URL);
const sub = new Redis(process.env.REDIS_URL);
// Each gateway subscribes to a pattern, filters locally
sub.psubscribe('events:*');
sub.on('pmessage', (pattern, channel, message) => {
const { roomId } = JSON.parse(message);
// Only send to sockets that joined this room
wss.clients.forEach((ws) => {
if (ws.readyState === 1 && ws.rooms.has(roomId)) {
ws.send(message, { binary: false });
}
});
});
wss.on('connection', async (ws, req) => {
// Ticket validation must happen before any subscription
const ticket = new URL(req.url, 'http://localhost').searchParams.get('ticket');
const user = await validateTicket(ticket); // Redis lookup + delete
if (!user) return ws.close(4001, 'Unauthorized');
ws.userId = user.id;
ws.rooms = new Set();
ws.isAlive = true;
ws.on('pong', () => { ws.isAlive = true; });
ws.on('message', (data) => handleClientMessage(ws, data));
});
// Heartbeat to detect half-open connections
setInterval(() => {
wss.clients.forEach((ws) => {
if (ws.isAlive === false) return ws.terminate();
ws.isAlive = false;
ws.ping();
});
}, 30000);
Notice the heartbeat. Without it, you will accumulate half-open connections from clients that lost network without sending a close frame. I've seen gateways with 80k connections where 20k were ghosts, holding file descriptors and memory. The ping interval of 25-30 seconds is intentional — it keeps the connection alive through most NAT and proxy idle timeouts (which are often 60 seconds) while not being chatty.
Sticky Sessions Are an Anti-Pattern — Use a Backplane Instead
Some tutorials suggest enabling IP-hash sticky sessions so a client always returns to the same gateway. This fails during rolling deploys and auto-scaling events. If you terminate the gateway holding 10k connections, those clients reconnect and all land on one remaining node, creating a thundering herd. The correct approach is to make any gateway able to serve any client by using a shared pub/sub backplane. When you need to send a message to a specific user, publish to user:{userId}:inbox and whichever gateway holds that user's socket will deliver it. This also lets you scale gateways horizontally without rebalancing.
Horizontal Scaling With Redis Pub/Sub, Presence, and Room Management
For many teams, Redis is the pragmatic backplane. It's operationally simple and fast enough for 100k-500k concurrent connections. Beyond that, I've migrated to NATS JetStream or Kafka for persistence, but Redis is an excellent starting point. The key is to never use Redis as a message store for WebSockets — use it as an ephemeral relay. If a client is offline when a message is published, that message should be retrieved via a separate REST endpoint on reconnect, not queued in Redis indefinitely.
Room and presence management is where complexity explodes. A naive SADD room:123 user:456 on every join and SREM on disconnect will lose data when a gateway crashes without cleaning up. I use expiring presence keys with heartbeats:
# Python presence service using redis-py with expiring keys
import asyncio
import redis.asyncio as redis
from uuid import uuid4
r = redis.from_url("redis://localhost", decode_responses=True)
INSTANCE_ID = f"gw:{uuid4().hex[:8]}"
async def join_room(user_id: str, room_id: str):
# Presence key expires in 45s; gateway must refresh every 30s
key = f"presence:{room_id}:{user_id}"
await r.set(key, INSTANCE_ID, ex=45)
await r.sadd(f"rooms:{room_id}:members", user_id)
await r.sadd(f"gateway:{INSTANCE_ID}:rooms", room_id)
async def refresh_presence():
# Called every 30s for all local connections
while True:
for user_id, room_id in local_connections:
await r.expire(f"presence:{room_id}:{user_id}", 45)
await asyncio.sleep(30)
async def get_room_members(room_id: str):
# Clean up expired members lazily
members = await r.smembers(f"rooms:{room_id}:members")
alive = []
for user_id in members:
if await r.exists(f"presence:{room_id}:{user_id}"):
alive.append(user_id)
else:
await r.srem(f"rooms:{room_id}:members", user_id)
return alive
This pattern survives gateway crashes — expired keys naturally disappear, and the lazy cleanup keeps the member set accurate. For more detailed documentation on asyncio patterns like this, the Python Documentation covers the underlying event loop mechanics that make this work at scale.
You also need to think about write amplification. If a room has 20,000 members spread across 10 gateways, a single publish results in 10 deliveries on the backplane and 20,000 socket writes. In my experience, batching helps: instead of publishing 500 small edits per second to a collaborative document, the application service aggregates them into 10 consolidated patches per second. Clients receive slightly less granular updates but your backplane throughput drops by 98%.
Backpressure, Heartbeats, and Reconnection Storms in Production
WebSockets have no built-in backpressure. If your server produces messages faster than the client's network can consume them, data buffers in memory on both sides until something crashes. Every serious gateway must implement send buffers with limits.
In Node.js, check ws.bufferedAmount before sending. In Go, use a buffered channel with a drop or coalesce policy. My rule: if bufferedAmount > 512KB for more than 5 seconds, the client is too slow — send a {type: "slow_consumer", action: "reload"} control message and close the connection with code 1013 Try Again Later. The client should reconnect with exponential backoff and request a full state snapshot via REST, then re-subscribe. This is far better than letting the gateway OOM.
Reconnection storms are the 2 AM killer I mentioned at the start. When you deploy new gateway code, you close 50,000 sockets simultaneously. If every client reconnects immediately, you create a self-inflicted DDoS. Clients must implement exponential backoff with jitter. Never let the server dictate this alone.
// Browser client with exponential backoff and jitter
class ResilientSocket {
constructor(url, ticketProvider) {
this.url = url;
this.ticketProvider = ticketProvider;
this.retryCount = 0;
this.maxDelay = 30000;
}
async connect() {
const ticket = await this.ticketProvider();
const ws = new WebSocket(`${this.url}?ticket=${ticket}`);
ws.onopen = () => {
this.retryCount = 0; // reset on successful connection
this.heartbeat = setInterval(() => ws.send(JSON.stringify({ type: 'ping' })), 25000);
};
ws.onclose = (event) => {
clearInterval(this.heartbeat);
// Don't reconnect on auth errors or normal closure
if (event.code === 4001 || event.code === 1000) return;
const base = Math.min(1000 * Math.pow(2, this.retryCount), this.maxDelay);
const jitter = base * 0.2 * Math.random();
const delay = base + jitter;
this.retryCount++;
console.warn(`Socket closed ${event.code}, reconnecting in ${Math.round(delay)}ms`);
setTimeout(() => this.connect(), delay);
};
}
}
On the server side, implement a connection rate limiter per gateway. I've found that accepting more than ~200 new connections per second per node causes TLS handshake contention. Use a token bucket and return 503 during the HTTP upgrade phase if overloaded — the client's backoff will spread the load. This connects directly to patterns I discuss in Rate Limiting Patterns for APIs: Token Bucket, Sliding Window and Beyond, but applied to connection establishment rather than REST calls.
Observability You Can't Live Without
Standard HTTP metrics miss half the picture. You must track: websocket_connections_active (gauge per gateway), websocket_messages_sent_total by opcode, websocket_buffered_bytes, websocket_handshake_duration_seconds, and pubsub_fanout_latency_seconds. Alert on connection churn rate — a sudden spike in onclose codes 1006 Abnormal Closure usually means a proxy or firewall started killing idle sockets. I also log the Sec-WebSocket-Key hash at handshake time so I can correlate load balancer logs with application logs when debugging a specific client's path.
Securing and Throttling Persistent Connections Without Killing Latency
Authentication at handshake is not enough. A hijacked socket stays open until closed. Implement periodic re-validation: every 5 minutes, verify the user's session is still valid by checking a central auth service or Redis session store. If the user logged out or their permissions changed, close the socket with 4003 Forbidden. Don't trust the socket just because it was authenticated 3 hours ago.
Authorization should be enforced on every subscription message, not just at connect. When a client sends { "subscribe": "project:884" }, check that the user still has read access to that project at that moment. I store entitlements in a short-TTL cache (60 seconds) on the gateway to avoid hitting the database on every subscribe, but invalidate immediately via pub/sub when permissions change.
Rate limiting persistent connections requires two buckets: one for connection attempts and one for messages per connection. A single malicious client can send 10,000 messages per second down one socket and saturate your fan-out. I enforce a per-socket message limit of 100 messages per second with a 200 burst, and a per-user limit across all their sockets of 300 per second. Exceeding it doesn't close the socket immediately — that would let the attacker reconnect — instead I drop messages and send a rate_limited error frame, then close if the behavior continues for 10 seconds.
| Transport | Direction | Latency Overhead | Scaling Complexity | Best For |
|---|---|---|---|---|
| WebSockets (wss) | Bidirectional | 2-14 bytes / frame | High (stateful, needs backplane) | Chat, multiplayer, collaborative editing |
| Server-Sent Events (SSE) | Server → Client only | ~200 bytes / event (HTTP) | Low (plain HTTP, stateless) | Live feeds, dashboards, notifications |
| Long Polling | Client ↔ Server (emulated) | ~800 bytes + TLS per poll | Medium (request queuing) | Legacy browser support, infrequent updates |
| gRPC Streaming | Bidirectional | 5 byte frame + Protobuf | Medium (HTTP/2, needs proxy support) | Service-to-service, strongly typed streams |
| WebTransport (HTTP/3) | Bidirectional, multi-stream | Minimal (QUIC) | Very High (emerging support) | Future low-latency media, gaming |
Finally, protect your origin. WebSockets respect the Origin header, but that header can be spoofed by non-browser clients. For browser clients, validate Origin strictly against an allowlist and set Content-Security-Policy: connect-src wss://api.example.com. For non-browser clients, require client certificates or signed tickets as described earlier. And never expose your gateway directly — put it behind a DDoS mitigation layer that understands WebSockets. Cloudflare, AWS Shield, and similar services now handle wss:// correctly, but I always verify that their "WebSocket support" means passthrough, not buffering.
Building real-time APIs that scale is less about the WebSocket protocol itself — which is elegant and minimal — and more about everything around it: connection management, backpressure, presence, failure modes, and observability. Start with a dedicated gateway fleet, a simple Redis backplane, explicit heartbeats, and client backoff with jitter. Measure fan-out latency and buffered bytes from day one. The in-memory map of sockets on a single node will take you surprisingly far; the distributed problems only appear after 50k concurrent connections, which gives you time to get the fundamentals right before you need Kafka partitions and consistent hashing.
Frequently Asked Questions
How many WebSocket connections can a single server handle?
In practice, a tuned Linux node with 4 vCPUs and 8GB RAM handles 60,000–120,000 concurrent idle connections, limited primarily by file descriptors and memory per socket (roughly 20–50KB kernel + userspace overhead each). Active connections with frequent messaging top out much earlier — around 20,000–40,000 — due to CPU for framing and pub/sub fan-out. I've found that raising ulimit -n to 500k, tuning net.core.somaxconn, and using epoll (Node.js/Go do this by default) are required before you approach those numbers. Monitor bufferedAmount and GC pauses rather than just connection count.
Should I use STOMP or plain WebSockets?
Plain WebSockets with a small JSON envelope like { "action": "subscribe", "channel": "orders:123" } is sufficient for most browser-to-server cases and keeps the gateway simple. STOMP or MQTT over WebSockets add useful conventions — destinations, acknowledgments, transactions — but they add parsing overhead and another library to audit. I recommend STOMP only if you already use RabbitMQ with STOMP or need interoperability with IoT clients speaking MQTT. Otherwise, define a minimal application protocol yourself and version it with a protocolVersion field in your first message.
How do I handle WebSocket connections during rolling deploys without disconnecting everyone?
Drain, don't kill. On SIGTERM, stop accepting new upgrades, send a control frame { "type": "going_away", "reconnect_in": 5000 } to all connected sockets, wait 10–15 seconds for clients to gracefully close and reconnect (they will land on other gateways), then close remaining sockets and exit. Use a readiness probe that fails during draining so the load balancer stops routing new connections. On the client, handle going_away by reconnecting immediately with a small random jitter (500–1500ms) rather than exponential backoff, since this is a planned migration, not a failure.
Can I use WebSockets with HTTP/2 or HTTP/3?
Standard WebSockets (RFC 6455) require HTTP/1.1 for the Upgrade handshake and cannot be multiplexed over HTTP/2's single connection — browsers open a separate HTTP/1.1 connection for wss://. RFC 8441 defines WebSockets over HTTP/2 (extended CONNECT), and support is growing in modern proxies and Chromium, but it is not yet universal. WebTransport over HTTP/3 is the successor that provides multiplexed, bidirectional streams with better head-of-line blocking behavior. For the next 1–2 years, design for HTTP/1.1 WebSockets unless you control both client and infrastructure and can verify HTTP/2 WebSocket support end-to-end.