PluginBench
Skill
Pass
Audit score 90

websocket-engineer

jeffallan/claude-skills

Build real-time bidirectional communication systems with WebSockets and Socket.IO, including clustering and presence tracking.

What is websocket-engineer?

WebSocket Engineer helps you design and implement scalable real-time communication systems. Use it when building chat, live updates, presence tracking, or any bidirectional messaging system that needs horizontal scaling with Redis, room management, and production-grade reliability.

  • Design WebSocket architecture for connection scale, message volume, and latency requirements
  • Implement Socket.IO servers with JWT authentication, room management, and event handling
  • Set up Redis pub/sub adapters for horizontal scaling across multiple instances
  • Configure sticky sessions and load balancing for stateful WebSocket connections
  • Build client-side reconnection logic with exponential backoff and message queuing
  • Monitor connections, latency, throughput, and error rates with alerting

How to install websocket-engineer

npx skills add https://github.com/jeffallan/claude-skills --skill websocket-engineer
Prerequisites
  • Node.js runtime environment
  • Redis instance for clustering (optional for single-instance, required for horizontal scaling)
  • Understanding of JWT or token-based authentication
  • Familiarity with event-driven architecture
Claude Code
Cursor
Windsurf
Cline

How to use websocket-engineer

  1. 1.Analyze your requirements: identify expected connection count, message volume, and latency needs
  2. 2.Design your architecture: plan clustering strategy, pub/sub topology, and state management approach
  3. 3.Implement server setup: configure Socket.IO with authentication middleware, rooms, and event handlers
  4. 4.Test locally: validate connection handling, auth rejection, room join/leave, and message delivery using wscat or similar tools
  5. 5.Configure scaling: set up Redis adapter, enable sticky sessions, and test pub/sub round-trip across instances
  6. 6.Deploy and monitor: track connection counts, latency, throughput, and error rates with alerts for spikes

Use cases

Good for
  • Building multi-user chat applications with room-based messaging and presence indicators
  • Implementing live notification systems that push updates to connected clients without polling
  • Creating collaborative tools (whiteboards, document editors) with real-time synchronization across users
  • Scaling WebSocket servers horizontally using Redis adapters while maintaining connection state
  • Handling graceful reconnection and message buffering when clients temporarily disconnect
Who it's for
  • Backend engineers building real-time APIs
  • Full-stack developers implementing live features
  • DevOps engineers scaling WebSocket infrastructure
  • Architects designing bidirectional communication systems

websocket-engineer FAQ

When should I use WebSockets instead of HTTP polling or Server-Sent Events?

Use WebSockets for true bidirectional communication where the client needs to send data to the server in real-time. Use SSE for server-to-client push only. Use polling for simple, low-frequency updates. WebSockets have higher overhead but lower latency and are ideal for chat, collaborative tools, and live gaming.

How do I scale WebSocket connections across multiple servers?

Use a Redis adapter (e.g., @socket.io/redis-adapter) to enable pub/sub between instances. Configure sticky sessions in your load balancer so each client always routes to the same server instance. Verify Redis connectivity and pub/sub round-trip before enabling in production.

What happens if a client disconnects temporarily?

Implement client-side message queuing: buffer outgoing messages while disconnected and flush them on reconnect. Use exponential backoff with jitter for reconnection attempts to avoid thundering herd. Set appropriate pingTimeout and pingInterval to detect dead connections quickly.

How do I authenticate WebSocket connections?

Use JWT tokens passed in the handshake auth object. Verify the token in Socket.IO's authentication middleware before the connection is established. Reject connections with invalid or missing tokens. Optionally refresh tokens during long-lived connections.

What are the key constraints I must follow?

Use sticky sessions for stateful routing. Implement heartbeat/ping-pong to detect dead connections. Use rooms/namespaces for message scoping. Queue messages during disconnection. Plan connection limits per instance before scaling. Always load test before production.

Full instructions (SKILL.md)

Source of truth, from jeffallan/claude-skills.


name: websocket-engineer description: Use when building real-time communication systems with WebSockets or Socket.IO. Invoke for bidirectional messaging, horizontal scaling with Redis, presence tracking, room management. license: MIT metadata: author: https://github.com/Jeffallan version: "1.1.0" domain: api-architecture triggers: WebSocket, Socket.IO, real-time communication, bidirectional messaging, pub/sub, server push, live updates, chat systems, presence tracking role: specialist scope: implementation output-format: code related-skills: fastapi-expert, nestjs-expert, devops-engineer, monitoring-expert, security-reviewer

WebSocket Engineer

Core Workflow

  1. Analyze requirements — Identify connection scale, message volume, latency needs
  2. Design architecture — Plan clustering, pub/sub, state management, failover
  3. Implement — Build WebSocket server with authentication, rooms, events
  4. Validate locally — Test connection handling, auth, and room behavior before scaling (e.g., npx wscat -c ws://localhost:3000); confirm auth rejection on missing/invalid tokens, room join/leave events, and message delivery
  5. Scale — Verify Redis connection and pub/sub round-trip before enabling the adapter; configure sticky sessions and confirm with test connections across multiple instances; set up load balancing
  6. Monitor — Track connections, latency, throughput, error rates; add alerts for connection-count spikes and error-rate thresholds

Reference Guide

Load detailed guidance based on context:

TopicReferenceLoad When
Protocolreferences/protocol.mdWebSocket handshake, frames, ping/pong, close codes
Scalingreferences/scaling.mdHorizontal scaling, Redis pub/sub, sticky sessions
Patternsreferences/patterns.mdRooms, namespaces, broadcasting, acknowledgments
Securityreferences/security.mdAuthentication, authorization, rate limiting, CORS
Alternativesreferences/alternatives.mdSSE, long polling, when to choose WebSockets

Code Examples

Server Setup (Socket.IO with Auth and Room Management)

import { createServer } from "http";
import { Server } from "socket.io";
import { createAdapter } from "@socket.io/redis-adapter";
import { createClient } from "redis";
import jwt from "jsonwebtoken";

const httpServer = createServer();
const io = new Server(httpServer, {
  cors: { origin: process.env.ALLOWED_ORIGIN, credentials: true },
  pingTimeout: 20000,
  pingInterval: 25000,
});

// Authentication middleware — runs before connection is established
io.use((socket, next) => {
  const token = socket.handshake.auth.token;
  if (!token) return next(new Error("Authentication required"));
  try {
    socket.data.user = jwt.verify(token, process.env.JWT_SECRET);
    next();
  } catch {
    next(new Error("Invalid token"));
  }
});

// Redis adapter for horizontal scaling
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) => {
  const { userId } = socket.data.user;
  console.log(`connected: ${userId} (${socket.id})`);

  // Presence: mark user online
  pubClient.hSet("presence", userId, socket.id);

  socket.on("join-room", (roomId) => {
    socket.join(roomId);
    socket.to(roomId).emit("user-joined", { userId });
  });

  socket.on("message", ({ roomId, text }) => {
    io.to(roomId).emit("message", { userId, text, ts: Date.now() });
  });

  socket.on("disconnect", () => {
    pubClient.hDel("presence", userId);
    console.log(`disconnected: ${userId}`);
  });
});

httpServer.listen(3000);

Client-Side Reconnection with Exponential Backoff

import { io } from "socket.io-client";

const socket = io("wss://api.example.com", {
  auth: { token: getAuthToken() },
  reconnection: true,
  reconnectionAttempts: 10,
  reconnectionDelay: 1000,       // initial delay (ms)
  reconnectionDelayMax: 30000,   // cap at 30 s
  randomizationFactor: 0.5,      // jitter to avoid thundering herd
});

// Queue messages while disconnected
let messageQueue = [];

socket.on("connect", () => {
  console.log("connected:", socket.id);
  // Flush queued messages
  messageQueue.forEach((msg) => socket.emit("message", msg));
  messageQueue = [];
});

socket.on("disconnect", (reason) => {
  console.warn("disconnected:", reason);
  if (reason === "io server disconnect") socket.connect(); // manual reconnect
});

socket.on("connect_error", (err) => {
  console.error("connection error:", err.message);
});

function sendMessage(roomId, text) {
  const msg = { roomId, text };
  if (socket.connected) {
    socket.emit("message", msg);
  } else {
    messageQueue.push(msg); // buffer until reconnected
  }
}

Constraints

MUST DO

  • Use sticky sessions for load balancing (WebSocket connections are stateful — requests must route to the same server instance)
  • Implement heartbeat/ping-pong to detect dead connections (TCP keepalive alone is insufficient)
  • Use rooms/namespaces for message scoping rather than filtering in application logic
  • Queue messages during disconnection windows to avoid silent data loss
  • Plan connection limits per instance before scaling horizontally

MUST NOT DO

  • Store large state in memory without a clustering strategy (use Redis or an external store)
  • Mix WebSocket and HTTP on the same port without explicit upgrade handling
  • Forget to handle connection cleanup (presence records, room membership, in-flight timers)
  • Skip load testing before production — connection-count spikes behave differently from HTTP traffic spikes

Output Templates

When implementing WebSocket features, provide:

  1. Server setup (Socket.IO/ws configuration)
  2. Event handlers (connection, message, disconnect)
  3. Client library (connection, events, reconnection)
  4. Brief explanation of scaling strategy

Knowledge Reference

Socket.IO, ws, uWebSockets.js, Redis adapter, sticky sessions, nginx WebSocket proxy, JWT over WebSocket, rooms/namespaces, acknowledgments, binary data, compression, heartbeat, backpressure, horizontal pod autoscaling

Documentation