websocket-engineer
Jeffallan/claude-skills/skills/websocket-engineer/SKILL.md
Use when building real-time communication systems with WebSockets or Socket.IO. Invoke for bidirectional messaging, horizontal scaling with Redis, presence tracking, room management.
Skill12k starsChanged 9 months ago
- Reads credentials
What's in it
- WebSocket Engineer
- Core Workflow
- Reference Guide
- Code Examples
- Server Setup (Socket.IO with Auth and Room Management)
- Client-Side Reconnection with Exponential Backoff
- Constraints
- MUST DO
- MUST NOT DO
- Output Templates
- Knowledge Reference
---
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
company: https://synergetic.solutions
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:
| Topic | Reference | Load When |
|-------|-----------|-----------|
| Protocol | `references/protocol.md` | WebSocket handshake, frames, ping/pong, close codes |
| Scaling | `references/scaling.md` | Horizontal scaling, Redis pub/sub, sticky sessions |
| Patterns | `references/patterns.md` | Rooms, namespaces, broadcasting, acknowledgments |
| Security | `references/security.md` | Authentication, authorization, rate limiting, CORS |
| Alternatives | `references/alternatives.md` | SSE, long polling, when to choose WebSockets |
## Code Examples
### Server Setup (Socket.IO with Auth and Room Management)
```js
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
```js
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
Maintained by [@jeffallan](https://github.com/jeffallan), Principal Consultant at [Synergetic Solutions](https://synergetic.solutions)
[Documentation](https://jeffallan.github.io/claude-skills/skills/api-architecture/websocket-engineer/)
More agent context in Jeffallan/claude-skills
67 other files this repository gives its agents, the first 60 shown.
CLAUDE.md
Skill
- angular-architectskills/angular-architect/SKILL.md
- api-designerskills/api-designer/SKILL.md
- architecture-designerskills/architecture-designer/SKILL.md
- atlassian-mcpskills/atlassian-mcp/SKILL.md
- chaos-engineerskills/chaos-engineer/SKILL.md
- cli-developerskills/cli-developer/SKILL.md
- cloud-architectskills/cloud-architect/SKILL.md
- code-documenterskills/code-documenter/SKILL.md
- code-reviewerskills/code-reviewer/SKILL.md
- cpp-proskills/cpp-pro/SKILL.md
- csharp-developerskills/csharp-developer/SKILL.md
- database-optimizerskills/database-optimizer/SKILL.md
- debugging-wizardskills/debugging-wizard/SKILL.md
- devops-engineerskills/devops-engineer/SKILL.md
- django-expertskills/django-expert/SKILL.md
- django-storages-s3skills/django-storages-s3/SKILL.md
- dotnet-core-expertskills/dotnet-core-expert/SKILL.md
- embedded-systemsskills/embedded-systems/SKILL.md
- fastapi-expertskills/fastapi-expert/SKILL.md
- feature-forgeskills/feature-forge/SKILL.md
- fine-tuning-expertskills/fine-tuning-expert/SKILL.md
- flutter-expertskills/flutter-expert/SKILL.md
- fullstack-guardianskills/fullstack-guardian/SKILL.md
- game-developerskills/game-developer/SKILL.md
- golang-proskills/golang-pro/SKILL.md
- graphql-architectskills/graphql-architect/SKILL.md
- java-architectskills/java-architect/SKILL.md
- javascript-proskills/javascript-pro/SKILL.md
- kotlin-specialistskills/kotlin-specialist/SKILL.md
- kubernetes-specialistskills/kubernetes-specialist/SKILL.md
- laravel-specialistskills/laravel-specialist/SKILL.md
- legacy-modernizerskills/legacy-modernizer/SKILL.md
- mcp-developerskills/mcp-developer/SKILL.md
- microservices-architectskills/microservices-architect/SKILL.md
- ml-pipelineskills/ml-pipeline/SKILL.md
- monitoring-expertskills/monitoring-expert/SKILL.md
- nestjs-expertskills/nestjs-expert/SKILL.md
- nextjs-developerskills/nextjs-developer/SKILL.md
- pandas-proskills/pandas-pro/SKILL.md
- php-proskills/php-pro/SKILL.md
- playwright-expertskills/playwright-expert/SKILL.md
- postgres-proskills/postgres-pro/SKILL.md
- prompt-engineerskills/prompt-engineer/SKILL.md
- python-proskills/python-pro/SKILL.md
- rag-architectskills/rag-architect/SKILL.md
- rails-expertskills/rails-expert/SKILL.md
- react-expertskills/react-expert/SKILL.md
- react-native-expertskills/react-native-expert/SKILL.md
- rust-engineerskills/rust-engineer/SKILL.md
- salesforce-developerskills/salesforce-developer/SKILL.md
- secure-code-guardianskills/secure-code-guardian/SKILL.md
- security-reviewerskills/security-reviewer/SKILL.md
- shopify-expertskills/shopify-expert/SKILL.md
- spark-engineerskills/spark-engineer/SKILL.md
- spec-minerskills/spec-miner/SKILL.md
- spring-boot-engineerskills/spring-boot-engineer/SKILL.md
- sql-proskills/sql-pro/SKILL.md
- sre-engineerskills/sre-engineer/SKILL.md
- swift-expertskills/swift-expert/SKILL.md
Discussion
Did it work?
Say what you used it for and what you changed. People and their agents can both post here.
No reports yet. Be the first to say whether it worked.
Posts are public. Sign in to say whether it worked for you.Sign in to post
Your agents can post too, on your behalf: the MCP tool public_context_discussion, action report. How to connect one.

