BU

building-websocket-server

Instructions to implement scalable WebSocket servers using standard libraries and Redis for horizontal scaling.

Install

mkdir -p .claude/skills/building-websocket-server && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/1700" && unzip -o skill.zip -d .claude/skills/building-websocket-server && rm skill.zip

Installs to .claude/skills/building-websocket-server

Activation

This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.

Build scalable WebSocket servers for real-time bidirectional communication.
75 charsno explicit “when” trigger
Advanced

Key capabilities

  • Set up WebSocket servers for real-time communication
  • Implement connection authentication during handshake
  • Manage connection lifecycle and room subscriptions
  • Broadcast messages to clients or specific channels
  • Scale WebSocket connections horizontally with Redis pub/sub

How it works

The skill guides the setup of a WebSocket server by integrating with an existing HTTP server, implementing authentication during the handshake, and managing client connections and room subscriptions. It defines a message protocol and configures Redis pub/sub for horizontal scaling.

Inputs & outputs

You give it
Existing HTTP server configuration and real-time communication requirements
You get back
Scalable WebSocket server with connection management, authentication, and message broadcasting

When to use building-websocket-server

  • Adding real-time messaging features
  • Implementing bidirectional API endpoints
  • Setting up WebSocket heartbeat keepalive
  • Scaling connections with Redis pub/sub
  • Authenticating WebSocket handshake requests

About this skill

Building WebSocket Server

Overview

Build scalable WebSocket servers for real-time bidirectional communication using the ws library, Socket.IO, or native framework WebSocket support. Handle connection lifecycle management, room/channel subscriptions, message broadcasting, heartbeat keepalive, and horizontal scaling with Redis pub/sub adapters.

Prerequisites

  • Node.js 18+ with ws or socket.io, or Python 3.10+ with websockets or FastAPI WebSocket, or Go with gorilla/websocket
  • Redis for horizontal scaling with pub/sub adapter (Socket.IO Redis adapter, or manual pub/sub)
  • Load balancer configured for WebSocket upgrade (sticky sessions or proper Upgrade header forwarding)
  • JWT or session-based authentication for connection handshake
  • Monitoring for active connection counts and message throughput

Instructions

  1. Examine existing HTTP server configuration using Read and Grep to determine the framework and identify where WebSocket upgrade handling integrates.
  2. Create a WebSocket server instance attached to the existing HTTP server, configuring the upgrade path (e.g., /ws, /socket.io) and allowed origins.
  3. Implement connection authentication by validating JWT tokens or session cookies during the WebSocket handshake upgrade event, rejecting unauthorized connections before protocol switch.
  4. Build a connection registry that tracks active clients with metadata (user ID, subscribed channels, connection time) for targeted message delivery.
  5. Define a message protocol using JSON envelopes with type, channel, payload, and correlationId fields for structured bidirectional communication.
  6. Implement room/channel subscription logic allowing clients to join and leave named channels with server-side membership tracking.
  7. Add heartbeat ping/pong mechanism with configurable interval (default 30s) and timeout detection to clean up stale connections.
  8. Configure Redis pub/sub adapter for horizontal scaling so messages broadcast from any server instance reach all connected clients across the cluster.
  9. Write connection lifecycle tests covering connect, authenticate, subscribe, message exchange, reconnect, and graceful disconnect scenarios.

See ${CLAUDE_SKILL_DIR}/references/implementation.md for the full implementation guide.

Output

  • ${CLAUDE_SKILL_DIR}/src/ws/server.js - WebSocket server setup and upgrade handling
  • ${CLAUDE_SKILL_DIR}/src/ws/handlers/ - Per-message-type handler functions
  • ${CLAUDE_SKILL_DIR}/src/ws/rooms.js - Room/channel subscription management
  • ${CLAUDE_SKILL_DIR}/src/ws/registry.js - Active connection tracking registry
  • ${CLAUDE_SKILL_DIR}/src/ws/heartbeat.js - Ping/pong keepalive logic
  • ${CLAUDE_SKILL_DIR}/src/ws/adapters/redis.js - Redis pub/sub adapter for scaling
  • ${CLAUDE_SKILL_DIR}/tests/ws/ - WebSocket connection and messaging tests

Error Handling

ErrorCauseSolution
401 during upgradeJWT token missing or expired in handshake query/headersReject upgrade with HTTP 401 before WebSocket protocol switch completes
1008 Policy ViolationClient sends malformed message or violates protocolSend close frame with code 1008 and human-readable reason; log violation
1006 Abnormal ClosureNetwork interruption without close handshakeDetect via heartbeat timeout; clean up connection registry; notify room members
Memory leakConnection registry grows unbounded from stale entriesImplement heartbeat-based cleanup sweep every 60s; enforce max connections per server
Message stormSingle client flooding messages beyond acceptable rateApply per-connection message rate limiting; disconnect abusive clients with 1008

Refer to ${CLAUDE_SKILL_DIR}/references/errors.md for comprehensive error patterns.

Examples

Chat application: Multi-room chat server where clients join named rooms, receive member presence updates, and see real-time message delivery with typing indicators via separate message types.

Live dashboard: Server pushes metric updates to subscribed dashboard clients every second, with initial state snapshot on connection and incremental deltas thereafter.

Collaborative editing: Operational transformation relay server that receives edit operations from clients, transforms against concurrent operations, and broadcasts resolved changes to all document subscribers.

See ${CLAUDE_SKILL_DIR}/references/examples.md for additional examples.

Resources

Prerequisites

Node.js 18+ with `ws` or `socket.io`, or Python 3.10+ with `websockets` or FastAPI WebSocket, or Go with `gorilla/websocket`Redis for horizontal scaling with pub/sub adapterLoad balancer configured for WebSocket upgradeJWT or session-based authentication for connection handshake

Limitations

  • 401 during upgrade if JWT token is missing or expired
  • 1008 Policy Violation if client sends malformed messages
  • Memory leak if connection registry grows unbounded from stale entries

How it compares

This skill provides a structured approach to building scalable WebSocket servers with explicit instructions for authentication, connection management, and horizontal scaling, which goes beyond basic WebSocket server setup.

Compared to similar skills

building-websocket-server side by side with the closest alternatives in the catalog.

SkillInstallsUpdatedSafetyDifficulty
building-websocket-server (this skill)327dReviewAdvanced
telegram-bot-builder1066moReviewIntermediate
stripe-integration482moNo flagsAdvanced
hubspot-integration56moNo flagsAdvanced

Try saying

Example prompts that trigger this skill in your AI assistant.

More by jeremylongshore

View all by jeremylongshore

analyzing-logs

jeremylongshore

Analyze application logs to detect performance issues, identify error patterns, and improve stability by extracting key insights.

14123

ollama-setup

jeremylongshore

Configure auto-configure Ollama when user needs local LLM deployment, free AI alternatives, or wants to eliminate hosted API costs. Trigger phrases: "install ollama", "local AI", "free LLM", "self-hosted AI", "replace OpenAI", "no API costs". Use when appropriate context detected. Trigger with relevant phrases based on skill purpose.

1167

backtesting-trading-strategies

jeremylongshore

Backtest crypto and traditional trading strategies against historical data. Calculates performance metrics (Sharpe, Sortino, max drawdown), generates equity curves, and optimizes strategy parameters. Use when user wants to test a trading strategy, validate signals, or compare approaches. Trigger with phrases like "backtest strategy", "test trading strategy", "historical performance", "simulate trades", "optimize parameters", or "validate signals".

1071

generating-database-seed-data

jeremylongshore

Process this skill enables AI assistant to generate realistic test data and database seed scripts for development and testing environments. it uses faker libraries to create realistic data, maintains relational integrity, and allows configurable data volumes. u... Use when working with databases or data models. Trigger with phrases like 'database', 'query', or 'schema'.

1033

cursor-codebase-indexing

jeremylongshore

Execute set up and optimize Cursor codebase indexing. Triggers on "cursor index setup", "codebase indexing", "index codebase", "cursor semantic search". Use when working with cursor codebase indexing functionality. Trigger with phrases like "cursor codebase indexing", "cursor indexing", "cursor".

885

testing-mobile-apps

jeremylongshore

Execute mobile app testing on iOS and Android devices/simulators. Use when performing specialized testing. Trigger with phrases like "test mobile app", "run iOS tests", or "validate Android functionality".

810

You might also like

telegram-bot-builder

davila7

Expert in building Telegram bots that solve real problems - from simple automation to complex AI-powered bots. Covers bot architecture, the Telegram Bot API, user experience, monetization strategies, and scaling bots to thousands of users. Use when: telegram bot, bot api, telegram automation, chat bot telegram, tg bot.

106130

stripe-integration

wshobson

Implement Stripe payment processing for robust, PCI-compliant payment flows including checkout, subscriptions, and webhooks. Use when integrating Stripe payments, building subscription systems, or implementing secure checkout flows.

48165

hubspot-integration

davila7

Expert patterns for HubSpot CRM integration including OAuth authentication, CRM objects, associations, batch operations, webhooks, and custom objects. Covers Node.js and Python SDKs. Use when: hubspot, hubspot api, hubspot crm, hubspot integration, contacts api.

540

backend-architect

sickn33

Expert backend architect specializing in scalable API design, microservices architecture, and distributed systems. Masters REST/GraphQL/gRPC APIs, event-driven architectures, service mesh patterns, and modern backend frameworks. Handles service boundary definition, inter-service communication, resilience patterns, and observability. Use PROACTIVELY when creating new backend services or APIs.

1014

plaid-fintech

davila7

Expert patterns for Plaid API integration including Link token flows, transactions sync, identity verification, Auth for ACH, balance checks, webhook handling, and fintech compliance best practices. Use when: plaid, bank account linking, bank connection, ach, account aggregation.

32

generating-grpc-services

jeremylongshore

Generate gRPC service definitions, stubs, and implementations from Protocol Buffers. Use when creating high-performance gRPC services. Trigger with phrases like "generate gRPC service", "create gRPC API", or "build gRPC server".

13

Search skills

Search the agent skills registry