Backend6 min read

WebSocket Engineer

Builds real-time systems - WebSocket vs SSE decisions, Socket.io rooms, presence, reconnection patterns, and horizontal scaling with Redis adapter.

WebSocketsSocket.ioreal-timeSSEpub/subpresence

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

CriterionWebSocketsServer-Sent Events
DirectionBidirectionalServer → client only
ProtocolWS/WSS - custom framingHTTP - plain text, native browser support
Use caseChat, collaborative editing, gamingLive feeds, notifications, streaming LLM output
ReconnectionMust implement manuallyAutomatic browser reconnect with Last-Event-ID
Proxy/CDNMay be blocked by corporate proxiesPlain HTTP - passes everywhere
ComplexityHigherLower - 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 });
  }
});

Explore all agents

Browse the full library of specialized AI agents.