websocket-builder
When the user wants to build real-time features using WebSockets. Use when the user mentions "WebSocket," "real-time," "live updates," "socket," "ws," "push notifications," "live chat," "streaming data," or "bidirectional communication." Covers server setup, room management, authentication, reconnection handling, and scaling with Redis pub/sub. For data persistence, see realtime-database.
What this skill does
# WebSocket Builder
## Overview
Builds production-ready WebSocket servers for real-time features — chat, live dashboards, collaborative editing, notifications. Handles the hard parts: authentication during handshake, room/channel management, connection lifecycle, automatic reconnection, message ordering, and horizontal scaling via Redis pub/sub.
## Instructions
### 1. Server Setup
When setting up a WebSocket server:
- Attach to existing HTTP server (share the port)
- Use a mature library: `ws` for Node.js, `websockets` for Python, `gorilla/websocket` for Go
- Implement ping/pong heartbeats (30s interval, 90s timeout)
- Set max message size to prevent abuse (default: 64KB)
- Add connection limits per user (default: 5 concurrent connections)
### 2. Authentication
Authenticate during the WebSocket handshake, not after:
```
1. Client connects with token in query string: ws://host/ws?token=<jwt>
2. Server validates JWT before upgrading the connection
3. If invalid → reject with 401 before upgrade completes
4. Attach user context to the socket object for later use
```
Do NOT accept auth via a post-connection message — the connection is already open and resources allocated.
### 3. Room/Channel Management
```
RoomManager:
join(socketId, roomId) — Add socket to room, notify members
leave(socketId, roomId) — Remove socket, notify members
broadcast(roomId, event, data, excludeSocketId?) — Send to all in room
getMembers(roomId) — List connected user IDs
getUserRooms(socketId) — List rooms for a socket
On connect: auto-join user's channel rooms from database
On disconnect: leave all rooms, broadcast presence update
```
### 4. Event Routing
Use a message format with event types:
```json
{ "event": "message.send", "data": { "channelId": "ch_1", "content": "Hello" }, "id": "client-uuid" }
```
Route events to handlers:
```
eventHandlers = {
"message.send": handleMessageSend,
"message.edit": handleMessageEdit,
"typing.start": handleTypingStart,
"presence.heartbeat": handleHeartbeat
}
```
Always include a client-generated `id` for idempotency and acknowledgment.
### 5. Scaling with Redis Pub/Sub
For multi-server deployments:
```
1. Each server subscribes to Redis channels matching room IDs
2. On broadcast: publish to Redis channel instead of local-only broadcast
3. Each server receives the publish and forwards to local sockets in that room
4. Use Redis adapter (e.g., @socket.io/redis-adapter or custom with ioredis)
```
### 6. Reconnection Protocol
```
Client-side:
1. On disconnect: attempt reconnect with exponential backoff (1s, 2s, 4s, max 30s)
2. On reconnect: send last_event_id to server
3. Server replays missed events since that ID
4. Client merges with local state, deduplicating by event ID
Server-side:
1. Keep recent events in Redis sorted set (TTL: 1 hour)
2. On reconnect with last_event_id: return all events after that ID
3. If ID is too old (beyond retention): send full state refresh
```
## Examples
### Example 1: Chat WebSocket Server (Node.js)
**Prompt**: "Set up a WebSocket server for my Express app with rooms and JWT auth"
**Output**: Server with authenticated connections, room manager, event routing, ping/pong heartbeats, and reconnection support. Files: `ws/server.ts`, `ws/rooms.ts`, `ws/handlers/`, `ws/middleware/auth.ts`.
### Example 2: Live Dashboard (Python)
**Prompt**: "I need real-time updates for a monitoring dashboard. FastAPI backend, 500 concurrent viewers."
**Output**: WebSocket endpoint with broadcast-only channels (viewers don't send), Redis pub/sub for horizontal scaling, connection pooling, and automatic cleanup. Files: `realtime/server.py`, `realtime/broadcaster.py`, `realtime/redis_pubsub.py`.
## Guidelines
- **Always authenticate at handshake** — never after connection is open
- **Use binary frames** for large payloads (images, files) — text frames for JSON
- **Implement backpressure** — if a client can't keep up, buffer then disconnect
- **Log connection lifecycle** — connect, disconnect, error, room join/leave (debugging is hard without this)
- **Test with connection drops** — kill connections mid-message to verify recovery
- **Set idle timeouts** — disconnect clients that stop sending heartbeats
- **Never trust client input** — validate every message against expected schema
Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.