Index of every page on this site: llms.txt
All skills
jeffallan avatar

/websocket-engineer

@67c1961
by jeffallanjeffallan/claude-skills12k stars
1,202
Run it yourself

Use when building real-time communication systems with WebSockets or Socket.IO. Invoke for bidirectional messaging, horizontal scaling with Redis, presence tracking, room management.

Use this Skill: https://skilld.dev/gh/jeffallan/claude-skills/websocket-engineer

Nothing lands on disk. Nothing to clean up.

Fork this Skill

Edit a local copy. It keeps the author and licence.

SKILL.md

≈51 tokens for metadata: the name and description. ≈1.5k when used: this file. ≈10k more on demand in 5 files.

Description uses 2.5% of example budget

Before choosing a Skill, your Agent reads its name and description. All available Skills share that space.

  • A shorter description leaves more room for other Skills. This entry exceeds our 1% size suggestion.

In our Claude Code example, all Skill names and descriptions share 8,000 characters. This Skill uses ≈203 characters, or 2.5%.

The 1% threshold is a size suggestion. Longer descriptions can still fit.

Your model, settings, and other Skills decide how much text your Agent can read.

Example settings and source

The example uses a 200k-token context and default Claude Code settings. The count includes the name, description, separators, and when_to_use when present. Codex also counts local file paths.

Skit's source and limits: Codex 0.160.1, Claude Code 2.1.292.

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)

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

Maintained by @jeffallan, Principal Consultant at Synergetic Solutions

Documentation

Source: SKILL.md on GitHub

skilld matched fixed text patterns in SKILL.md and file names. Patterns miss obfuscated code.

skilld run checks every file with the same patterns. It asks for approval before it loads a Skill with a behavior marked Needs approval.

1 alert25d5 checks · Risk CRITICAL
  • Gen Agent Trust Hub25d

    The skill is a professional implementation guide for WebSocket and real-time communication systems. It includes comprehensive security best practices, such as JWT authentication, distributed rate limiting, and HTML sanitization. Automated scanner alerts regarding documentation links on GitHub Pages are considered false positives as they point to the author's project documentation on a well-known hosting service.

  • Socket25d

    No alerts

  • Snyk25d

    Risk: LOW · No issues

  • Runlayer8mo

    3/6 files flagged

  • ZeroLeaks7mo

    1 finding · Score: 82/100

Signed by skilld at 67c1961. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub 4 days ago.

Activeupdated 4 weeks ago
Other metadata
metadata
{
  "author": "https://github.com/Jeffallan",
  "company": "https://synergetic.solutions",
  "version": "1.1.1",
  "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
  • socket.io
  • real-time
  • redis
  • scaling
  • authentication
  • rooms
  • pub-sub
  • nodejs

README badge

README badge for jeffallan/claude-skills/websocket-engineer

Builds real-time bidirectional messaging systems using WebSocket or Socket.IO, covering authentication, room management, Redis pub/sub scaling, and production monitoring. Provides server setup, client reconnection patterns, and strategies for horizontal scaling with sticky sessions and load balancing.

Generated from the current SKILL.md.

Does this skill work with both Socket.IO and the ws library?
The skill covers Socket.IO primarily, with reference material on the ws library and alternatives. Code examples use Socket.IO; ws patterns differ in event handling and scaling.
How does this skill handle horizontal scaling?
It uses Redis pub/sub adapter and sticky sessions to route WebSocket connections to the same server instance, enabling message delivery across multiple servers.
Does this include authentication and authorization?
Yes. The skill covers JWT authentication middleware that runs before connection, plus reference material on authorization and rate limiting strategies.
What monitoring and observability does this cover?
The skill outlines tracking connections, latency, throughput, and error rates with alerts for connection spikes and error thresholds, but relies on the monitoring-expert skill for detailed instrumentation.
Does this handle client-side reconnection?
Yes. The skill includes exponential backoff with jitter, message queuing during disconnection, and manual reconnect logic for server-initiated disconnects.

Generated from the current SKILL.md. These answers refresh after source changes.