The first WebSocket app I shipped worked great in dev and died on the second production pod. The reason was simple and embarrassing: each pod kept its own connection registry, so a user connected to pod A couldn't send a message to a user connected to pod B. The "real-time" chat was actually "real-time if you happen to land on the same server." That's the moment you learn that WebSockets at scale is a distributed systems problem dressed up as a frontend feature.

This article is the WebSocket playbook: when to use them, how to build them, and the architecture you need to scale past a single process.

When to actually use WebSockets

WebSockets are not the default for "real-time" features. They're the right tool when you need bidirectional, low-latency, server-pushed communication. Most "real-time" needs are actually one-directional, and Server-Sent Events (SSE) is simpler and just as fast.

Use case Right tool Why
Live notifications SSE One-way, server→client
Activity feed SSE One-way, server→client
Chat WebSockets Bidirectional, low latency
Multiplayer game WebSockets Bidirectional, high frequency
Live dashboards SSE One-way, server→client
Collaborative editing WebSockets Bidirectional, ordering matters
File upload progress SSE One-way, server→client
Stock ticker SSE One-way, server→client

If you're reaching for WebSockets and the data only flows server→client, use SSE. It's HTTP, it auto-reconnects, it works through proxies, and you don't need a custom protocol. Your ops team will thank you.

The case for WebSockets is bidirectional. If clients are sending frequent messages back (typing indicators, cursor positions, game moves), WebSockets avoid the per-request overhead of HTTP.

The library landscape

Node.js:ws vs Socket.io

ws is a low-level WebSocket implementation. Socket.io is a framework built on top of WebSockets (with a long-polling fallback) that adds rooms, namespaces, auto-reconnect, and acknowledgements.

Use ws when:

  • You want maximum throughput and minimum overhead.
  • You're building your own protocol on top.
  • You're scaling horizontally with Redis pub/sub anyway.

Use Socket.io when:

  • You need rooms/namespaces out of the box.
  • You want client auto-reconnect without writing it.
  • You have a small team and want batteries included.

Socket.io's overhead is real: ~2x the per-message size and ~30% lower throughput than raw ws in benchmarks. For most apps that doesn't matter. For 10k+ connections per server, it does.

Python:websockets vs FastAPI WebSocket

websockets is the de facto Python WebSocket library. FastAPI wraps it for integration with the rest of your API.

BashCopy 

pip install websockets fastapi uvicorn redis

I'll show both Node.js and Python examples below. The architecture is the same.

A simple Node.js WebSocket server

JavaScriptCopy 


javascript
// server.js
import { WebSocketServer } from "ws"
import http from "http"
import { parse } from "url"
import { verifyJwt } from "./auth.js"

const server = http.createServer()
const wss = new WebSocketServer({ noServer: true })

const clients = new Map() // userId -> Set

server.on("upgrade", (req, socket, head) => {
const { query } = parse(req.url, true)
const token = query.token

let userId
try {
const payload = verifyJwt(token)
userId = payload.sub
} catch (err) {
socket.write("HTTP/1.1 401 Unauthorized

")
socket.destroy()
return
}

wss.handleUpgrade(req, socket, head, (ws) => {
ws.userId = userId
ws.isAlive = true

if (!clients.has(userId)) clients.set(userId, new Set())
clients.get(userId).add(ws)

wss.emit("connection", ws, req)
})
})

wss.on("connection", (ws) => {
ws.on("pong", () => { ws.isAlive = true })

ws.on("message", (raw) => {
let msg
try {
msg = JSON.parse(raw.toString())
} catch {
ws.send(JSON.stringify({ type: "error", error: "invalid_json" }))
return
}

if (msg.type === "direct_message") {
const target = clients.get(msg.to)
if (target) {
for (const peer of target) {
if (peer.readyState === ws.OPEN) {
peer.send(JSON.stringify({
type: "direct_message",
from: ws.userId,
text: msg.text,
at: Date.now(),
}))
}
}
}
}
})

ws.on("close", () => {
const userSockets = clients.get(ws.userId)
if (userSockets) {
userSockets.delete(ws)
if (userSockets.size === 0) clients.delete(ws.userId)
}
})

ws.send(JSON.stringify({ type: "connected", userId: ws.userId }))
})

// Heartbeat
const interval = setInterval(() => {
wss.clients.forEach((ws) => {
if (!ws.isAlive) return ws.terminate()
ws.isAlive = false
ws.ping()
})
}, 30000)

wss.on("close", () => clearInterval(interval))

server.listen(8080, () => console.log("WS server on :8080"))


markdown

This handles the basics: JWT auth in the upgrade handshake, per-user connection registry, JSON message protocol, heartbeat to detect dead connections. It does not handle horizontal scaling.

The horizontal scaling problem

Run two pods of the above server behind a load balancer. User A connects to pod 1, user B connects to pod 2. User A sends a direct message to user B. Pod 1 looks in its local clients map, finds nothing, drops the message. User B never sees it.

This is the WebSocket scaling problem in one sentence. Solutions:

  1. Sticky sessions (load balancer routes user A to pod 1 always): solves the "where is user A" question but doesn't solve "user A wants to reach user B on pod 2." Doesn't work for fanout.
  2. Full mesh (every pod connects to every other pod): works for small clusters (3-5 pods), falls apart at scale.
  3. Pub/sub broker (Redis, NATS, Kafka): each pod subscribes to a channel, publishes messages it can't deliver locally. This is the right answer for almost everyone.

Redis pub/sub architecture

CodeCopy 


plaintext
┌──────────────┐
│ Load Balancer│
└──────┬───────┘
│
┌──────────────┼──────────────┐
│ │ │
┌────▼────┐ ┌────▼────┐ ┌────▼────┐
│ Pod 1 │ │ Pod 2 │ │ Pod 3 │
│ clients │ │ clients │ │ clients │
│ {A,B} │ │ {C,D} │ │ {E,F} │
└────┬────┘ └────┬────┘ └────┬────┘
│ │ │
└──────────────┼──────────────┘
│
┌──────▼───────┐
│ Redis │
│ pub/sub │
└──────────────┘


markdown

Each pod maintains its local connection registry AND subscribes to Redis channels. When a pod receives a message destined for a user not in its local registry (or for a fanout), it publishes to Redis. All pods receive the publication and check their local registry.

Node.js with Redis

JavaScriptCopy 


javascript
// server-scaled.js
import { WebSocketServer } from "ws"
import http from "http"
import { parse } from "url"
import { createClient } from "redis"
import { verifyJwt } from "./auth.js"

const POD_ID = process.env.POD_ID || pod-${Math.random().toString(36).slice(2, 8)}
const REDIS_URL = process.env.REDIS_URL || "redis://localhost:6379"

const pub = createClient({ url: REDIS_URL })
const sub = createClient({ url: REDIS_URL })
await Promise.all([pub.connect(), sub.connect()])

const server = http.createServer()
const wss = new WebSocketServer({ noServer: true })
const clients = new Map() // userId -> Set

// Subscribe to user-specific channels
await sub.subscribe("user:*", (raw, channel) => {
const userId = channel.split(":")[1]
const peers = clients.get(userId)
if (!peers) return
const msg = JSON.parse(raw)
for (const peer of peers) {
if (peer.readyState === peer.OPEN) peer.send(raw)
}
}, true) // pattern subscription

// Subscribe to broadcast channel
await sub.subscribe("broadcast", (raw) => {
for (const ws of wss.clients) {
if (ws.readyState === ws.OPEN) ws.send(raw)
}
})

server.on("upgrade", (req, socket, head) => {
const { query } = parse(req.url, true)
let userId
try {
userId = verifyJwt(query.token).sub
} catch {
socket.write("HTTP/1.1 401 Unauthorized

")
socket.destroy()
return
}

wss.handleUpgrade(req, socket, head, (ws) => {
ws.userId = userId
ws.isAlive = true
if (!clients.has(userId)) clients.set(userId, new Set())
clients.get(userId).add(ws)
wss.emit("connection", ws, req)
})
})

wss.on("connection", (ws) => {
ws.on("pong", () => { ws.isAlive = true })

ws.on("message", (raw) => {
let msg
try { msg = JSON.parse(raw.toString()) } catch { return }

if (msg.type === "direct_message") {
// Try local first
const local = clients.get(msg.to)
const deliveredLocally = local && [...local].some(peer => peer.readyState === peer.OPEN)

// Always publish to Redis (handles cross-pod + multi-device)
pub.publish(user:${msg.to}, JSON.stringify({
type: "direct_message",
from: ws.userId,
text: msg.text,
at: Date.now(),
}))

if (deliveredLocally) {
// Local delivery will happen via Redis subscription echo
// This avoids double-delivery: don't send directly here
}
}

if (msg.type === "broadcast") {
pub.publish("broadcast", JSON.stringify({
type: "broadcast",
from: ws.userId,
text: msg.text,
at: Date.now(),
}))
}
})

ws.on("close", () => {
const userSockets = clients.get(ws.userId)
if (userSockets) {
userSockets.delete(ws)
if (userSockets.size === 0) {
clients.delete(ws.userId)
// Notify other pods this user is offline (optional)
pub.publish("presence:offline", JSON.stringify({ userId: ws.userId }))
}
}
})
})

const interval = setInterval(() => {
wss.clients.forEach((ws) => {
if (!ws.isAlive) return ws.terminate()
ws.isAlive = false
ws.ping()
})
}, 30000)

wss.on("close", () => clearInterval(interval))
server.listen(8080, () => console.log(${POD_ID} listening on :8080))


plaintext

A subtlety: when pod 1 publishes to user:A and pod 1 also has user A connected, pod 1 will receive its own publication. That's fine-dedupe on message ID if you need exactly-once. The simpler approach: always publish to Redis, let every pod (including the sender) deliver via subscription. Single code path, no double-delivery.

Redis Streams vs Redis Pub/Sub

Pub/Sub is fire-and-forget. If a pod is briefly disconnected from Redis, messages are lost. For chat where message loss is unacceptable, use Redis Streams:

JavaScriptCopy 


javascript
// Publishing to a stream
await pub.xAdd("messages:global", "*", {
type: "direct_message",
from: ws.userId,
to: msg.to,
text: msg.text,
at: Date.now().toString(),
})

// Consuming from a stream with consumer group
await sub.xReadGroup(
"GROUP", "ws-pods", POD_ID,
"COUNT", 100,
"BLOCK", 5000,
"STREAMS", "messages:global", ">"
)


markdown

Streams persist messages, support consumer groups (each message goes to one pod in the group), and let you replay. Use Streams for chat. Use Pub/Sub for ephemeral signals like presence.

Python with FastAPI

The same architecture in Python:

PythonCopy 


python

main.py

import asyncio
import json
import os
from contextlib import asynccontextmanager
from fastapi import FastAPI, WebSocket, WebSocketDisconnect, Query, status
from redis.asyncio import Redis
import jwt

POD_ID = os.getenv("POD_ID", f"pod-{os.urandom(4).hex()}")
JWT_SECRET = os.getenv("JWT_SECRET", "dev-secret")
REDIS_URL = os.getenv("REDIS_URL", "redis://localhost:6379")

redis: Redis = None
clients: dict[str, set[WebSocket]] = {}

async def redis_listener():
pubsub = redis.pubsub()
await pubsub.psubscribe("user:*", "broadcast")
async for message in pubsub.listen():
if message["type"] != "pmessage":
continue
channel = message["channel"].decode()
raw = message["data"].decode()
if channel == "broadcast":
await _broadcast(raw)
elif channel.startswith("user:"):
user_id = channel.split(":", 1)[1]
await _send_to_user(user_id, raw)

async def _send_to_user(user_id: str, raw: str):
peers = clients.get(user_id, set())
dead = []
for ws in peers:
try:
await ws.send_text(raw)
except Exception:
dead.append(ws)
for ws in dead:
peers.discard(ws)

async def _broadcast(raw: str):
for user_peers in clients.values():
for ws in list(user_peers):
try:
await ws.send_text(raw)
except Exception:
pass

@asynccontextmanager
async def lifespan(app: FastAPI):
global redis
redis = Redis.from_url(REDIS_URL, decode_responses=False)
listener_task = asyncio.create_task(redis_listener())
yield
listener_task.cancel()
await redis.close()

app = FastAPI(lifespan=lifespan)

def verify_jwt(token: str) -> str:
payload = jwt.decode(token, JWT_SECRET, algorithms=["HS256"])
return payload["sub"]

@app.websocket("/ws")
async def websocket_endpoint(ws: WebSocket, token: str = Query(...)):
try:
user_id = verify_jwt(token)
except jwt.PyJWTError:
await ws.close(code=status.WS_1008_POLICY_VIOLATION)
return

await ws.accept()
clients.setdefault(user_id, set()).add(ws)
await ws.send_text(json.dumps({"type": "connected", "userId": user_id}))

try:
while True:
raw = await ws.receive_text()
try:
msg = json.loads(raw)
except json.JSONDecodeError:
await ws.send_text(json.dumps({"type": "error", "error": "invalid_json"}))
continue

if msg.get("type") == "direct_message":
await redis.publish(f"user:{msg['to']}", json.dumps({
"type": "direct_message",
"from": user_id,
"text": msg["text"],
"at": int(import("time").time() * 1000),
}))
elif msg.get("type") == "broadcast":
await redis.publish("broadcast", json.dumps({
"type": "broadcast",
"from": user_id,
"text": msg["text"],
}))
except WebSocketDisconnect:
pass
finally:
peers = clients.get(user_id, set())
peers.discard(ws)
if not peers:
clients.pop(user_id, None)
await redis.publish("presence:offline", json.dumps({"userId": user_id}))


markdown

Run with uvicorn main:app --host 0.0.0.0 --port 8080 --workers 1. Use exactly one worker per process-multiple workers can't share the in-process clients dict. Scale horizontally by running more pods, not more workers.

Authentication patterns

Three common approaches:

  1. Token in query string (ws://host/ws?token=...): simple, works everywhere, but tokens end up in proxy logs. Use short-lived tokens.
  2. Cookie-based: WebSocket upgrades include cookies. Best if your auth is already cookie-based and same-origin.
  3. First-message auth: accept the connection, wait for an auth message, close if it doesn't arrive within 5 seconds. Avoids logging tokens but adds a round-trip.

I prefer short-lived query-string tokens minted from your HTTP API:

TypeScriptCopy 


javascript
// POST /api/ws-token → { token, expiresAt }
import jwt from "jsonwebtoken"

app.post("/api/ws-token", requireAuth, (req, res) => {
const token = jwt.sign(
{ sub: req.user.id },
process.env.WS_JWT_SECRET,
{ expiresIn: "5m" } // short-lived
)
res.json({ token, expiresAt: Date.now() + 5 * 60 * 1000 })
})


markdown

The client mints a token from your HTTP API, then opens the WebSocket with that token. Tokens expire in 5 minutes, so even if logged, they're useless quickly.

Heartbeat and dead connection cleanup

Half-open connections (client died without sending FIN) are the silent killer of WebSocket servers. Without active heartbeat, your clients map fills with ghosts, you waste memory, and you waste Redis publishes.

The pattern: server pings every 30s, client must pong. If no pong in 30s, terminate.

JavaScriptCopy 


javascript
const HEARTBEAT_MS = 30000

const interval = setInterval(() => {
wss.clients.forEach((ws) => {
if (ws.isAlive === false) {
console.log(terminating dead connection for ${ws.userId})
return ws.terminate()
}
ws.isAlive = false
ws.ping()
})
}, HEARTBEAT_MS)


plaintext

The ws library handles pings automatically when you set ws.isAlive = false before sending ping and reset it on pong event. Don't skip this. Without it, your server will gradually OOM under connection churn.

For Python/websockets, the library has built-in ping:

PythonCopy 


python
import websockets
from websockets.exceptions import ConnectionClosed

async def handler(ws):
try:
await asyncio.wait_for(ws.recv(), timeout=60)
except (asyncio.TimeoutError, ConnectionClosed):
await ws.close()


markdown

Backpressure

When a client is slow (mobile on bad network, paused tab), ws.send() returns immediately but data piles up in the kernel send buffer. Eventually you OOM.

For ws in Node.js, check ws.bufferedAmount:

JavaScriptCopy 


javascript
function sendSafe(ws, message) {
const data = typeof message === "string" ? message : JSON.stringify(message)
if (ws.bufferedAmount > 1024 * 1024) { // 1MB backlog
console.warn(backpressure: closing slow client ${ws.userId})
ws.close(1009, "backpressure")
return false
}
ws.send(data)
return true
}


plaintext

In Python with websockets, send() returns an awaitable that resolves when the data is flushed. If you're sending faster than the client can receive, you'll back up. Use a queue with a max size:

PythonCopy 


python
import asyncio

MAX_QUEUE = 100

class SafeConnection:
def init(self, ws):
self.ws = ws
self.queue: asyncio.Queue = asyncio.Queue(maxsize=MAX_QUEUE)
self.task = asyncio.create_task(self._pump())

async def _pump(self):
try:
while True:
msg = await self.queue.get()
await self.ws.send(msg)
except Exception:
pass

async def send(self, msg):
if self.queue.full():
await self.ws.close(code=1013) # try again later
raise RuntimeError("client too slow")
await self.queue.put(msg)

async def close(self):
self.task.cancel()
await self.ws.close()


markdown

Production deployment

Nginx reverse proxy

nginxCopy 


nginx
upstream ws_backend {
server pod1:8080;
server pod2:8080;
server pod3:8080;
}

server {
listen 443 ssl http2;
server_name ws.example.com;

ssl_certificate /etc/ssl/cert.pem;
ssl_certificate_key /etc/ssl/key.pem;

location /ws {
proxy_pass http://ws_backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;

proxy_read_timeout 86400s;
proxy_send_timeout 86400s;
proxy_buffering off;
}
}


markdown

The timeouts matter. Nginx defaults to 60s read timeout, which closes idle WebSocket connections. Set it to 24h or longer.

Sticky sessions (if you need them)

You usually don't, because Redis pub/sub handles cross-pod delivery. But for stateful protocols where session affinity matters:

nginxCopy 


nginx
upstream ws_backend {
hash $arg_user_id consistent;
server pod1:8080;
server pod2:8080;
}


plaintext

Hash on user ID so the same user always lands on the same pod. The risk: rebalancing when pods come and go redistributes everyone.

Kubernetes

YAMLCopy 


yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: ws-server
spec:
replicas: 3
selector:
matchLabels: { app: ws-server }
template:
metadata:
labels: { app: ws-server }
spec:
containers:

  • name: ws image: my-ws-server:latest ports: [{ containerPort: 8080 }] env:
  • { name: REDIS_URL, value: "redis://redis:6379" }
  • { name: JWT_SECRET, valueFrom: { secretKeyRef: { name: ws-secrets, key: jwt-secret } } } resources: requests: { cpu: "200m", memory: "256Mi" } limits: { cpu: "1", memory: "512Mi" } readinessProbe: httpGet: { path: /healthz, port: 8080 } initialDelaySeconds: 5 livenessProbe: httpGet: { path: /healthz, port: 8080 } initialDelaySeconds: 15 --- apiVersion: v1 kind: Service metadata: name: ws-server spec: selector: { app: ws-server } ports: [{ port: 8080, targetPort: 8080 }]


plaintext

Add an HTTP /healthz endpoint to your server that checks Redis connectivity:

JavaScriptCopy 


javascript
server.on("request", (req, res) => {
if (req.url === "/healthz") {
if (pub.isOpen && sub.isOpen) {
res.writeHead(200).end("ok")
} else {
res.writeHead(503).end("redis down")
}
}
})


markdown

Monitoring

Metrics that matter for WebSocket servers:

  • Active connections: per pod and aggregate. Alert on sudden drops (could indicate network issues or pod crashes).
  • Messages/sec in/out: throughput.
  • Message latency p95/p99: from receive to delivery.
  • Redis pub/sub lag: if your listener falls behind, messages pile up.
  • Memory per connection: should be stable. Growth means a leak.
  • Dead connection cleanup rate: high rate means clients are dying without closing.
  • Auth failure rate: spikes indicate scanning or token leakage.

Prometheus metrics in Node.js with prom-client:

JavaScriptCopy 


javascript
import client from "prom-client"
const registry = new client.Registry()

const activeConnections = new client.Gauge({
name: "ws_active_connections",
help: "Active WebSocket connections",
registers: [registry],
})

const messagesIn = new client.Counter({
name: "ws_messages_in_total",
help: "Messages received from clients",
registers: [registry],
})

const messagesOut = new client.Counter({
name: "ws_messages_out_total",
help: "Messages sent to clients",
registers: [registry],
})

// Update gauges on connect/disconnect
activeConnections.set(wss.clients.size)

// Expose
server.on("request", async (req, res) => {
if (req.url === "/metrics") {
res.writeHead(200, { "Content-Type": registry.contentType })
res.end(await registry.metrics())
}
})


markdown

Common mistakes

No heartbeat: dead connections accumulate, memory grows, server eventually OOMs. Always implement ping/pong with timeout.

Token in URL without short expiry: tokens end up in nginx/CDN logs. Use 5-minute tokens minted from your HTTP API.

Multiple workers per process: in-process clients dict can't be shared across workers. Run one worker per process, scale with pods.

Missing proxy_buffering off in nginx: nginx buffers WebSocket frames, breaking real-time delivery. Always disable buffering for WS routes.

No backpressure handling: slow clients cause OOM. Check bufferedAmount (Node) or use bounded queues (Python).

Using Socket.io without Redis adapter: Socket.io's default adapter is in-memory. Multi-pod deployments silently drop cross-pod messages. Use @socket.io/redis-adapter.

Authenticating after accept: accepting the WebSocket and then checking auth lets attackers hold connections open. Reject at the HTTP upgrade level before accepting.

Forgetting to clean up on disconnect: every connection you don't remove from your registry is a memory leak and a phantom-message recipient.

Long-running handlers blocking the event loop: in Node.js, a synchronous JSON.stringify of a 5MB message blocks all other connections. Use streaming or chunk large payloads.

Troubleshooting real production issues

Symptom: Connections drop after 60 seconds.
Cause: Nginx default read timeout.
Fix: set proxy_read_timeout 86400s; on the WS location.

Symptom: Memory grows linearly over hours.
Cause: dead connections not cleaned up, or disconnected clients still in clients map.
Fix: verify heartbeat is running and close handler removes from the map.

Symptom: Messages sometimes delivered twice.
Cause: pod sends locally AND via Redis.
Fix: pick one path. Either always go through Redis (recommended) or skip local delivery when you publish.

Symptom: Cross-pod messages lost under load.
Cause: Redis pub/sub drops messages when subscriber is briefly disconnected, or listener task is blocked.
Fix: use Redis Streams for durability, or ensure the listener never blocks.

Symptom: Connection works from dev machine, fails from corporate network.
Cause: corporate proxy doesn't support WebSocket upgrade.
Fix: Socket.io's polling fallback helps here. For raw ws, you need a TURN-like relay or wss-over-HTTP fallback.

Symptom: p99 latency spikes when a pod is deploying.
Cause: pod drains instantly, clients reconnect simultaneously, thundering herd.
Fix: drain gracefully-send close code 1001 (going away), give clients 5-10 seconds to reconnect, then terminate.

Security

  • Origin check: reject upgrades from unknown origins to prevent cross-site WebSocket hijacking.
JavaScriptCopy 


javascript
const ALLOWED_ORIGINS = new Set(["https://app.example.com", "https://staging.example.com"])

server.on("upgrade", (req, socket) => {
const origin = req.headers.origin
if (!ALLOWED_ORIGINS.has(origin)) {
socket.write("HTTP/1.1 403 Forbidden

")
socket.destroy()
return
}
// ... rest of upgrade
})


markdown

  • Rate limiting: per-user message rate, per-IP connection rate. Without it, a single client can DoS your server.
  • Message size limits: reject frames over a sensible size (1MB for chat, more for file transfer). The default in some libraries is unbounded.
  • Input validation: every message must be validated with a schema (zod, pydantic). Never trust incoming JSON.
JavaScriptCopy 


typescript
import { z } from "zod"

const MessageSchema = z.discriminatedUnion("type", [
z.object({ type: z.literal("direct_message"), to: z.string().uuid(), text: z.string().max(2000) }),
z.object({ type: z.literal("broadcast"), text: z.string().max(2000) }),
z.object({ type: z.literal("typing"), to: z.string().uuid() }),
])

ws.on("message", (raw) => {
let parsed
try { parsed = JSON.parse(raw.toString()) } catch { return ws.close(1003) }
const result = MessageSchema.safeParse(parsed)
if (!result.success) return ws.send(JSON.stringify({ type: "error", error: result.error.message }))
// ... dispatch
})


markdown

Testing

Unit tests for handlers are easy. Integration tests for the full connection lifecycle are harder but more valuable.

TypeScriptCopy 


javascript
import { test, expect } from "vitest"
import { WebSocket } from "ws"
import { startServer } from "./server"

test("user receives direct message from another user", async () => {
const server = await startServer({ port: 0 })
const port = server.address().port

const alice = new WebSocket(ws://localhost:${port}/ws?token=${await mintToken("alice")})
const bob = new WebSocket(ws://localhost:${port}/ws?token=${await mintToken("bob")})

await Promise.all([once(alice, "open"), once(bob, "open")])

const received = new Promise((resolve) => {
bob.on("message", (raw) => {
const msg = JSON.parse(raw.toString())
if (msg.type === "direct_message" && msg.from === "alice") {
expect(msg.text).toBe("hi bob")
resolve()
}
})
})

alice.send(JSON.stringify({ type: "direct_message", to: "bob", text: "hi bob" }))
await received

alice.close(); bob.close()
server.close()
})

Always test the reconnect path, the auth-rejection path, and the backpressure path. Those are the three that break in production.

Cost considerations

WebSocket connections are expensive compared to HTTP. A connection holds memory (50KB-500KB depending on library and buffers), keeps a file descriptor open, and consumes CPU for heartbeat processing.

  • Per-connection memory: 100KB for ws, 200KB for Socket.io, 150KB for Python websockets.
  • Connections per pod: realistic ceiling is ~10k for Node.js on a 512MB pod, ~50k on a 2GB pod. Python is ~30-50% lower.
  • Redis bandwidth: every message crosses Redis twice (publish + subscribe). For 1000 msgs/sec at 1KB each, that's 2MB/sec through Redis-trivial. For 10k msgs/sec, you need a Redis cluster.

Rough cost for a 10k concurrent connection chat service:

  • 3 pods × 2 vCPU / 2GB RAM: ~$150/month on AWS.
  • Redis cache.r6g.large: ~$150/month.
  • Load balancer + bandwidth: ~$50/month.
  • Total: ~$350/month for 10k concurrent users, not counting your app servers.

Real-world use cases

  • Customer support chat: 5k concurrent agents + customers, ws + Redis Streams for message durability, ~$300/month.
  • Multiplayer game lobby: 500 concurrent players, Socket.io with Redis adapter, ~$80/month.
  • Live trading dashboard: SSE for prices, WebSocket for order updates, 2k concurrent traders, ~$400/month.
  • Collaborative doc editor: WebSockets with CRDT sync, 200 concurrent editors per doc, ~$200/month.

Conclusion

WebSocket servers are easy to build and easy to scale badly. The pattern that works in production: pick ws or websockets for the implementation, Redis for cross-pod pub/sub, heartbeat for dead connection cleanup, backpressure handling for slow clients, short-lived tokens for auth, and an origin check for security. Get those right and your "real-time" feature will actually be real-time at scale. Skip the Redis broker and you'll discover the hard way that real-time only works when you're lucky enough to land on the same pod as your recipient.

Originally published on Mango Developer.