Command Palette

Search for a command to run...

Назад к скиллам
скилл № 13447

backend-websocket-patterns

Use when the user asks about WebSockets, live chat with socket.io and rooms, Server-Sent Events, heartbeats, reconnection, broadcasting or scaling WebSockets…

БесплатноБез исполняемых скриптов
j4flmaoот j4flmao★ 47 звёзд на GitHub

Установить backend-websocket-patterns в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Об этом скилле

Backend WebSocket Patterns

Purpose

Design consistent, production-grade WebSocket services. Every connection must follow the same conventions for handshake, message framing, room management, reconnection, error handling, and cross-node scaling.

Agent Protocol

Trigger

Exact user phrases: "WebSocket", "real-time", "socket.io", "WS connection", "reconnection", "WS rooms", "broadcast", "WS scaling", "WS clustering", "pub/sub over WS", "SSE", "Server-Sent Events", "long polling", "WS handshake", "design a WebSocket server".

Input Context

Before activating, verify:

  • The real-time feature being designed is known.
  • The transport (raw WebSocket / Socket.IO / SSE) is chosen. If not, ask: "Raw WebSocket, Socket.IO, or SSE?"
  • The scaling requirement (single node vs multi-node) is known.
  • The authentication model is known.

Output Artifact

No file output unless the user requests it. Produces WebSocket connection specs and message protocols as text.

Response Format

For each message type:

Event: {event_name}
Direction: {client→server | server→client | bidirectional}
Payload: {schema reference}
Ack: {required/optional/none}

For a full connection spec:

## Connection
Endpoint: {ws/wss}://{host}/{path}
Auth: {mechanism}

## Messages
{list of message types}

## Lifecycle
{connection → auth → subscribe → message → disconnect}

No preamble. No postamble. No explanations. No filler/hedging/transitions. Compress output — why use many token when few do trick.

Completion Criteria

  • Connection lifecycle (handshake, auth, heartbeat, teardown) is documented.
  • Every message type has: event name, direction, payload schema, ack requirement.
  • Reconnection strategy (backoff, max attempts, jitter) is defined.
  • Room/subscription model is defined.
  • Scaling strategy (sticky sessions vs external pub/sub) is documented.
  • Error handling and disconnect scenarios are covered.

Max Response Length

Per message type: 5 lines. Per connection spec: unlimited.

Decision Tree

Which Transport?

What is your use case?
  ├── Bidirectional, need low latency, full control
  │   └── Raw WebSocket — minimal overhead, no auto-reconnect, no fallback
  ├── Bidirectional, need auto-reconnect, rooms, fallback
  │   └── Socket.IO — rooms, namespaces, auto-reconnect, long-polling fallback
  ├── Server→client only (notifications, stream updates)
  │   └── SSE (Server-Sent Events) — simpler, HTTP-native, auto-reconnect via EventSource
  └── Client needs to push AND receive, but SSE + POST is simpler
      └── SSE for server→client + POST for client→server (REST-like)

Single Node vs Multi-Node?

How many instances?
  ├── Single instance (small app, dev, low traffic)
  │   └── In-memory socket map, no external deps
  ├── Multiple instances, sticky sessions available
  │   └── Sticky sessions + in-memory socket map (server affinity)
  ├── Multiple instances, no sticky sessions
  │   └── External pub/sub (Redis, NATS, Kafka) for cross-node broadcast
  └── Global scale, many regions
      └── Global pub/sub + edge WebSocket termination

Workflow

Step 1: Choose Transport

Raw WebSocket:  minimal overhead, full control, no auto-reconnect, no fallback
Socket.IO:      rooms, namespaces, auto-reconnect, fallback to long-polling
SSE:            server→only, text-only, auto-reconnect via EventSource, no binary

Step 2: Define Connection Lifecycle

1. TCP handshake → HTTP upgrade request
2. Auth verification (token in query param / first message / cookie)
3. Heartbeat established (ping/pong every N seconds)
4. Subscribe to rooms/channels
5. Message exchange
6. Graceful disconnect (close frame with code + reason)

Step 3: Message Framing

Use a consistent JSON envelope for every message:

{
  "event": "string",
  "data": {},
  "id": "uuid",
  "timestamp": "2026-05-18T10:00:00Z"
}

Ack response:

{
  "event": "ack",
  "data": { "ackId": "uuid", "status": "ok" },
  "id": "uuid",
  "timestamp": "2026-05-18T10:00:01Z"
}

Error response:

{
  "event": "error",
  "data": { "code": "INVALID_MESSAGE", "message": "Reason" },
  "id": "uuid",
  "timestamp": "2026-05-18T10:00:01Z"
}

Step 4: Room / Subscription Model

JOIN room:{roomId}     → Subscribe to room events
LEAVE room:{roomId}    → Unsubscribe from room events

Server broadcasts:
  {event, data}        → All clients in room
  {event, data, except: [clientId]} → All clients except sender

Room metadata (track per room):

{ roomId, memberCount, metadata: {}, createdAt }

Step 5: Reconnection Strategy

Exponential backoff with jitter:
  Attempt 1: 1s
  Attempt 2: 2s
  Attempt 3: 4s
  Attempt 4: 8s
  ...
  Max delay: 30s
  Max attempts: 10
  Jitter: ±50%

On reconnect:
  1. New handshake + auth
  2. Client sends resume with last received event ID
  3. Server replays missed events from buffer (configurable TTL)

Step 6: Scaling Across

Полный SKILL.md на GitHub

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

  • references/event_sync_logic.md
  • references/reconnection-strategy.md
  • references/socket-io-patterns.md
  • references/websocket-auth.md
  • references/websocket-implementation.md
  • references/websocket-monitoring.md
  • references/websocket-patterns.md
  • references/websocket_state_management.md
  • references/ws-vs-sse.md

FAQ

Что делает скилл backend-websocket-patterns?

Use when the user asks about WebSockets, live chat with socket.io and rooms, Server-Sent Events, heartbeats, reconnection, broadcasting or scaling WebSockets with Redis pub/sub. Produces real-time messaging server code. Not for audio/video calls (use backend-web-real-time).

Как установить скилл backend-websocket-patterns?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл backend-websocket-patterns запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить backend-websocket-patterns с