{
  "schemaVersion": "1.0",
  "item": {
    "slug": "websocket-hub-patterns",
    "name": "Websocket Hub Patterns",
    "source": "tencent",
    "type": "skill",
    "category": "开发工具",
    "sourceUrl": "https://clawhub.ai/wpank/websocket-hub-patterns",
    "canonicalUrl": "https://clawhub.ai/wpank/websocket-hub-patterns",
    "targetPlatform": "OpenClaw"
  },
  "install": {
    "downloadMode": "redirect",
    "downloadUrl": "/downloads/websocket-hub-patterns",
    "sourceDownloadUrl": "https://wry-manatee-359.convex.site/api/v1/download?slug=websocket-hub-patterns",
    "sourcePlatform": "tencent",
    "targetPlatform": "OpenClaw",
    "installMethod": "Manual import",
    "extraction": "Extract archive",
    "prerequisites": [
      "OpenClaw"
    ],
    "packageFormat": "ZIP package",
    "includedAssets": [
      "README.md",
      "SKILL.md"
    ],
    "primaryDoc": "SKILL.md",
    "quickSetup": [
      "Download the package from Yavira.",
      "Extract the archive and review SKILL.md first.",
      "Import or place the package into your OpenClaw setup."
    ],
    "agentAssist": {
      "summary": "Hand the extracted package to your coding agent with a concrete install brief instead of figuring it out manually.",
      "steps": [
        "Download the package from Yavira.",
        "Extract it into a folder your agent can access.",
        "Paste one of the prompts below and point your agent at the extracted folder."
      ],
      "prompts": [
        {
          "label": "New install",
          "body": "I downloaded a skill package from Yavira. Read SKILL.md from the extracted folder and install it by following the included instructions. Then review README.md for any prerequisites, environment setup, or post-install checks. Tell me what you changed and call out any manual steps you could not complete."
        },
        {
          "label": "Upgrade existing",
          "body": "I downloaded an updated skill package from Yavira. Read SKILL.md from the extracted folder, compare it with my current installation, and upgrade it while preserving any custom configuration unless the package docs explicitly say otherwise. Then review README.md for any prerequisites, environment setup, or post-install checks. Summarize what changed and any follow-up checks I should run."
        }
      ]
    },
    "sourceHealth": {
      "source": "tencent",
      "status": "healthy",
      "reason": "direct_download_ok",
      "recommendedAction": "download",
      "checkedAt": "2026-05-07T17:22:31.273Z",
      "expiresAt": "2026-05-14T17:22:31.273Z",
      "httpStatus": 200,
      "finalUrl": "https://wry-manatee-359.convex.site/api/v1/download?slug=afrexai-annual-report",
      "contentType": "application/zip",
      "probeMethod": "head",
      "details": {
        "probeUrl": "https://wry-manatee-359.convex.site/api/v1/download?slug=afrexai-annual-report",
        "contentDisposition": "attachment; filename=\"afrexai-annual-report-1.0.0.zip\"",
        "redirectLocation": null,
        "bodySnippet": null
      },
      "scope": "source",
      "summary": "Source download looks usable.",
      "detail": "Yavira can redirect you to the upstream package for this source.",
      "primaryActionLabel": "Download for OpenClaw",
      "primaryActionHref": "/downloads/websocket-hub-patterns"
    },
    "validation": {
      "installChecklist": [
        "Use the Yavira download entry.",
        "Review SKILL.md after the package is downloaded.",
        "Confirm the extracted package contains the expected setup assets."
      ],
      "postInstallChecks": [
        "Confirm the extracted package includes the expected docs or setup files.",
        "Validate the skill or prompts are available in your target agent workspace.",
        "Capture any manual follow-up steps the agent could not complete."
      ]
    },
    "downloadPageUrl": "https://openagent3.xyz/downloads/websocket-hub-patterns",
    "agentPageUrl": "https://openagent3.xyz/skills/websocket-hub-patterns/agent",
    "manifestUrl": "https://openagent3.xyz/skills/websocket-hub-patterns/agent.json",
    "briefUrl": "https://openagent3.xyz/skills/websocket-hub-patterns/agent.md"
  },
  "agentAssist": {
    "summary": "Hand the extracted package to your coding agent with a concrete install brief instead of figuring it out manually.",
    "steps": [
      "Download the package from Yavira.",
      "Extract it into a folder your agent can access.",
      "Paste one of the prompts below and point your agent at the extracted folder."
    ],
    "prompts": [
      {
        "label": "New install",
        "body": "I downloaded a skill package from Yavira. Read SKILL.md from the extracted folder and install it by following the included instructions. Then review README.md for any prerequisites, environment setup, or post-install checks. Tell me what you changed and call out any manual steps you could not complete."
      },
      {
        "label": "Upgrade existing",
        "body": "I downloaded an updated skill package from Yavira. Read SKILL.md from the extracted folder, compare it with my current installation, and upgrade it while preserving any custom configuration unless the package docs explicitly say otherwise. Then review README.md for any prerequisites, environment setup, or post-install checks. Summarize what changed and any follow-up checks I should run."
      }
    ]
  },
  "documentation": {
    "source": "clawhub",
    "primaryDoc": "SKILL.md",
    "sections": [
      {
        "title": "WebSocket Hub Patterns",
        "body": "Production patterns for horizontally-scalable WebSocket connections with Redis-backed coordination."
      },
      {
        "title": "OpenClaw / Moltbot / Clawbot",
        "body": "npx clawhub@latest install websocket-hub-patterns"
      },
      {
        "title": "When to Use",
        "body": "Real-time bidirectional communication\nChat applications, collaborative editing\nLive dashboards with client interactions\nNeed horizontal scaling across multiple gateway instances"
      },
      {
        "title": "Hub Structure",
        "body": "type Hub struct {\n    // Local state\n    connections   map[*Connection]bool\n    subscriptions map[string]map[*Connection]bool // channel -> connections\n\n    // Channels\n    register   chan *Connection\n    unregister chan *Connection\n    broadcast  chan *Event\n\n    // Redis for scaling\n    redisClient  *redis.Client\n    redisSubs    map[string]*goredis.PubSub\n    redisSubLock sync.Mutex\n\n    // Optional: Distributed registry\n    connRegistry *ConnectionRegistry\n    instanceID   string\n\n    // Shutdown\n    done chan struct{}\n    wg   sync.WaitGroup\n}"
      },
      {
        "title": "Hub Main Loop",
        "body": "func (h *Hub) Run() {\n    for {\n        select {\n        case <-h.done:\n            return\n\n        case conn := <-h.register:\n            h.connections[conn] = true\n            if h.connRegistry != nil {\n                h.connRegistry.RegisterConnection(ctx, conn.ID(), info)\n            }\n\n        case conn := <-h.unregister:\n            if _, ok := h.connections[conn]; ok {\n                if h.connRegistry != nil {\n                    h.connRegistry.UnregisterConnection(ctx, conn.ID())\n                }\n                h.removeConnection(conn)\n            }\n\n        case event := <-h.broadcast:\n            h.broadcastToChannel(event)\n        }\n    }\n}"
      },
      {
        "title": "Lazy Redis Subscriptions",
        "body": "Subscribe to Redis only when first local subscriber joins:\n\nfunc (h *Hub) subscribeToChannel(conn *Connection, channel string) error {\n    // Add to local subscriptions\n    if h.subscriptions[channel] == nil {\n        h.subscriptions[channel] = make(map[*Connection]bool)\n    }\n    h.subscriptions[channel][conn] = true\n\n    // Lazy: Only subscribe to Redis on first subscriber\n    h.redisSubLock.Lock()\n    defer h.redisSubLock.Unlock()\n\n    if _, exists := h.redisSubs[channel]; !exists {\n        pubsub := h.redisClient.Subscribe(context.Background(), channel)\n        h.redisSubs[channel] = pubsub\n        go h.forwardRedisMessages(channel, pubsub)\n    }\n\n    return nil\n}\n\nfunc (h *Hub) unsubscribeFromChannel(conn *Connection, channel string) {\n    if subs, ok := h.subscriptions[channel]; ok {\n        delete(subs, conn)\n\n        // Cleanup when no local subscribers\n        if len(subs) == 0 {\n            delete(h.subscriptions, channel)\n            h.closeRedisSubscription(channel)\n        }\n    }\n}"
      },
      {
        "title": "Redis Message Forwarding",
        "body": "func (h *Hub) forwardRedisMessages(channel string, pubsub *goredis.PubSub) {\n    ch := pubsub.Channel()\n    for {\n        select {\n        case <-h.done:\n            return\n        case msg, ok := <-ch:\n            if !ok {\n                return\n            }\n            h.broadcast <- &Event{\n                Channel: channel,\n                Data:    []byte(msg.Payload),\n            }\n        }\n    }\n}\n\nfunc (h *Hub) broadcastToChannel(event *Event) {\n    subs := h.subscriptions[event.Channel]\n    for conn := range subs {\n        select {\n        case conn.send <- event.Data:\n            // Sent\n        default:\n            // Buffer full - close slow client\n            h.removeConnection(conn)\n        }\n    }\n}"
      },
      {
        "title": "Connection Write Pump",
        "body": "func (c *Connection) writePump() {\n    ticker := time.NewTicker(54 * time.Second) // Ping interval\n    defer func() {\n        ticker.Stop()\n        c.conn.Close()\n    }()\n\n    for {\n        select {\n        case message, ok := <-c.send:\n            c.conn.SetWriteDeadline(time.Now().Add(10 * time.Second))\n            if !ok {\n                c.conn.WriteMessage(websocket.CloseMessage, []byte{})\n                return\n            }\n            c.conn.WriteMessage(websocket.TextMessage, message)\n\n            // Batch drain queue\n            for i := 0; i < len(c.send); i++ {\n                c.conn.WriteMessage(websocket.TextMessage, <-c.send)\n            }\n\n        case <-ticker.C:\n            if err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil {\n                return\n            }\n        }\n    }\n}"
      },
      {
        "title": "Connection Registry for Horizontal Scaling",
        "body": "type ConnectionRegistry struct {\n    client     *redis.Client\n    instanceID string\n}\n\nfunc (r *ConnectionRegistry) RegisterConnection(ctx context.Context, connID string, info ConnectionInfo) error {\n    info.InstanceID = r.instanceID\n    data, _ := json.Marshal(info)\n    return r.client.Set(ctx, \"ws:conn:\"+connID, data, 2*time.Minute).Err()\n}\n\nfunc (r *ConnectionRegistry) HeartbeatInstance(ctx context.Context, connectionCount int) error {\n    info := InstanceInfo{\n        InstanceID:  r.instanceID,\n        Connections: connectionCount,\n    }\n    data, _ := json.Marshal(info)\n    return r.client.Set(ctx, \"ws:instance:\"+r.instanceID, data, 30*time.Second).Err()\n}"
      },
      {
        "title": "Graceful Shutdown",
        "body": "func (h *Hub) Shutdown() {\n    close(h.done)\n\n    // Close all Redis subscriptions\n    h.redisSubLock.Lock()\n    for channel, pubsub := range h.redisSubs {\n        pubsub.Close()\n        delete(h.redisSubs, channel)\n    }\n    h.redisSubLock.Unlock()\n\n    // Close all connections\n    for conn := range h.connections {\n        conn.Close()\n    }\n\n    h.wg.Wait()\n}"
      },
      {
        "title": "Decision Tree",
        "body": "SituationApproachSingle instanceSkip ConnectionRegistryMulti-instanceEnable ConnectionRegistryNo subscribers to channelLazy unsubscribe from RedisSlow clientClose on buffer overflowNeed message historyUse Redis Streams + Pub/Sub"
      },
      {
        "title": "Related Skills",
        "body": "Meta-skill: ai/skills/meta/realtime-dashboard/ — Complete realtime dashboard guide\ndual-stream-architecture — Event publishing\nresilient-connections — Connection resilience"
      },
      {
        "title": "NEVER Do",
        "body": "NEVER block on conn.send — Use select with default to detect overflow\nNEVER skip graceful shutdown — Clients need close frames\nNEVER share pubsub across channels — Each channel needs own subscription\nNEVER forget instance heartbeat — Dead instances leave orphaned connections\nNEVER send without ping/pong — Load balancers close \"idle\" connections"
      }
    ],
    "body": "WebSocket Hub Patterns\n\nProduction patterns for horizontally-scalable WebSocket connections with Redis-backed coordination.\n\nInstallation\nOpenClaw / Moltbot / Clawbot\nnpx clawhub@latest install websocket-hub-patterns\n\nWhen to Use\nReal-time bidirectional communication\nChat applications, collaborative editing\nLive dashboards with client interactions\nNeed horizontal scaling across multiple gateway instances\nHub Structure\ntype Hub struct {\n    // Local state\n    connections   map[*Connection]bool\n    subscriptions map[string]map[*Connection]bool // channel -> connections\n\n    // Channels\n    register   chan *Connection\n    unregister chan *Connection\n    broadcast  chan *Event\n\n    // Redis for scaling\n    redisClient  *redis.Client\n    redisSubs    map[string]*goredis.PubSub\n    redisSubLock sync.Mutex\n\n    // Optional: Distributed registry\n    connRegistry *ConnectionRegistry\n    instanceID   string\n\n    // Shutdown\n    done chan struct{}\n    wg   sync.WaitGroup\n}\n\nHub Main Loop\nfunc (h *Hub) Run() {\n    for {\n        select {\n        case <-h.done:\n            return\n\n        case conn := <-h.register:\n            h.connections[conn] = true\n            if h.connRegistry != nil {\n                h.connRegistry.RegisterConnection(ctx, conn.ID(), info)\n            }\n\n        case conn := <-h.unregister:\n            if _, ok := h.connections[conn]; ok {\n                if h.connRegistry != nil {\n                    h.connRegistry.UnregisterConnection(ctx, conn.ID())\n                }\n                h.removeConnection(conn)\n            }\n\n        case event := <-h.broadcast:\n            h.broadcastToChannel(event)\n        }\n    }\n}\n\nLazy Redis Subscriptions\n\nSubscribe to Redis only when first local subscriber joins:\n\nfunc (h *Hub) subscribeToChannel(conn *Connection, channel string) error {\n    // Add to local subscriptions\n    if h.subscriptions[channel] == nil {\n        h.subscriptions[channel] = make(map[*Connection]bool)\n    }\n    h.subscriptions[channel][conn] = true\n\n    // Lazy: Only subscribe to Redis on first subscriber\n    h.redisSubLock.Lock()\n    defer h.redisSubLock.Unlock()\n\n    if _, exists := h.redisSubs[channel]; !exists {\n        pubsub := h.redisClient.Subscribe(context.Background(), channel)\n        h.redisSubs[channel] = pubsub\n        go h.forwardRedisMessages(channel, pubsub)\n    }\n\n    return nil\n}\n\nfunc (h *Hub) unsubscribeFromChannel(conn *Connection, channel string) {\n    if subs, ok := h.subscriptions[channel]; ok {\n        delete(subs, conn)\n\n        // Cleanup when no local subscribers\n        if len(subs) == 0 {\n            delete(h.subscriptions, channel)\n            h.closeRedisSubscription(channel)\n        }\n    }\n}\n\nRedis Message Forwarding\nfunc (h *Hub) forwardRedisMessages(channel string, pubsub *goredis.PubSub) {\n    ch := pubsub.Channel()\n    for {\n        select {\n        case <-h.done:\n            return\n        case msg, ok := <-ch:\n            if !ok {\n                return\n            }\n            h.broadcast <- &Event{\n                Channel: channel,\n                Data:    []byte(msg.Payload),\n            }\n        }\n    }\n}\n\nfunc (h *Hub) broadcastToChannel(event *Event) {\n    subs := h.subscriptions[event.Channel]\n    for conn := range subs {\n        select {\n        case conn.send <- event.Data:\n            // Sent\n        default:\n            // Buffer full - close slow client\n            h.removeConnection(conn)\n        }\n    }\n}\n\nConnection Write Pump\nfunc (c *Connection) writePump() {\n    ticker := time.NewTicker(54 * time.Second) // Ping interval\n    defer func() {\n        ticker.Stop()\n        c.conn.Close()\n    }()\n\n    for {\n        select {\n        case message, ok := <-c.send:\n            c.conn.SetWriteDeadline(time.Now().Add(10 * time.Second))\n            if !ok {\n                c.conn.WriteMessage(websocket.CloseMessage, []byte{})\n                return\n            }\n            c.conn.WriteMessage(websocket.TextMessage, message)\n\n            // Batch drain queue\n            for i := 0; i < len(c.send); i++ {\n                c.conn.WriteMessage(websocket.TextMessage, <-c.send)\n            }\n\n        case <-ticker.C:\n            if err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil {\n                return\n            }\n        }\n    }\n}\n\nConnection Registry for Horizontal Scaling\ntype ConnectionRegistry struct {\n    client     *redis.Client\n    instanceID string\n}\n\nfunc (r *ConnectionRegistry) RegisterConnection(ctx context.Context, connID string, info ConnectionInfo) error {\n    info.InstanceID = r.instanceID\n    data, _ := json.Marshal(info)\n    return r.client.Set(ctx, \"ws:conn:\"+connID, data, 2*time.Minute).Err()\n}\n\nfunc (r *ConnectionRegistry) HeartbeatInstance(ctx context.Context, connectionCount int) error {\n    info := InstanceInfo{\n        InstanceID:  r.instanceID,\n        Connections: connectionCount,\n    }\n    data, _ := json.Marshal(info)\n    return r.client.Set(ctx, \"ws:instance:\"+r.instanceID, data, 30*time.Second).Err()\n}\n\nGraceful Shutdown\nfunc (h *Hub) Shutdown() {\n    close(h.done)\n\n    // Close all Redis subscriptions\n    h.redisSubLock.Lock()\n    for channel, pubsub := range h.redisSubs {\n        pubsub.Close()\n        delete(h.redisSubs, channel)\n    }\n    h.redisSubLock.Unlock()\n\n    // Close all connections\n    for conn := range h.connections {\n        conn.Close()\n    }\n\n    h.wg.Wait()\n}\n\nDecision Tree\nSituation\tApproach\nSingle instance\tSkip ConnectionRegistry\nMulti-instance\tEnable ConnectionRegistry\nNo subscribers to channel\tLazy unsubscribe from Redis\nSlow client\tClose on buffer overflow\nNeed message history\tUse Redis Streams + Pub/Sub\nRelated Skills\nMeta-skill: ai/skills/meta/realtime-dashboard/ — Complete realtime dashboard guide\ndual-stream-architecture — Event publishing\nresilient-connections — Connection resilience\nNEVER Do\nNEVER block on conn.send — Use select with default to detect overflow\nNEVER skip graceful shutdown — Clients need close frames\nNEVER share pubsub across channels — Each channel needs own subscription\nNEVER forget instance heartbeat — Dead instances leave orphaned connections\nNEVER send without ping/pong — Load balancers close \"idle\" connections"
  },
  "trust": {
    "sourceLabel": "tencent",
    "provenanceUrl": "https://clawhub.ai/wpank/websocket-hub-patterns",
    "publisherUrl": "https://clawhub.ai/wpank/websocket-hub-patterns",
    "owner": "wpank",
    "version": "1.0.0",
    "license": null,
    "verificationStatus": "Indexed source record"
  },
  "links": {
    "detailUrl": "https://openagent3.xyz/skills/websocket-hub-patterns",
    "downloadUrl": "https://openagent3.xyz/downloads/websocket-hub-patterns",
    "agentUrl": "https://openagent3.xyz/skills/websocket-hub-patterns/agent",
    "manifestUrl": "https://openagent3.xyz/skills/websocket-hub-patterns/agent.json",
    "briefUrl": "https://openagent3.xyz/skills/websocket-hub-patterns/agent.md"
  }
}