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 ${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
1---
2name: building-websocket-server
3description: |
4 Build scalable WebSocket servers for real-time bidirectional communication.
5 Use when enabling real-time bidirectional communication.
6 Trigger with phrases like "build WebSocket server", "add real-time API", or "implement WebSocket".
7
8allowed-tools: Read, Write, Edit, Grep, Glob, Bash(api:websocket-*)
9version: 1.0.0
10author: Jeremy Longshore <jeremy@intentsolutions.io>
11license: MIT
12compatible-with: claude-code, codex, openclaw
13metadata:
14 source: https://skillmd.com/skills/micsapp/building-websocket-server
15---
16
17# Building WebSocket Server
18
19## Overview
20
21Build 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.
22
23## Prerequisites
24
25- Node.js 18+ with `ws` or `socket.io`, or Python 3.10+ with `websockets` or FastAPI WebSocket, or Go with `gorilla/websocket`
26- Redis for horizontal scaling with pub/sub adapter (Socket.IO Redis adapter, or manual pub/sub)
27- Load balancer configured for WebSocket upgrade (sticky sessions or proper `Upgrade` header forwarding)
28- JWT or session-based authentication for connection handshake
29- Monitoring for active connection counts and message throughput
30
31## Instructions
32
331. Examine existing HTTP server configuration using Read and Grep to determine the framework and identify where WebSocket upgrade handling integrates.
342. Create a WebSocket server instance attached to the existing HTTP server, configuring the upgrade path (e.g., `/ws`, `/socket.io`) and allowed origins.
353. Implement connection authentication by validating JWT tokens or session cookies during the WebSocket handshake `upgrade` event, rejecting unauthorized connections before protocol switch.
364. Build a connection registry that tracks active clients with metadata (user ID, subscribed channels, connection time) for targeted message delivery.
375. Define a message protocol using JSON envelopes with `type`, `channel`, `payload`, and `correlationId` fields for structured bidirectional communication.
386. Implement room/channel subscription logic allowing clients to join and leave named channels with server-side membership tracking.
397. Add heartbeat ping/pong mechanism with configurable interval (default 30s) and timeout detection to clean up stale connections.
408. Configure Redis pub/sub adapter for horizontal scaling so messages broadcast from any server instance reach all connected clients across the cluster.
419. Write connection lifecycle tests covering connect, authenticate, subscribe, message exchange, reconnect, and graceful disconnect scenarios.
42
43See `${CLAUDE_SKILL_DIR}/references/implementation.md` for the full implementation guide.
44
45## Output
46
47- `${CLAUDE_SKILL_DIR}/src/ws/server.js` - WebSocket server setup and upgrade handling
48- `${CLAUDE_SKILL_DIR}/src/ws/handlers/` - Per-message-type handler functions
49- `${CLAUDE_SKILL_DIR}/src/ws/rooms.js` - Room/channel subscription management
50- `${CLAUDE_SKILL_DIR}/src/ws/registry.js` - Active connection tracking registry
51- `${CLAUDE_SKILL_DIR}/src/ws/heartbeat.js` - Ping/pong keepalive logic
52- `${CLAUDE_SKILL_DIR}/src/ws/adapters/redis.js` - Redis pub/sub adapter for scaling
53- `${CLAUDE_SKILL_DIR}/tests/ws/` - WebSocket connection and messaging tests
54
55## Error Handling
56
57| Error | Cause | Solution |
58|-------|-------|----------|
59| 401 during upgrade | JWT token missing or expired in handshake query/headers | Reject upgrade with HTTP 401 before WebSocket protocol switch completes |
60| 1008 Policy Violation | Client sends malformed message or violates protocol | Send close frame with code 1008 and human-readable reason; log violation |
61| 1006 Abnormal Closure | Network interruption without close handshake | Detect via heartbeat timeout; clean up connection registry; notify room members |
62| Memory leak | Connection registry grows unbounded from stale entries | Implement heartbeat-based cleanup sweep every 60s; enforce max connections per server |
63| Message storm | Single client flooding messages beyond acceptable rate | Apply per-connection message rate limiting; disconnect abusive clients with 1008 |
64
65Refer to `${CLAUDE_SKILL_DIR}/references/errors.md` for comprehensive error patterns.
66
67## Examples
68
69**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.
70
71**Live dashboard**: Server pushes metric updates to subscribed dashboard clients every second, with initial state snapshot on connection and incremental deltas thereafter.
72
73**Collaborative editing**: Operational transformation relay server that receives edit operations from clients, transforms against concurrent operations, and broadcasts resolved changes to all document subscribers.
74
75See `${CLAUDE_SKILL_DIR}/references/examples.md` for additional examples.
76
77## Resources
78
79- RFC 6455 The WebSocket Protocol
80- Socket.IO documentation: https://socket.io/docs/v4/
81- `ws` library: https://github.com/websockets/ws
82- Redis pub/sub for WebSocket scaling patterns