Websocket realtime patterns

From FerroxLabs/wayland · View interactive version

Websocket realtime patterns is an AI agent skill from the GitHub repository FerroxLabs/wayland. Guides expert-level websocket and real-time patterns implementation: web-development and frameworks decision frameworks, production-ready patterns, and concrete templates for websocket realtime patterns workflows. Use when the user asks about websocket and real-time patterns, websocket realtime patt

How to use this skill

Skill file

WebSocket Realtime Patterns

When to Use

Use this skill when:

Do NOT use this skill when:

Process

Step 1: Classify the Real-Time Use Case and Select the Transport

Before writing any code, identify which real-time pattern best fits the requirement.

Transport decision matrix:

| Requirement | WebSocket | SSE | Long Polling |

|---|---|---|---|

| Bidirectional messaging | ✅ Native | ❌ No | ❌ Simulated |

| Server-to-client only | ✅ Overkill | ✅ Ideal | ✅ Acceptable |

| Browser support | ✅ Universal | ✅ Universal | ✅ Universal |

| Works through HTTP proxies | ⚠️ Needs config | ✅ Always | ✅ Always |

| Binary frames | ✅ Yes | ❌ Text only | ❌ Text only |

| Auto-reconnect built in | ❌ Manual | ✅ Built in | ❌ Manual |

| Connection overhead | High | Medium | Low |

| Messages per second | Very high | High | < 1/sec practical |

Choose WebSockets when: bidirectional messaging is required OR message rate exceeds 1 per second OR latency must be under 100ms consistently.

Step 2: Design the Message Protocol

Raw WebSockets transmit unstructured bytes. Define a protocol before implementing any handler logic.

Step 3: Implement Connection Lifecycle Management

Connection lifecycle is where most WebSocket bugs originate. Handle every state transition explicitly.

Step 4: Build the Room and Channel System

Most real applications need to segment connections into logical groups.

Step 5: Handle Backpressure and Flow Control

Unchecked message sending is the leading cause of WebSocket server crashes at scale.

Step 6: Implement Reliability and Message Ordering

WebSockets do NOT guarantee delivery or ordering when connections drop and reconnect.

Step 7: Harden for Production

Address the operational concerns that cause production WebSocket deployments to fail.


Output Format

When responding to WebSocket implementation questions, structure your output as follows:

## WebSocket Implementation Plan: [Feature Name]

### Transport Selection
- Chosen transport: [WebSocket / SSE / Long Polling]
- Rationale: [1-3 sentences based on the use case classification]
- Bidirectional required: [Yes/No]
- Expected message rate: [X messages/second/connection]

### Message Protocol

#### Envelope Schema

{

"type": "namespace.action",

"id": "uuid-v4",

"ts": 1717000000000,

"v": 1,

"payload": { }

}


#### Message Types
| Type | Direction | Payload | Ack Required |
|------|-----------|---------|--------------|
| [type] | S→C / C→S / Both | [fields] | Yes/No |

### Connection Lifecycle

**Server-side handler pseudocode:**

onUpgrade(req):

token = req.headers['authorization'] || req.query.token

user = verifyToken(token) -- reject 401 if invalid

connectionId = generateId()

registry.add(userId, connectionId, socket)

startHeartbeat(connectionId, interval=25s, timeout=10s)

send({ type: 'session.init', connectionId, seq: currentSeq })

onMessage(connectionId, rawData):

msg = parse(rawData) -- reject if > maxSize

rateLimiter.check(connectionId) -- reject if exceeded

router.dispatch(msg.type, connectionId, msg)

onClose(connectionId, code, reason):

registry.remove(connectionId)

rooms.leaveAll(connectionId)

presence.setOffline(userId)

pubsub.unsubscribeAll(connectionId)

heartbeat.cancel(connectionId)


### Room / Channel Architecture
- Room implementation: [in-memory Map / Redis adapter]
- Cross-instance fan-out: [Redis Pub/Sub channel names]
- Presence storage: [Redis sorted set / in-memory]

### Reliability Settings
- Sequence numbers: [Yes/No]
- Replay buffer: [N messages / TTL]
- Client retry policy: [backoff formula]
- Idempotency key TTL: [seconds]

### Scaling Configuration
- Max connections per instance: [N]
- Load balancer sticky sessions: [Yes/No, configuration notes]
- Heartbeat interval: [N seconds]
- Proxy read timeout: [N seconds]

### Key Metrics to Monitor
- [metric name]: [threshold and alert condition]

### Implementation Checklist
- [ ] Authentication at upgrade (not post-connect)
- [ ] Heartbeat with configurable interval and timeout
- [ ] Connection registry with userId → [connectionId] mapping
- [ ] Message size limit enforced
- [ ] Per-connection rate limiting
- [ ] Graceful shutdown handler
- [ ] Backpressure detection on send buffer
- [ ] Sequence numbers on server-to-client messages
- [ ] Reconnect replay endpoint / message buffer
- [ ] Metrics instrumentation

Rules

  1. NEVER authenticate after the WebSocket connection is open. Authentication must happen during the HTTP upgrade handshake. A post-connect auth message creates a window where unauthenticated messages can arrive and be processed before the auth completes.
  1. NEVER use a single global room or broadcast channel for all messages. Every unfiltered broadcast to all connections scales as O(connections) and will cause noticeable latency spikes once you exceed 1,000 concurrent users. Always segment connections into rooms or topics.
  1. ALWAYS set a maximum message size limit. Without it, a single client can send a 1 GB message and exhaust server memory. Enforce this limit before deserializing the payload -- reject at the byte-count level using the WebSocket frame headers.
  1. NEVER store WebSocket connection objects in a database. Connection objects are in-memory only and not serializable. Store connection metadata (connectionId, userId, roomIds, lastSeen) in Redis with a TTL, and use that metadata to route messages to the correct server instance.
  1. ALWAYS implement heartbeat/ping at the server level, not just the client level. Load balancers (AWS ALB, GCP Load Balancer) and corporate firewalls silently kill idle TCP connections after 60--300 seconds. Server-initiated pings every 25 seconds prevent this. Client-only keepalives fail silently when the client tab is backgrounded.
  1. NEVER let a reconnect storm cause a cascading failure. When a server instance restarts, all its clients reconnect simultaneously. Without jitter in the reconnect backoff, all clients hit the server at the same moment, saturating it before it can stabilize. The reconnect formula MUST include random jitter.
  1. ALWAYS drain the send buffer check before sending. Check socket.bufferedAmount (browser) or the equivalent server-side metric before sending each message. Queuing messages to a slow client unboundedly causes memory exhaustion on the server and client. Drop, throttle, or close -- but never queue without bound.
  1. NEVER assume WebSocket messages arrive in order after a reconnect. The sequence number and replay buffer pattern is mandatory for any feature that depends on ordering (collaborative editing, event sourcing, financial operations). Without it, reconnecting clients will silently see inconsistent state.
  1. ALWAYS handle the error event on the WebSocket in addition to close. In Node.js with the ws library, if you do not attach an error handler, an unhandled error event will crash the process. The error event fires before close in many network failure scenarios. Always log the error, then let the close handler do cleanup.
  1. NEVER ignore the difference between WebSocket close codes. Code 1000 (normal closure) and 1001 (going away) are clean -- the client should reconnect with normal backoff. Code 1008 (policy violation) and 1009 (message too large) indicate a client bug -- the client should NOT immediately reconnect but instead alert or log. Code 1011 (server error) is a server bug -- the client should reconnect with aggressive backoff and alert ops. Your client reconnect logic must branch on close code.

Edge Cases

1. WebSocket Behind a Corporate Proxy or Strict Firewall

Some enterprise networks block WebSocket upgrades entirely or intercept TLS in a way that breaks the 101 Switching Protocols response. Symptoms: connections fail immediately with HTTP 403, 407, or time out during handshake.

2. Horizontal Scaling Without Sticky Sessions

If your deployment platform cannot guarantee sticky sessions (some Kubernetes ingress configurations, serverless WebSocket implementations), every message route must go through the shared broker.

3. Client-Side Tab Visibility and Backgrounded Tabs

Browsers aggressively throttle JavaScript timers and network activity in backgrounded tabs (Chrome: 1-minute freeze after 5 minutes background, Safari: aggressive suspension). This causes:

4. Large-Scale Fan-Out (>10,000 Recipients per Event)

Broadcasting a single event to 10,000+ connections synchronously can take 200--500ms and block the event loop in Node.js, causing all other clients to experience latency spikes during large broadcasts.

5. Schema Evolution and Protocol Versioning

After launching, changing the message schema breaks existing clients until they update. Mobile app clients may never update.

6. Memory Leaks from Zombie Connections

In high-churn deployments (users frequently opening and closing browser tabs), zombie connections accumulate when cleanup code fails silently.

7. Collaborative Editing and Operational Transform Conflicts

When multiple clients edit shared state concurrently (documents, whiteboards, code), last-write-wins is almost always wrong.


Example

Input: "I'm building a live collaborative whiteboard app. Multiple users can draw on a shared canvas simultaneously. There will be rooms (one per whiteboard), each with up to 50 concurrent users. We're running Node.js with multiple instances behind an AWS ALB. I need real-time cursor tracking, drawing operations synced across all users, and the board state should persist so new joiners see the current state. What's the WebSocket architecture and code patterns should I use?"


Output:

WebSocket Implementation Plan: Live Collaborative Whiteboard

Transport Selection


Message Protocol

Envelope Schema
{
  "type": "draw.stroke" ,
  "id": "7f3a1b2c-4d5e-6f7a-8b9c-0d1e2f3a4b5c",
  "ts": 1717000000000,
  "v": 1,
  "payload": { }
}
Message Types

| Type | Direction | Payload | Ack Required |

|---|---|---|---|

| session.init | C→S | { boardId, token, lastSeq } | Yes |

| session.ready | S→C | { connectionId, seq, snapshot } | No |

| cursor.move | C→S | { x, y } | No |

| cursor.update | S→C | { userId, x, y, color } | No |

| draw.stroke | C→S | { points[], color, width, tool } | Yes |

| draw.op | S→C | { userId, seq, points[], color, width, tool } | No |

| draw.undo | C→S | { opId } | Yes |

| presence.join | S→C | { userId, displayName, color, cursor } | No |

| presence.leave | S→C | { userId } | No |

| ack | S→C | { id, status, seq? } | No |

| error.rate_limit | S→C | { retryAfter } | No |

| server.shutdown | S→C | { reconnectDelay } | No |

Size limits: cursor messages max 128 bytes, draw operations max 32 KB, reject anything larger.


Connection Lifecycle

Server-side handler (Node.js + ws library):

// ws-server.js

const WebSocket = require('ws');
const redis = require('./redis-client'); // ioredis instance
const { verifyToken } = require('./auth');
const { registry, rooms, heartbeat } = require('./connection-manager');

const wss = new WebSocket.Server({ noServer: true });
const MAX_MESSAGE_BYTES = 32 * 1024; // 32 KB
const HEARTBEAT_INTERVAL_MS = 25000;
const HEARTBEAT_TIMEOUT_MS = 10000;
const RATE_LIMIT_MAX = 100;
const RATE_LIMIT_WINDOW_MS = 10000;

// Called from HTTP server upgrade event
function handleUpgrade(req, socket, head) {
  const token = req.headers['authorization']?.replace('Bearer ', '')
               || new URL(req.url, 'ws://x').searchParams.get('token');

  const user = verifyToken(token);
  if (!user) {
    socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
    socket.destroy();
    return;
  }

  wss.handleUpgrade(req, socket, head, (ws) => {
    wss.emit('connection', ws, req, user);
  });
}

wss.on('connection', (ws, req, user) => {
  const connectionId = crypto.randomUUID();
  
  // Register connection
  registry.add(user.id, connectionId, ws);
  
  // Start heartbeat -- server-initiated to survive ALB idle timeout
  const pingTimer = setInterval(() => {
    if (ws.readyState !== WebSocket.OPEN) return;
    ws.ping();
    ws._pongDeadline = setTimeout(() => {
      ws.close(1001, 'heartbeat timeout');
    }, HEARTBEAT_TIMEOUT_MS);
  }, HEARTBEAT_INTERVAL_MS);

  ws.on('pong', () => {
    clearTimeout(ws._pongDeadline);
  });

  ws.on('message', (data, isBinary) => {
    // Enforce size limit before parsing
    if (data.length > MAX_MESSAGE_BYTES) {
      send(ws, { type: 'error.message_too_large', maxBytes: MAX_MESSAGE_BYTES });
      return;
    }

    // Rate limiting: sliding window per connection
    const now = Date.now();
    ws._msgTimestamps = (ws._msgTimestamps || []).filter(t => now - t < RATE_LIMIT_WINDOW_MS);
    if (ws._msgTimestamps.length >= RATE_LIMIT_MAX) {
      send(ws, { type: 'error.rate_limit', retryAfter: RATE_LIMIT_WINDOW_MS });
      return;
    }
    ws._msgTimestamps.push(now);

    let msg;
    try {
      msg = JSON.parse(data.toString());
    } catch (e) {
      send(ws, { type: 'error.parse_failure' });
      return;
    }

    router(ws, user, connectionId, msg);
  });

  ws.on('error', (err) => {
    console.error(`ws error [${connectionId}]:`, err.message);
    // 'close' will fire after 'error' -- cleanup happens there
  });

  ws.on('close', (code, reason) => {
    clearInterval(pingTimer);
    clearTimeout(ws._pongDeadline);
    cleanup(user.id, connectionId);
  });
});

async function cleanup(userId, connectionId) {
  try {
    const boardId = registry.getBoardId(connectionId);
    registry.remove(connectionId);
    if (boardId) {
      rooms.leave(boardId, connectionId);
      await redis.publish(`board:${boardId}`, JSON.stringify({
        type: 'presence.leave',
        payload: { userId }
      }));
      await redis.zrem('presence:' + boardId, userId);
    }
  } catch (err) {
    console.error(`cleanup error [${connectionId}]:`, err);
  }
}

function send(ws, msg) {
  if (ws.readyState !== WebSocket.OPEN) return;
  // Backpressure check
  if (ws.bufferedAmount > 1024 * 1024) { // 1 MB threshold
    if (msg.type === 'cursor.update') return; // Drop low-priority, never drop critical
    console.warn('send buffer full, dropping:', msg.type);
    return;
  }
  ws.send(JSON.stringify(msg));
}

Room and Channel Architecture

Multi-instance fan-out using Redis Pub/Sub:

// board-room.js -- Redis adapter for cross-instance broadcast

const redis = require('./redis-client');
const subscriber = redis.duplicate(); // separate connection for subscriptions

// Each instance subscribes to board channels for boards it has active connections
async function joinBoard(boardId, connectionId, ws, userId, lastSeq) {
  const channelKey = `board:${boardId}`;
  
  // Subscribe this instance to the board channel if not already subscribed
  if (!activeSubscriptions.has(boardId)) {
    await subscriber.subscribe(channelKey);
    activeSubscriptions.add(boardId);
  }
  
  rooms.join(boardId, connectionId);
  
  // Load snapshot + replay missed messages
  const [snapshot, missedOps] = await Promise.all([
    redis.get(`board:${boardId}:snapshot`),
    replayFrom(boardId, lastSeq)
  ]);
  
  // Send current state to the joining client
  send(ws, {
    type: 'session.ready',
    connectionId,
    seq: await getCurrentSeq(boardId),
    snapshot: snapshot ? JSON.parse(snapshot) : null,
    missedOps
  });
  
  // Announce presence to room
  const presentUsers = await redis.zrange(`presence:${boardId}`, 0, -1);
  await redis.zadd(`presence:${boardId}`, Date.now(), userId);
  await redis.publish(channelKey, JSON.stringify({
    type: 'presence.join',
    payload: { userId, displayName: user.displayName, color: user.color }
  }));
}

// When Redis delivers a message, fan out to all local connections in the room
subscriber.on('message', (channel, data) => {
  const boardId = channel.replace('board:', '');
  const msg = JSON.parse(data);
  const connections = rooms.getConnections(boardId);
  
  for (const connectionId of connections) {
    const ws = registry.getSocket(connectionId);
    if (ws) send(ws, msg);
  }
});

Redis data model:

board:{boardId}:snapshot        STRING  -- JSON, current board state (updated every 50 ops)
board:{boardId}:seq             STRING  -- INCR counter, current sequence number
board:{boardId}:ops             LIST    -- RPUSH, last 500 operations (LTRIM to 500)
presence:{boardId}              ZSET    -- member=userId, score=lastSeenTimestamp
session:{connectionId}:meta     HASH    -- userId, boardId, lastSeq (TTL: 1 hour)
idempotency:{msgId}             STRING  -- "1", TTL 5 minutes

Drawing Operation Handler with Sequence Numbers

// router.js

async function handleDrawStroke(ws, user, connectionId, msg) {
  const { boardId } = registry.getMeta(connectionId);
  
  // Idempotency check
  const dedupKey = `idempotency:${msg.id}`;
  const isDuplicate = await redis.set(dedupKey, '1', 'EX', 300, 'NX') === null;
  if (isDuplicate) {
    // Resend original ack, do not reprocess
    send(ws, { type: 'ack', id: msg.id, status: 'ok' });
    return;
  }
  
  // Assign server-side sequence number
  const seq = await redis.incr(`board:${boardId}:seq`);
  
  const op = {
    type: 'draw.op',
    id: msg.id,
    seq,
    ts: Date.now(),
    payload: {
      userId: user.id,
      ...msg.payload // points, color, width, tool
    }
  };
  
  // Persist to replay buffer
  const opJson = JSON.stringify(op);
  await redis.pipeline()
    .rpush(`board:${boardId}:ops`, opJson)
    .ltrim(`board:${boardId}:ops`, -500, -1) // keep last 500
    .exec();
  
  // Snapshot every 50 operations
  if (seq % 50 === 0) {
    await updateSnapshot(boardId);
  }
  
  // Fan out to all room members via Redis
  await redis.publish(`board:${boardId}`, opJson);
  
  // Ack to originating client
  send(ws, { type: 'ack', id: msg.id, status: 'ok', seq });
}

// Cursor moves: no ack, no persistence, high frequency
async function handleCursorMove(ws, user, connectionId, msg) {
  const { boardId } = registry.getMeta(connectionId);
  await redis.publish(`board:${boardId}`, JSON.stringify({
    type: 'cursor.update',
    payload: { userId: user.id, x: msg.payload.x, y: msg.payload.y }
  }));
}

Client Reconnect Logic

// client/ws-client.js

class WhiteboardSocket {
  constructor(boardId, token) {
    this.boardId = boardId;
    this.token = token;
    this.lastSeq = parseInt(sessionStorage.getItem(`board:${boardId}:seq`) || '0');
    this.attempt = 0;
    this.connect();
  }
  
  connect() {
    this.ws = new WebSocket(`wss://api.example.com/ws?token=${this.token}`);
    
    this.ws.onopen = () => {
      this.attempt = 0;
      this.ws.send(JSON.stringify({
        type: 'session.init',
        id: crypto.randomUUID(),
        ts: Date.now(),
        v: 1,
        payload: { boardId: this.boardId, lastSeq: this.lastSeq }
      }));
    };
    
    this.ws.onmessage = (event) => {
      const msg = JSON.parse(event.data);
      if (msg.seq) {
        this.lastSeq = msg.seq;
        sessionStorage.setItem(`board:${this.boardId}:seq`, msg.seq);
      }
      this.onMessage(msg);
    };
    
    this.ws.onclose = (event) => {
      // Do not reconnect on policy violations -- indicates a client bug
      if (event.code === 1008 || event.code === 1009) {
        console.error('WebSocket closed due to policy violation -- not reconnecting', event.code);
        this.onFatalError(event.code);
        return;
      }
      this.scheduleReconnect();
    };
    
    this.ws.onerror = (err) => {
      console.error('WebSocket error:', err);
      // onclose fires next -- reconnect logic is there
    };
    
    // Handle backgrounded tab
    document.addEventListener('visibilitychange', () => {
      if (document.visibilityState === 'visible' && this.ws.readyState !== WebSocket.OPEN) {
        this.connect();
      }
    });
  }
  
  scheduleReconnect() {
    const delay = Math.min(1000 * Math.pow(1.5, this.attempt), 30000);
    const jitter = delay * (0.8 + 0.4 * Math.random());
    this.attempt++;
    setTimeout(() => this.connect(), jitter);
  }
}

Scaling Configuration

| Parameter | Value | Rationale |

|---|---|---|

| Max connections per instance | 15,000 | ~200 KB/conn with Yjs doc state; 3 GB reserved for connections on 4 GB instance |

| Heartbeat interval | 25 seconds | AWS ALB idle timeout is 60 seconds; this provides 2x margin |

| Pong timeout | 10 seconds | Total dead detection: 35 seconds |

| Proxy read timeout (nginx) | 3,600 seconds | 1-hour max session without requiring reconnect |

| Replay buffer | 500 ops per board | Covers ~60 seconds of heavy drawing at max rate |

| Snapshot frequency | Every 50 ops | Caps replay time on join to < 50 ops at all times |

| Idempotency key TTL | 300 seconds | Covers any realistic retransmit window |

| Rate limit | 100 messages / 10 seconds | ~10 msg/sec sustained; burst allows fast strokes |


Key Metrics to Monitor


Implementation Checklist

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.