Implementing Real-Time Communication Using WebSockets
Authenticate, reconnect and scale WebSocket servers beyond a single process.
- websockets
- real-time
- node.js
- redis
On this page ยท 15 sections
HTTP is request and response: the client asks, the server answers. Chat, live dashboards, collaborative editing and multiplayer features need the server to push data the moment it exists. WebSockets provide a persistent, two-way connection over a single TCP connection. They are simple to start and surprisingly easy to get wrong in production: authentication, dropped connections, reconnection storms and scaling across servers all need deliberate design. This guide builds a real-time server in Node.js and TypeScript that handles each of them.
Choose the right tool first
| Need | Good fit |
|---|---|
| Two-way, low-latency (chat, games, collaboration) | WebSockets |
| Server-to-client updates only (notifications, live feed) | Server-Sent Events |
| Infrequent updates, maximum simplicity | Polling |
If your use case only needs the server to push updates, SSE over plain HTTP is often simpler and works through most proxies without special configuration.
How a WebSocket connection starts
- 1HTTP upgrade request
client sends Upgrade: websocket
- 2Authenticate
validate the session or token, check the origin
- 3Connection open
two-way messages, both sides can send any time
- 4Heartbeat
ping/pong detects dead connections
The handshake is an ordinary HTTP request, which is what makes authentication at upgrade time possible: you can reject the connection before it exists.
A server with the ws library
npm install ws zodnpm install -D @types/wsHandle the upgrade yourself so you can authenticate before accepting:
// src/realtime/server.tsimport http from "node:http";import { WebSocketServer, type WebSocket } from "ws";import { authenticateRequest } from "../auth";interface Client extends WebSocket { userId?: string; isAlive?: boolean; rooms: Set<string>;}const ALLOWED_ORIGINS = new Set(["https://app.example.com"]);export function attachRealtime(server: http.Server) { const wss = new WebSocketServer({ noServer: true, maxPayload: 64 * 1024 }); server.on("upgrade", async (req, socket, head) => { try { // 1. Check the Origin header: browsers always send it for WebSockets. const origin = req.headers.origin; if (!origin || !ALLOWED_ORIGINS.has(origin)) throw new Error("Bad origin"); // 2. Authenticate with the session cookie (or a short-lived ticket). const user = await authenticateRequest(req); if (!user) throw new Error("Unauthorized"); wss.handleUpgrade(req, socket, head, (ws) => { const client = ws as Client; client.userId = user.id; client.rooms = new Set(); wss.emit("connection", client, req); }); } catch { socket.write("HTTP/1.1 401 Unauthorized\r\nConnection: close\r\n\r\n"); socket.destroy(); } }); return wss;}Three protections appear here: an origin check (browsers do not enforce the same-origin policy for WebSockets, so cross-site hijacking is possible without it), authentication before upgrade, and a maxPayload limit.
Validate every message
Treat each incoming frame like an HTTP request body:
// src/realtime/messages.tsimport { z } from "zod";export const clientMessage = z.discriminatedUnion("type", [ z.object({ type: z.literal("join"), room: z.string().min(1).max(64) }), z.object({ type: z.literal("leave"), room: z.string().min(1).max(64) }), z.object({ type: z.literal("chat"), room: z.string().min(1).max(64), text: z.string().min(1).max(2000) }),]);export type ClientMessage = z.infer<typeof clientMessage>;wss.on("connection", (ws: Client) => { ws.isAlive = true; ws.on("pong", () => { ws.isAlive = true; }); ws.on("message", async (data) => { let parsed; try { parsed = clientMessage.parse(JSON.parse(data.toString())); } catch { return ws.send(JSON.stringify({ type: "error", message: "Invalid message" })); } await handleMessage(ws, parsed); }); ws.on("close", () => cleanup(ws)); ws.on("error", () => ws.terminate());});Authorization still applies after the connection is open. Before accepting a join, check that the user is allowed in that room.
Heartbeats detect dead connections
Networks fail silently: a laptop closes, a phone loses signal, and the server never receives a close frame. Ping periodically and terminate connections that do not answer:
const interval = setInterval(() => { for (const ws of wss.clients as Set<Client>) { if (ws.isAlive === false) { ws.terminate(); continue; } ws.isAlive = false; ws.ping(); }}, 30_000);wss.on("close", () => clearInterval(interval));Heartbeats also keep traffic flowing so that proxies and load balancers do not close the connection for being idle.
Rooms and broadcasting
const rooms = new Map<string, Set<Client>>();function join(ws: Client, room: string) { ws.rooms.add(room); if (!rooms.has(room)) rooms.set(room, new Set()); rooms.get(room)!.add(ws);}function broadcast(room: string, payload: unknown, except?: Client) { const message = JSON.stringify(payload); for (const client of rooms.get(room) ?? []) { if (client !== except && client.readyState === client.OPEN) { // Backpressure: skip or drop slow consumers instead of buffering without limit. if (client.bufferedAmount > 1_000_000) { client.terminate(); continue; } client.send(message); } }}function cleanup(ws: Client) { for (const room of ws.rooms) rooms.get(room)?.delete(ws);}Always clean up on close. Leaked references in room maps are a common memory leak. Check bufferedAmount so one slow client cannot make your server buffer unbounded data.
A resilient browser client
Reconnection is the client's job. Use exponential backoff with jitter so that, after a server restart, thousands of clients do not reconnect at the same instant:
// client/realtime.tsexport function connect(url: string, onMessage: (data: unknown) => void) { let attempt = 0; let socket: WebSocket | undefined; let closedByUser = false; const open = () => { socket = new WebSocket(url); socket.onopen = () => { attempt = 0; }; socket.onmessage = (e) => onMessage(JSON.parse(e.data)); socket.onclose = () => { if (closedByUser) return; const base = Math.min(30_000, 500 * 2 ** attempt++); const delay = base / 2 + Math.random() * (base / 2); // jitter setTimeout(open, delay); }; }; open(); return { send: (msg: unknown) => socket?.readyState === WebSocket.OPEN && socket.send(JSON.stringify(msg)), close: () => { closedByUser = true; socket?.close(); }, };}After reconnecting, the client must rejoin its rooms and fetch missed messages (for example by asking for everything after the last message id it saw). The connection is not a reliable store of events; your database is.
Scale across multiple servers
A connection lives on one server. If user A is connected to server 1 and user B to server 2, a message from A must reach B. Connect the servers with a pub/sub channel, such as Redis:
// src/realtime/bus.tsimport Redis from "ioredis";const pub = new Redis(process.env.REDIS_URL!);const sub = new Redis(process.env.REDIS_URL!); // a subscriber connection cannot run other commandsexport async function startBus(onEvent: (room: string, payload: unknown) => void) { await sub.psubscribe("room:*"); sub.on("pmessage", (_pattern, channel, raw) => { onEvent(channel.slice("room:".length), JSON.parse(raw)); });}export function publishToRoom(room: string, payload: unknown) { return pub.publish(`room:${room}`, JSON.stringify(payload));}The flow becomes: a client sends a message, the server saves it, publishes it to Redis, and every server (including the sender's) delivers it to its local room members through broadcast. This also works for messages triggered by your HTTP API or background jobs.
Put Nginx or a load balancer in front
Proxies must pass the Upgrade headers and must not close idle connections too early:
location /ws { proxy_pass http://app_backend; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host $host; proxy_read_timeout 3600s;}On AWS, Application Load Balancers support WebSockets; raise the idle timeout to exceed your heartbeat interval.
Security considerations
- Always use
wss://(TLS) in production. - Check the Origin header and authenticate during the upgrade.
- Use short-lived tickets rather than long-lived tokens in the URL.
- Validate message shape and size; limit messages per second per connection.
- Re-check authorization for each room or resource, not only at connect time.
- Escape or sanitize user content before rendering it in other users' browsers.
Performance considerations
- Keep messages small and use binary formats for high-volume data.
- Throttle high-frequency events (cursor positions) on the client.
- Watch memory per connection; thousands of idle connections are cheap, but per-connection state adds up.
- Raise operating system file descriptor limits for large connection counts.
Testing
Test the server with a real WebSocket client in an integration test:
import WebSocket from "ws";it("rejects connections with a bad origin", async () => { const ws = new WebSocket(`ws://localhost:${port}/ws`, { headers: { origin: "https://evil.example" } }); const result = await new Promise((resolve) => { ws.on("unexpected-response", (_req, res) => resolve(res.statusCode)); ws.on("error", () => resolve("error")); }); expect(result).toBe(401);});it("delivers a chat message to other members of the room", async () => { const [a, b] = await Promise.all([connectAs("alice"), connectAs("bob")]); a.send(JSON.stringify({ type: "join", room: "general" })); b.send(JSON.stringify({ type: "join", room: "general" })); const received = nextMessage(b); a.send(JSON.stringify({ type: "chat", room: "general", text: "hello" })); expect(await received).toMatchObject({ type: "chat", text: "hello" });});Also test reconnection (kill the server and restart it), heartbeats (a client that never answers pings is dropped) and what happens when two server instances share a Redis bus.
Common mistakes
- No authentication at upgrade time, or tokens in the URL.
- Missing origin checks.
- No heartbeats, so dead connections pile up.
- Reconnect loops without backoff or jitter.
- Keeping state only in server memory, so it is lost on restart or deploy.
- No shared bus, so rooms break when you add a second server.
- Unbounded buffers for slow clients.
Best practices
- Authenticate and authorize at the edge, and again per action.
- Validate every message with a schema.
- Heartbeat, back off with jitter and resync after reconnecting.
- Treat the database as the source of truth and the socket as a delivery channel.
- Use a pub/sub bus to scale horizontally.
Conclusion
A WebSocket connection is easy to open and hard to keep healthy. The difference between a demo and a production feature is the surrounding discipline: authenticate before upgrading, validate every frame, detect dead connections, reconnect gracefully, persist what matters and connect servers with a shared bus. Add these one at a time, and real-time features stop being fragile.
Frequently asked questions
+WebSockets, Server-Sent Events or polling: which should I use?
Use WebSockets for two-way, low-latency communication such as chat or collaborative editing. Use Server-Sent Events for one-way server-to-client updates, which are simpler and work well over HTTP. Use polling when updates are infrequent and simplicity matters more than latency.
+How do I authenticate a WebSocket connection?
Authenticate during the HTTP upgrade request, using a session cookie or a short-lived token, and reject the upgrade if it is invalid. Avoid putting long-lived tokens in the URL because URLs end up in logs.
+Why do my connections drop after about a minute?
Proxies and load balancers close idle connections. Send periodic ping/pong heartbeats from the server and raise the idle timeouts on Nginx or the load balancer so healthy connections stay open.
+How do I scale WebSockets across multiple servers?
Each connection lives on one server, so servers need a shared message bus. Publish messages through Redis pub/sub (or a similar broker) and have every server forward relevant messages to its own connected clients.
+Do I need sticky sessions?
Not for plain WebSockets, since the connection stays on one server for its lifetime. Sticky sessions are mainly needed for libraries that fall back to HTTP long-polling, such as Socket.IO's polling transport.
+Should I use the ws library or Socket.IO?
ws is a small, standards-based WebSocket implementation. Socket.IO adds rooms, acknowledgements, automatic reconnection and fallbacks, but uses its own protocol, so both client and server must use it. Choose based on how many of those features you need.
+How do I prevent a client from flooding the server?
Limit message size and rate per connection, validate every message against a schema, close connections that misbehave, and watch backpressure on slow clients.