building-websocket-server

Build scalable WebSocket servers for real-time bidirectional communication. Use when enabling real-time bidirectional communication. Trigger with phrases like "build WebSocket server", "add real-time API", or "implement WebSocket".

25 stars

Best use case

building-websocket-server is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

Build scalable WebSocket servers for real-time bidirectional communication. Use when enabling real-time bidirectional communication. Trigger with phrases like "build WebSocket server", "add real-time API", or "implement WebSocket".

Teams using building-websocket-server should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/building-websocket-server/SKILL.md --create-dirs "https://raw.githubusercontent.com/ComeOnOliver/skillshub/main/skills/jeremylongshore/claude-code-plugins-plus-skills/building-websocket-server/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/building-websocket-server/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How building-websocket-server Compares

Feature / Agentbuilding-websocket-serverStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

Build scalable WebSocket servers for real-time bidirectional communication. Use when enabling real-time bidirectional communication. Trigger with phrases like "build WebSocket server", "add real-time API", or "implement WebSocket".

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

SKILL.md Source

# 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

| Error | Cause | Solution |
|-------|-------|----------|
| 401 during upgrade | JWT token missing or expired in handshake query/headers | Reject upgrade with HTTP 401 before WebSocket protocol switch completes |
| 1008 Policy Violation | Client sends malformed message or violates protocol | Send close frame with code 1008 and human-readable reason; log violation |
| 1006 Abnormal Closure | Network interruption without close handshake | Detect via heartbeat timeout; clean up connection registry; notify room members |
| Memory leak | Connection registry grows unbounded from stale entries | Implement heartbeat-based cleanup sweep every 60s; enforce max connections per server |
| Message storm | Single client flooding messages beyond acceptable rate | Apply 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

- RFC 6455 The WebSocket Protocol
- Socket.IO documentation: https://socket.io/docs/v4/
- `ws` library: https://github.com/websockets/ws
- Redis pub/sub for WebSocket scaling patterns

Related Skills

websocket-handler-setup

25
from ComeOnOliver/skillshub

Websocket Handler Setup - Auto-activating skill for Backend Development. Triggers on: websocket handler setup, websocket handler setup Part of the Backend Development skill category.

websocket-client-creator

25
from ComeOnOliver/skillshub

Websocket Client Creator - Auto-activating skill for API Integration. Triggers on: websocket client creator, websocket client creator Part of the API Integration skill category.

building-terraform-modules

25
from ComeOnOliver/skillshub

This skill empowers Claude to build reusable Terraform modules based on user specifications. It leverages the terraform-module-builder plugin to generate production-ready, well-documented Terraform module code, incorporating best practices for security, scalability, and multi-platform support. Use this skill when the user requests to create a new Terraform module, generate Terraform configuration, or needs help structuring infrastructure as code using Terraform. The trigger terms include "create Terraform module," "generate Terraform configuration," "Terraform module code," and "infrastructure as code."

server-sent-events-setup

25
from ComeOnOliver/skillshub

Server Sent Events Setup - Auto-activating skill for API Integration. Triggers on: server sent events setup, server sent events setup Part of the API Integration skill category.

building-recommendation-systems

25
from ComeOnOliver/skillshub

This skill empowers Claude to construct recommendation systems using collaborative filtering, content-based filtering, or hybrid approaches. It analyzes user preferences, item features, and interaction data to generate personalized recommendations. Use this skill when the user requests to build a recommendation engine, needs help with collaborative filtering, wants to implement content-based filtering, or seeks to rank items based on relevance for a specific user or group of users. It is triggered by requests involving "recommendations", "collaborative filtering", "content-based filtering", "ranking items", or "building a recommender".

building-neural-networks

25
from ComeOnOliver/skillshub

This skill allows Claude to construct and configure neural network architectures using the neural-network-builder plugin. It should be used when the user requests the creation of a new neural network, modification of an existing one, or assistance with defining the layers, parameters, and training process. The skill is triggered by requests involving terms like "build a neural network," "define network architecture," "configure layers," or specific mentions of neural network types (e.g., "CNN," "RNN," "transformer").

building-gitops-workflows

25
from ComeOnOliver/skillshub

This skill enables Claude to construct GitOps workflows using ArgoCD and Flux. It is designed to generate production-ready configurations, implement best practices, and ensure a security-first approach for Kubernetes deployments. Use this skill when the user explicitly requests "GitOps workflow", "ArgoCD", "Flux", or asks for help with setting up a continuous delivery pipeline using GitOps principles. The skill will generate the necessary configuration files and setup code based on the user's specific requirements and infrastructure.

building-classification-models

25
from ComeOnOliver/skillshub

This skill enables Claude to construct and evaluate classification models using provided datasets or specifications. It leverages the classification-model-builder plugin to automate model creation, optimization, and reporting. Use this skill when the user requests to "build a classifier", "create a classification model", "train a classification model", or needs help with supervised learning tasks involving labeled data. The skill ensures best practices are followed, including data validation, error handling, and performance metric reporting.

building-graphql-server

25
from ComeOnOliver/skillshub

Build production-ready GraphQL servers with schema design, resolvers, and subscriptions. Use when building GraphQL APIs with schemas and resolvers. Trigger with phrases like "build GraphQL API", "create GraphQL server", or "setup GraphQL".

building-cicd-pipelines

25
from ComeOnOliver/skillshub

Execute use when you need to work with deployment and CI/CD. This skill provides deployment automation and pipeline orchestration with comprehensive guidance and automation. Trigger with phrases like "deploy application", "create pipeline", or "automate deployment".

building-automl-pipelines

25
from ComeOnOliver/skillshub

Build automated machine learning pipelines with feature engineering, model selection, and hyperparameter tuning. Use when automating ML workflows from data preparation through model deployment. Trigger with phrases like "build automl pipeline", "automate ml workflow", or "create automated training pipeline".

building-api-gateway

25
from ComeOnOliver/skillshub

Create API gateways with routing, load balancing, rate limiting, and authentication. Use when routing and managing multiple API services. Trigger with phrases like "build API gateway", "create API router", or "setup API gateway".