简介
基于 Redis 的生产级 WebSocket 水平扩展架构方案,提供惰性订阅、连接注册与优雅关闭机制,助力构建高并发实时通信系统。
原始描述
Horizontally-scalable WebSocket hub pattern with lazy Redis subscriptions, connection registry, and graceful shutdown. Use when building real-time WebSocket servers that scale across multiple instances. Triggers on WebSocket hub, WebSocket scaling, connection registry, Redis WebSocket, real-time gateway, horizontal scaling.
通过你的 Agent 添加
点「快速安装」复制一段指令,粘给你正在用的 Agent(Claude Code、Codex、OpenClaw 等),它会自己完成安装。
或者手动安装
包里是 SKILL.md 加作者附带的文件,解压后目录名就是技能名。
技能申请的权限由作者决定,装之前请确认它能读什么、能执行什么。
中文使用说明 来自收录源
WebSocket Hub Patterns:水平扩展的实时通信架构指南
核心用法
websocket-hub-patterns 是一套面向生产环境的 WebSocket Hub 参考架构模式。它采用 Go 语言编写,核心围绕 Hub 结构体展开,通过本地连接映射和 Redis 发布/订阅实现跨实例的消息广播。其关键特性包括:惰性 Redis 订阅(仅在首个本地客户端订阅频道时才建立 Redis 连接,无订阅者时自动取消),连接注册表(将连接信息存储至 Redis,实现多实例间的连接可见性),以及优雅关闭机制(先关闭 Redis 订阅,再关闭所有客户端连接)。该 Skill 以纯文档形式提供,包含完整的代码片段,适用于需要水平扩展的实时聊天、协作编辑、实时仪表盘等场景。
显著优点
- 生产级架构设计:包含了连接超时处理、慢客户端自动剔除、写泵批量排空、心跳检测(Ping/Pong)等生产环境必需的细节,并非简单的玩具示例。
- 水平扩展友好:通过 Redis Pub/Sub 和连接注册表,天然支持多网关实例部署,解决了单机 WebSocket 的扩展瓶颈。
- 资源高效:惰性订阅模式避免了为无本地订阅者的频道维持 Redis 连接,显著降低 Redis 连接数和内存占用。
- 安全可靠:经过 CLS-Certify 六维自动扫描,0 个危险函数、0 个密钥泄露、0 个依赖风险、0 个可疑网络请求,安全评级为 A 级(92 分)。
- 纯文档无依赖:作为参考模式而非可执行包,零依赖,无供应链攻击面,可直接将代码逻辑融入自身项目。
潜在缺点或局限性
- 非开箱即用:这是一份架构参考文档,开发者需要理解代码逻辑并适配到自己的项目中,不具备直接安装运行的能力。
- 缺乏持久化:仅提供 Pub/Sub 实时推送机制,未内置消息持久化或历史消息回放功能(文档虽提及可使用 Redis Streams,但未提供完整实现)。
- 连接注册表简单化:提供的连接注册表实现较为基础,未包含心跳失败清理、连接状态机等复杂逻辑,生产部署时可能需额外补充。
- T3 来源限制:维护者 wpank 为个人开发者,仓库属于个人项目,信任等级评为 T3,评级自动上限为 A 级(无法达到 S+ 或 S 级)。尽管内容本身无安全缺陷,但来源权威性低于组织级维护的项目。
适合的目标群体
- 后端/基础设施工程师:需要为自己的实时应用(如聊天系统、协作工具)构建可扩展 WebSocket 网关的 Go 开发者。
- 架构师和技术负责人:希望参考经过验证的 WebSocket 水平扩展模式来设计系统架构。
- 学习生产级 Go 并发的开发者:代码中大量运用 goroutine、channel、select、sync.Mutex 等并发原语,是学习 Go 并发编程的优质范例。
使用该技能可能存在的常规风险
- 语言绑定风险:该 Skill 完全基于 Go 语言和 Go Redis 客户端(goredis),若团队使用其他语言(如 Node.js、Python)构建 WebSocket 网关,需要自行翻译代码逻辑。
- Redis 版本兼容性:代码依赖 Redis 的 Pub/Sub 特性,若使用 Redis Cluster 或特定云服务商的受限版本,需确认 Pub/Sub 的跨节点传播行为是否符合预期。
- 资源泄露风险:文档中的优雅关闭逻辑需开发者完整实现,若忽略实例心跳或 Redis 订阅清理,在多实例环境下可能产生僵尸连接或订阅泄露。
- 运维复杂度:引入 Redis 作为协调层后,部署和运维需额外管理 Redis 集群的可用性和延迟,增加系统复杂度。
技能正文
name: websocket-hub-patterns model: standard description: Horizontally-scalable WebSocket hub pattern with lazy Redis subscriptions, connection registry, and graceful shutdown. Use when building real-time WebSocket servers that scale across multiple instances. Triggers on WebSocket hub, WebSocket scaling, connection registry, Redis WebSocket, real-time gateway, horizontal scaling.
WebSocket Hub Patterns
Production patterns for horizontally-scalable WebSocket connections with Redis-backed coordination.
Installation
OpenClaw / Moltbot / Clawbot
npx clawhub@latest install websocket-hub-patterns
When to Use
- Real-time bidirectional communication
- Chat applications, collaborative editing
- Live dashboards with client interactions
- Need horizontal scaling across multiple gateway instances
Hub Structure
type Hub struct {
// Local state
connections map[*Connection]bool
subscriptions map[string]map[*Connection]bool // channel -> connections
// Channels
register chan *Connection
unregister chan *Connection
broadcast chan *Event
// Redis for scaling
redisClient *redis.Client
redisSubs map[string]*goredis.PubSub
redisSubLock sync.Mutex
// Optional: Distributed registry
connRegistry *ConnectionRegistry
instanceID string
// Shutdown
done chan struct{}
wg sync.WaitGroup
}
Hub Main Loop
func (h *Hub) Run() {
for {
select {
case <-h.done:
return
case conn := <-h.register:
h.connections[conn] = true
if h.connRegistry != nil {
h.connRegistry.RegisterConnection(ctx, conn.ID(), info)
}
case conn := <-h.unregister:
if _, ok := h.connections[conn]; ok {
if h.connRegistry != nil {
h.connRegistry.UnregisterConnection(ctx, conn.ID())
}
h.removeConnection(conn)
}
case event := <-h.broadcast:
h.broadcastToChannel(event)
}
}
}
Lazy Redis Subscriptions
Subscribe to Redis only when first local subscriber joins:
func (h *Hub) subscribeToChannel(conn *Connection, channel string) error {
// Add to local subscriptions
if h.subscriptions[channel] == nil {
h.subscriptions[channel] = make(map[*Connection]bool)
}
h.subscriptions[channel][conn] = true
// Lazy: Only subscribe to Redis on first subscriber
h.redisSubLock.Lock()
defer h.redisSubLock.Unlock()
if _, exists := h.redisSubs[channel]; !exists {
pubsub := h.redisClient.Subscribe(context.Background(), channel)
h.redisSubs[channel] = pubsub
go h.forwardRedisMessages(channel, pubsub)
}
return nil
}
func (h *Hub) unsubscribeFromChannel(conn *Connection, channel string) {
if subs, ok := h.subscriptions[channel]; ok {
delete(subs, conn)
// Cleanup when no local subscribers
if len(subs) == 0 {
delete(h.subscriptions, channel)
h.closeRedisSubscription(channel)
}
}
}
Redis Message Forwarding
func (h *Hub) forwardRedisMessages(channel string, pubsub *goredis.PubSub) {
ch := pubsub.Channel()
for {
select {
case <-h.done:
return
case msg, ok := <-ch:
if !ok {
return
}
h.broadcast <- &Event{
Channel: channel,
Data: []byte(msg.Payload),
}
}
}
}
func (h *Hub) broadcastToChannel(event *Event) {
subs := h.subscriptions[event.Channel]
for conn := range subs {
select {
case conn.send <- event.Data:
// Sent
default:
// Buffer full - close slow client
h.removeConnection(conn)
}
}
}
Connection Write Pump
func (c *Connection) writePump() {
ticker := time.NewTicker(54 * time.Second) // Ping interval
defer func() {
ticker.Stop()
c.conn.Close()
}()
for {
select {
case message, ok := <-c.send:
c.conn.SetWriteDeadline(time.Now().Add(10 * time.Second))
if !ok {
c.conn.WriteMessage(websocket.CloseMessage, []byte{})
return
}
c.conn.WriteMessage(websocket.TextMessage, message)
// Batch drain queue
for i := 0; i < len(c.send); i++ {
c.conn.WriteMessage(websocket.TextMessage, <-c.send)
}
case <-ticker.C:
if err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil {
return
}
}
}
}
Connection Registry for Horizontal Scaling
type ConnectionRegistry struct {
client *redis.Client
instanceID string
}
func (r *ConnectionRegistry) RegisterConnection(ctx context.Context, connID string, info ConnectionInfo) error {
info.InstanceID = r.instanceID
data, _ := json.Marshal(info)
return r.client.Set(ctx, "ws:conn:"+connID, data, 2*time.Minute).Err()
}
func (r *ConnectionRegistry) HeartbeatInstance(ctx context.Context, connectionCount int) error {
info := InstanceInfo{
InstanceID: r.instanceID,
Connections: connectionCount,
}
data, _ := json.Marshal(info)
return r.client.Set(ctx, "ws:instance:"+r.instanceID, data, 30*time.Second).Err()
}
Graceful Shutdown
func (h *Hub) Shutdown() {
close(h.done)
// Close all Redis subscriptions
h.redisSubLock.Lock()
for channel, pubsub := range h.redisSubs {
pubsub.Close()
delete(h.redisSubs, channel)
}
h.redisSubLock.Unlock()
// Close all connections
for conn := range h.connections {
conn.Close()
}
h.wg.Wait()
}
Decision Tree
| Situation | Approach |
|---|---|
| Single instance | Skip ConnectionRegistry |
| Multi-instance | Enable ConnectionRegistry |
| No subscribers to channel | Lazy unsubscribe from Redis |
| Slow client | Close on buffer overflow |
| Need message history | Use Redis Streams + Pub/Sub |
Related Skills
- Meta-skill: ai/skills/meta/realtime-dashboard/ — Complete realtime dashboard guide
- dual-stream-architecture — Event publishing
- resilient-connections — Connection resilience
NEVER Do
- NEVER block on conn.send — Use select with default to detect overflow
- NEVER skip graceful shutdown — Clients need close frames
- NEVER share pubsub across channels — Each channel needs own subscription
- NEVER forget instance heartbeat — Dead instances leave orphaned connections
- NEVER send without ping/pong — Load balancers close "idle" connections
正文来自原始发布页, 版权归作者所有,许可未标注。 权利人认为有不妥,可申请下架。