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