This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: websocket-redis-pubsub-cluster

WebSocket Cluster Scalability & Redis Pub/Sub Backpressure Architecture

Production real-time architecture for horizontally scaled WebSocket clusters. Mandates Redis Pub/Sub or Streams for cross-node message routing, heartbeat ping-pong socket pruning, exponential reconnection backoff with jitter, and buffer backpressure limits.

Prohibited Anti-Pattern: AI stores active WebSockets in local process memory Maps, dropping messages across multi-instance server deployments.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: WebSocket Cluster Scalability & Redis Pub/Sub Backpressure Architecture - Production real-time architecture for horizontally scaled WebSocket clusters. Mandates Redis Pub/Sub or Streams for cross-node message routing, heartbeat ping-pong socket pruning, exponential reconnection backoff with jitter, and buffer backpressure limits.
globs: **/*ws*.ts, **/*websocket*.ts, **/*socket*.py
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/websocket-redis-pubsub-cluster"
---

# WebSocket Cluster Scalability & Redis Pub/Sub Backpressure Architecture

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: AI stores active WebSockets in local process memory Maps, dropping messages across multi-instance server deployments.

## System Constraints
You are a real-time communications and distributed networking specialist. Never broadcast WebSocket messages solely using local in-memory Maps when building scalable services. Always use a distributed message bus (e.g., Redis Pub/Sub, Redis Streams) to fan out events across cluster nodes, enforce ping/pong heartbeats to reap dead sockets, and check ws.bufferedAmount for backpressure.

## Strict Guidelines
- Publish real-time events to Redis Pub/Sub channels (or Redis Streams) so all server nodes receive and forward messages to their local connected clients.
- Implement periodic ping/pong heartbeats (every 30s) and terminate unresponsive sockets that fail to return pong frames.
- Inspect ws.bufferedAmount before transmitting large payloads; pause or drop slow clients to prevent server memory bloat.
- Client reconnections must incorporate exponential backoff with full jitter to eliminate thundering herd storms on server restarts.

## Bad vs Good Implementations
### Distributed Multi-Node Pub/Sub Broadcast vs Single-Instance In-Memory Map

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: In Kubernetes or multi-instance clouds, events dispatched by node A are invisible to users connected to nodes B and C.
```typescript
// ANTI-PATTERN: Broadcasting only to local connections in a multi-container deployment
const localClients = new Set<WebSocket>();
function broadcastNotification(message: string) {
  // Users on other container instances will NEVER receive this event!
  for (const client of localClients) client.send(message);
}
```

#### Production Standard (Correct)
> **Standard**: Guarantees reliable message delivery regardless of which pod or region the user's socket is connected to.
```typescript
// PRODUCTION STANDARD: Redis Pub/Sub Cross-Cluster WebSocket Fanout
import { WebSocketServer, WebSocket } from "ws";
import Redis from "ioredis";

const pub = new Redis(process.env.REDIS_URL!);
const sub = new Redis(process.env.REDIS_URL!);
const localSockets = new Map<string, WebSocket>();

sub.subscribe("ws:events:broadcast");
sub.on("message", (channel, messageStr) => {
  const payload = JSON.parse(messageStr);
  const ws = localSockets.get(payload.targetUserId);
  if (ws && ws.readyState === WebSocket.OPEN && ws.bufferedAmount < 65536) {
    ws.send(JSON.stringify(payload.data));
  }
});

export async function emitUserEvent(targetUserId: string, data: unknown) {
  await pub.publish("ws:events:broadcast", JSON.stringify({ targetUserId, data }));
}
```

### Heartbeat Ping-Pong Dead Socket Reaper

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Silently abandoned half-open connections leak server memory and socket descriptors indefinitely.
```typescript
// ANTI-PATTERN: Relying on TCP FIN packets to detect disconnections
wss.on("connection", (ws) => {
  ws.on("close", () => console.log("closed")); // Never fires when wifi drops abruptly!
});
```

#### Production Standard (Correct)
> **Standard**: Actively prunes ghost connections within 30 seconds, maintaining accurate connected client counts and freeing server memory.
```typescript
// PRODUCTION STANDARD: Active heartbeat sweep every 30 seconds
const interval = setInterval(() => {
  wss.clients.forEach((ws: any) => {
    if (ws.isAlive === false) {
      localSockets.delete(ws.userId);
      return ws.terminate();
    }
    ws.isAlive = false;
    ws.ping();
  });
}, 30000);
wss.on("connection", (ws: any) => {
  ws.isAlive = true;
  ws.on("pong", () => { ws.isAlive = true; });
});
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: WebSocket Cluster Scalability & Redis Pub/Sub Backpressure Architecture

WebSocket Cluster Scalability & Redis Pub/Sub Backpressure Architecture defines an industrial-grade behavioral standard for backend engineering. Production real-time architecture for horizontally scaled WebSocket clusters. Mandates Redis Pub/Sub or Streams for cross-node message routing, heartbeat ping-pong socket pruning, exponential reconnection backoff with jitter, and buffer backpressure limits. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: AI stores active WebSockets in local process memory Maps, dropping messages across multi-instance server deployments. Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftAI stores active WebSockets in local process memory Maps, dropping messages across multi-instance server deployments.Critical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Publish real-time events to Redis Pub/Sub channels (or Redis Streams) so all server nodes receive and forward messages to their local connected clients.

Publish real-time events to Redis Pub/Sub channels (or Redis Streams) so all server nodes receive and forward messages to their local connected clients.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Implement periodic ping/pong heartbeats (every 30s) and terminate unresponsive sockets that fail to return pong frames.

Implement periodic ping/pong heartbeats (every 30s) and terminate unresponsive sockets that fail to return pong frames.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Inspect ws.bufferedAmount before transmitting large payloads

Inspect ws.bufferedAmount before transmitting large payloads; pause or drop slow clients to prevent server memory bloat.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Client reconnections must incorporate exponential backoff with full jitter to eliminate thundering herd storms on server restarts.

Client reconnections must incorporate exponential backoff with full jitter to eliminate thundering herd storms on server restarts.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is WebSocket Cluster Scalability & Redis Pub/Sub Backpressure Architecture critical for AI coding assistants?

Production real-time architecture for horizontally scaled WebSocket clusters. Mandates Redis Pub/Sub or Streams for cross-node message routing, heartbeat ping-pong socket pruning, exponential reconnection backoff with jitter, and buffer backpressure limits. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (AI stores active WebSockets in local process memory Maps, dropping messages across multi-instance server deployments.) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

1 Rule in Stack

WebSocket