The WebSocket Engineer builds real-time communication systems - collaborative editing, live dashboards, chat, presence indicators, and notifications. The first decision is always protocol choice: WebSockets for bidirectional communication, SSE for server-to-client-only push. Getting this wrong means unnecessary complexity or missing capabilities.
WebSockets vs SSE Decision
| Criterion | WebSockets | Server-Sent Events |
|---|---|---|
| Direction | Bidirectional | Server → client only |
| Protocol | WS/WSS - custom framing | HTTP - plain text, native browser support |
| Use case | Chat, collaborative editing, gaming | Live feeds, notifications, streaming LLM output |
| Reconnection | Must implement manually | Automatic browser reconnect with Last-Event-ID |
| Proxy/CDN | May be blocked by corporate proxies | Plain HTTP - passes everywhere |
| Complexity | Higher | Lower - just a long HTTP response |
Socket.io Setup with Rooms
import { Server } from 'socket.io';
import { createAdapter } from '@socket.io/redis-adapter';
import { createClient } from 'redis';
const io = new Server(httpServer, {
cors: { origin: process.env.FRONTEND_URL, methods: ['GET', 'POST'] },
transports: ['websocket', 'polling'], // Polling fallback for corporate proxies
});
// Redis adapter for horizontal scaling - events fan out across all server instances
const pubClient = createClient({ url: process.env.REDIS_URL });
const subClient = pubClient.duplicate();
await Promise.all([pubClient.connect(), subClient.connect()]);
io.adapter(createAdapter(pubClient, subClient));
io.on('connection', (socket) => {
// Authenticate first - reject unauthenticated connections immediately
const userId = verifyToken(socket.handshake.auth.token);
if (!userId) { socket.disconnect(); return; }
// Join a room for the user (for targeted notifications)
socket.join(`user:${userId}`);
socket.on('join-document', async (docId: string) => {
// Authorise before joining
if (!await canAccessDocument(userId, docId)) return;
socket.join(`doc:${docId}`);
// Notify others in the document
socket.to(`doc:${docId}`).emit('user-joined', { userId });
});
socket.on('send-operation', (docId: string, op: DocumentOperation) => {
// Broadcast to all in room except sender
socket.to(`doc:${docId}`).emit('operation', op);
});
socket.on('disconnect', () => {
// Presence cleanup handled by Redis TTL on user key
});
});
Client Reconnection Pattern
// Socket.io client - reconnection built in, but configure properly
import { io } from 'socket.io-client';
const socket = io(process.env.NEXT_PUBLIC_WS_URL!, {
auth: { token: getAuthToken() },
reconnectionDelayMax: 10_000, // Max 10s between retries
reconnectionAttempts: Infinity, // Keep trying
timeout: 20_000,
});
socket.on('connect_error', (err) => {
if (err.message === 'unauthorized') {
// Token expired - refresh and reconnect
refreshToken().then(token => socket.auth = { token });
}
});