jpskill.com
🛠️ 開発・MCP コミュニティ

websocket-engineer

WebSocketやWebRTCなど、リアルタイム通信技術を駆使して、双方向かつ高速な情報伝達システムを構築するSkill。

📜 元の英語説明(参考)

Expert in real-time communication systems, including WebSockets, Socket.IO, SSE, and WebRTC.

🇯🇵 日本人クリエイター向け解説

一言でいうと

WebSocketやWebRTCなど、リアルタイム通信技術を駆使して、双方向かつ高速な情報伝達システムを構築するSkill。

※ jpskill.com 編集部が日本のビジネス現場向けに補足した解説です。Skill本体の挙動とは独立した参考情報です。

⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。

🎯 このSkillでできること

下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。

📦 インストール方法 (3ステップ)

  1. 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
  2. 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
  3. 3. 展開してできたフォルダを、ホームフォルダの .claude/skills/ に置く
    • · macOS / Linux: ~/.claude/skills/
    • · Windows: %USERPROFILE%\.claude\skills\

Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。

詳しい使い方ガイドを見る →
最終更新
2026-05-17
取得日時
2026-05-17
同梱ファイル
1

📖 Skill本文(日本語訳)

※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。

WebSocket & リアルタイムエンジニア

目的

WebSocketアーキテクチャ、Socket.IO、およびイベント駆動型システムに特化したリアルタイム通信の専門知識を提供します。数百万の同時接続にスケール可能な、低遅延で双方向の通信システムを構築します。

使用する場面

  • チャットアプリ、ライブダッシュボード、またはマルチプレイヤーゲームの構築
  • WebSocketサーバーの水平スケーリング(Redis Adapter)
  • 一方向の更新のための「Server-Sent Events」(SSE)の実装
  • 接続切断、ハートビート障害、またはCORS問題のトラブルシューティング
  • ステートフルな接続アーキテクチャの設計
  • ポーリングからプッシュ技術への移行

例1:リアルタイムチャットアプリケーション

シナリオ: 企業向けのスケーラブルなチャットプラットフォームを構築します。

実装:

  1. Socket.IOを使用したWebSocketアーキテクチャを設計しました。
  2. 水平スケーリングのためにRedis Adapterを実装しました。
  3. ルームベースのメッセージルーティングを作成しました。
  4. メッセージの永続化と履歴を追加しました。
  5. プレゼンスシステム(オンライン/オフライン)を実装しました。

結果:

  • 100,000以上の同時接続をサポートします。
  • 平均メッセージ配信時間は50msです。
  • 99.99%の接続安定性があります。
  • シームレスな水平スケーリングを実現します。

例2:ライブダッシュボードシステム

シナリオ: サブ秒単位で更新されるリアルタイム分析ダッシュボードです。

実装:

  1. 低遅延のWebSocketサーバーを実装しました。
  2. 効率的なメッセージバッチ処理戦略を作成しました。
  3. マルチサーバーサポートのためにRedis pub/subを追加しました。
  4. クライアント側の更新結合を実装しました。
  5. 大容量ペイロードのために圧縮を追加しました。

結果:

  • ダッシュボードの更新は100ms未満です。
  • 10,000の同時ダッシュボードビューを処理します。
  • ポーリングと比較してサーバー負荷を80%削減します。
  • 再接続中のデータ損失はゼロです。

例3:マルチプレイヤーゲームバックエンド

シナリオ: 低遅延のマルチプレイヤーゲームサーバーです。

実装:

  1. バイナリプロトコルを使用したWebSocketサーバーを実装しました。
  2. 権威あるサーバーアーキテクチャを作成しました。
  3. クライアント側の予測と調整を追加しました。
  4. ラグ補償アルゴリズムを実装しました。
  5. サーバー側の物理演算と衝突検出を設定しました。

結果:

  • エンドツーエンドの遅延は30msです。
  • サーバーあたり1000人の同時プレイヤーをサポートします。
  • ネットワークの変動にもかかわらずスムーズなゲームプレイを実現します。
  • チート耐性のあるサーバー権限があります。

ベストプラクティス

接続管理

  • ハートビート: 接続状態のためにping/pongを実装します。
  • 再接続: バックオフ付きの自動再接続を行います。
  • 状態クリーンアップ: 切断時に適切なクリーンアップを行います。
  • 接続制限: リソース枯渇を防ぎます。

スケーリング

  • 水平スケーリング: マルチサーバーのためにRedis Adapterを使用します。
  • スティッキーセッション: 適切なロードバランサー設定を行います。
  • メッセージルーティング: ブロードキャスト/ユニキャストのための効率的なルーティングを行います。
  • レート制限: 乱用と過負荷を防ぎます。

パフォーマンス

  • メッセージバッチ処理: 適切な場合にメッセージをバッチ処理します。
  • 圧縮: メッセージを圧縮します(permessage-deflate)。
  • バイナリプロトコル: パフォーマンスが重要なデータにはバイナリを使用します。
  • 接続プール: 効率的なクライアント接続の再利用を行います。

セキュリティ

  • 認証: ハンドシェイク時に検証します。
  • TLS: 常にWSSを使用します。
  • 入力検証: すべての受信メッセージを検証します。
  • レート制限: 接続/メッセージレートを制限します。


2. 意思決定フレームワーク

プロトコル選択

What is the communication pattern?
│
├─ **Bi-directional (Chat/Game)**
│  ├─ Low Latency needed? → **WebSockets (Raw)**
│  ├─ Fallbacks/Auto-reconnect needed? → **Socket.IO**
│  └─ P2P Video/Audio? → **WebRTC**
│
├─ **One-way (Server → Client)**
│  ├─ Stock Ticker / Notifications? → **Server-Sent Events (SSE)**
│  └─ Large File Download? → **HTTP Stream**
│
└─ **High Frequency (IoT)**
   └─ Constrained device? → **MQTT** (over TCP/WS)

スケーリング戦略

スケール アーキテクチャ バックエンド
< 1万ユーザー モノリス Node.js シングルインスタンス
1万 - 10万 クラスタリング Node.js Cluster + Redis Adapter
10万 - 100万 マイクロサービス Go/Elixir/Rust + NATS/Kafka
グローバル エッジ Cloudflare Workers / PubNub / Pusher

ロードバランサー設定

  • スティッキーセッション: Socket.IO(ハンドシェイクフェーズ)には必須です。
  • タイムアウト: アイドルタイムアウトを長くします(例:60秒以上)。
  • ヘッダー: Upgrade: websocketConnection: Upgrade

危険信号 → security-engineer にエスカレート:

  • 任意のOrigin (*) からの認証情報付き接続を受け入れる
  • 接続要求にレート制限がない(DoSリスク)
  • URLクエリパラメータでJWTを送信する(プロキシログに記録される) - 代わりにCookieまたは初期メッセージを使用する


3. コアワークフロー

ワークフロー1:スケーラブルなSocket.IOサーバー(Node.js)

目標: 複数のコア/インスタンスにスケール可能なチャットサーバー。

手順:

  1. 依存関係のインストール

    npm install socket.io redis @socket.io/redis-adapter
  2. 実装 (server.js)

    const { Server } = require("socket.io");
    const { createClient } = require("redis");
    const { createAdapter } = require("@socket.io/redis-adapter");
    
    const pubClient = createClient({ url: "redis://localhost:6379" });
    const subClient = pubClient.duplicate();
    
    Promise.all([pubClient.connect(), subClient.connect()]).then(() => {
      const io = new Server(3000, {
        adapter: createAdapter(pubClient, subClient),
        cors: {
          origin: "https://myapp.com",
          methods: ["GET", "POST"]
        }
      });
    
      io.on("connection", (socket) => {
        // User joins a room (e.g., "chat-123")
        socket.on("join", (room) => {
          socket.join(room);
        });
    
        // Send message to room (propagates via Redis to all nodes)
        socket.on("message", (data) => {
          io.to(data.room).emit("chat", data.text);
        });
      });
    });


ワークフロー3:本番環境チューニング(Linux)

目標: 単一サーバーで5万の同時接続を処理します。

手順:

  1. ファイルディスクリプタ

    • 制限を増やします: ulimit -n 65535
    • /etc/security/limits.conf を編集します。
  2. Epheme

📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開

WebSocket & Real-Time Engineer

Purpose

Provides real-time communication expertise specializing in WebSocket architecture, Socket.IO, and event-driven systems. Builds low-latency, bidirectional communication systems scaling to millions of concurrent connections.

When to Use

  • Building chat apps, live dashboards, or multiplayer games
  • Scaling WebSocket servers horizontally (Redis Adapter)
  • Implementing "Server-Sent Events" (SSE) for one-way updates
  • Troubleshooting connection drops, heartbeat failures, or CORS issues
  • Designing stateful connection architectures
  • Migrating from polling to push technology

Examples

Example 1: Real-Time Chat Application

Scenario: Building a scalable chat platform for enterprise use.

Implementation:

  1. Designed WebSocket architecture with Socket.IO
  2. Implemented Redis Adapter for horizontal scaling
  3. Created room-based message routing
  4. Added message persistence and history
  5. Implemented presence system (online/offline)

Results:

  • Supports 100,000+ concurrent connections
  • 50ms average message delivery
  • 99.99% connection stability
  • Seamless horizontal scaling

Example 2: Live Dashboard System

Scenario: Real-time analytics dashboard with sub-second updates.

Implementation:

  1. Implemented WebSocket server with low latency
  2. Created efficient message batching strategy
  3. Added Redis pub/sub for multi-server support
  4. Implemented client-side update coalescing
  5. Added compression for large payloads

Results:

  • Dashboard updates in under 100ms
  • Handles 10,000 concurrent dashboard views
  • 80% reduction in server load vs polling
  • Zero data loss during reconnections

Example 3: Multiplayer Game Backend

Scenario: Low-latency multiplayer game server.

Implementation:

  1. Implemented WebSocket server with binary protocols
  2. Created authoritative server architecture
  3. Added client-side prediction and reconciliation
  4. Implemented lag compensation algorithms
  5. Set up server-side physics and collision detection

Results:

  • 30ms end-to-end latency
  • Supports 1000 concurrent players per server
  • Smooth gameplay despite network variations
  • Cheat-resistant server authority

Best Practices

Connection Management

  • Heartbeats: Implement ping/pong for connection health
  • Reconnection: Automatic reconnection with backoff
  • State Cleanup: Proper cleanup on disconnect
  • Connection Limits: Prevent resource exhaustion

Scaling

  • Horizontal Scaling: Use Redis Adapter for multi-server
  • Sticky Sessions: Proper load balancer configuration
  • Message Routing: Efficient routing for broadcast/unicast
  • Rate Limiting: Prevent abuse and overload

Performance

  • Message Batching: Batch messages where appropriate
  • Compression: Compress messages (permessage-deflate)
  • Binary Protocols: Use binary for performance-critical data
  • Connection Pooling: Efficient client connection reuse

Security

  • Authentication: Validate on handshake
  • TLS: Always use WSS
  • Input Validation: Validate all incoming messages
  • Rate Limiting: Limit connection/message rates


2. Decision Framework

Protocol Selection

What is the communication pattern?
│
├─ **Bi-directional (Chat/Game)**
│  ├─ Low Latency needed? → **WebSockets (Raw)**
│  ├─ Fallbacks/Auto-reconnect needed? → **Socket.IO**
│  └─ P2P Video/Audio? → **WebRTC**
│
├─ **One-way (Server → Client)**
│  ├─ Stock Ticker / Notifications? → **Server-Sent Events (SSE)**
│  └─ Large File Download? → **HTTP Stream**
│
└─ **High Frequency (IoT)**
   └─ Constrained device? → **MQTT** (over TCP/WS)

Scaling Strategy

Scale Architecture Backend
< 10k Users Monolith Node.js Single Instance
10k - 100k Clustering Node.js Cluster + Redis Adapter
100k - 1M Microservices Go/Elixir/Rust + NATS/Kafka
Global Edge Cloudflare Workers / PubNub / Pusher

Load Balancer Config

  • Sticky Sessions: REQUIRED for Socket.IO (handshake phase).
  • Timeouts: Increase idle timeouts (e.g., 60s+).
  • Headers: Upgrade: websocket, Connection: Upgrade.

Red Flags → Escalate to security-engineer:

  • Accepting connections from any Origin (*) with credentials
  • No Rate Limiting on connection requests (DoS risk)
  • Sending JWTs in URL query params (Logged in proxy logs) - Use Cookie or Initial Message instead


3. Core Workflows

Workflow 1: Scalable Socket.IO Server (Node.js)

Goal: Chat server capable of scaling across multiple cores/instances.

Steps:

  1. Install Dependencies

    npm install socket.io redis @socket.io/redis-adapter
  2. Implementation (server.js)

    const { Server } = require("socket.io");
    const { createClient } = require("redis");
    const { createAdapter } = require("@socket.io/redis-adapter");
    
    const pubClient = createClient({ url: "redis://localhost:6379" });
    const subClient = pubClient.duplicate();
    
    Promise.all([pubClient.connect(), subClient.connect()]).then(() => {
      const io = new Server(3000, {
        adapter: createAdapter(pubClient, subClient),
        cors: {
          origin: "https://myapp.com",
          methods: ["GET", "POST"]
        }
      });
    
      io.on("connection", (socket) => {
        // User joins a room (e.g., "chat-123")
        socket.on("join", (room) => {
          socket.join(room);
        });
    
        // Send message to room (propagates via Redis to all nodes)
        socket.on("message", (data) => {
          io.to(data.room).emit("chat", data.text);
        });
      });
    });


Workflow 3: Production Tuning (Linux)

Goal: Handle 50k concurrent connections on a single server.

Steps:

  1. File Descriptors

    • Increase limit: ulimit -n 65535.
    • Edit /etc/security/limits.conf.
  2. Ephemeral Ports

    • Increase range: sysctl -w net.ipv4.ip_local_port_range="1024 65535".
  3. Memory Optimization

    • Use ws (lighter) instead of Socket.IO if features not needed.
    • Disable "Per-Message Deflate" (Compression) if CPU is high.


5. Anti-Patterns & Gotchas

❌ Anti-Pattern 1: Stateful Monolith

What it looks like:

  • Storing users = [] array in Node.js memory.

Why it fails:

  • When you scale to 2 servers, User A on Server 1 cannot talk to User B on Server 2.
  • Memory leaks crash the process.

Correct approach:

  • Use Redis as the state store (Adapter).
  • Stateless servers, Stateful backend (Redis).

❌ Anti-Pattern 2: The "Thundering Herd"

What it looks like:

  • Server restarts. 100,000 clients reconnect instantly.
  • Server crashes again due to CPU spike.

Why it fails:

  • Connection handshakes are expensive (TLS + Auth).

Correct approach:

  • Randomized Jitter: Clients wait random(0, 10s) before reconnecting.
  • Exponential Backoff: Wait 1s, then 2s, then 4s...

❌ Anti-Pattern 3: Blocking the Event Loop

What it looks like:

  • socket.on('message', () => { heavyCalculation(); })

Why it fails:

  • Node.js is single-threaded. One heavy task blocks all 10,000 connections.

Correct approach:

  • Offload work to a Worker Thread or Message Queue (RabbitMQ/Bull).


7. Quality Checklist

Scalability:

  • [ ] Adapter: Redis/NATS adapter configured for multi-node.
  • [ ] Load Balancer: Sticky sessions enabled (if using polling fallback).
  • [ ] OS Limits: File descriptors limit increased.

Resilience:

  • [ ] Reconnection: Exponential backoff + Jitter implemented.
  • [ ] Heartbeat: Ping/Pong interval configured (< LB timeout).
  • [ ] Fallback: Socket.IO fallbacks (HTTP Long Polling) enabled/tested.

Security:

  • [ ] WSS: TLS enabled (Secure WebSockets).
  • [ ] Auth: Handshake validates credentials properly.
  • [ ] Rate Limit: Connection rate limiting active.

Anti-Patterns

Connection Management Anti-Patterns

  • No Heartbeats: Not detecting dead connections - implement ping/pong
  • Memory Leaks: Not cleaning up closed connections - implement proper cleanup
  • Infinite Reconnects: Reloop without backoff - implement exponential backoff
  • Sticky Sessions Required: Not designing for stateless - use Redis for state

Scaling Anti-Patterns

  • Single Server: Not scaling beyond one instance - use Redis adapter
  • No Load Balancing: Direct connections to servers - use proper load balancer
  • Broadcast Storm: Sending to all connections blindly - target specific connections
  • Connection Saturation: Too many connections per server - scale horizontally

Performance Anti-Patterns

  • Message Bloat: Large unstructured messages - use efficient message formats
  • No Throttling: Unlimited send rates - implement rate limiting
  • Blocking Operations: Synchronous processing - use async processing
  • No Monitoring: Operating blind - implement connection metrics

Security Anti-Patterns

  • No TLS: Using unencrypted connections - always use WSS
  • Weak Auth: Simple token validation - implement proper authentication
  • No Rate Limits: Vulnerable to abuse - implement connection/message limits
  • CORS Exposed: Open cross-origin access - configure proper CORS