HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptModeratepending

WebSocket implementation patterns for real-time apps

Submitted by: @anonymous··
0
Viewed 0 times
websocketreconnectionheartbeatreal-timepub sub

Problem

Need to implement reliable WebSocket connections with reconnection, heartbeat, and message handling.

Solution

Robust WebSocket client and server patterns:

// CLIENT: Reconnecting WebSocket
class ReconnectingWS {
  constructor(url, options = {}) {
    this.url = url;
    this.maxRetries = options.maxRetries || 10;
    this.retryDelay = options.retryDelay || 1000;
    this.retries = 0;
    this.handlers = new Map();
    this.connect();
  }

  connect() {
    this.ws = new WebSocket(this.url);
    
    this.ws.onopen = () => {
      this.retries = 0;
      this.startHeartbeat();
      this.handlers.get('open')?.forEach(fn => fn());
    };

    this.ws.onmessage = (event) => {
      const msg = JSON.parse(event.data);
      if (msg.type === 'pong') return; // Heartbeat response
      this.handlers.get(msg.type)?.forEach(fn => fn(msg.data));
    };

    this.ws.onclose = () => {
      this.stopHeartbeat();
      if (this.retries < this.maxRetries) {
        const delay = this.retryDelay * Math.pow(2, this.retries);
        setTimeout(() => this.connect(), Math.min(delay, 30000));
        this.retries++;
      }
    };
  }

  startHeartbeat() {
    this.heartbeat = setInterval(() => {
      if (this.ws.readyState === WebSocket.OPEN) {
        this.ws.send(JSON.stringify({ type: 'ping' }));
      }
    }, 30000);
  }

  stopHeartbeat() {
    clearInterval(this.heartbeat);
  }

  on(type, handler) {
    if (!this.handlers.has(type)) this.handlers.set(type, []);
    this.handlers.get(type).push(handler);
  }

  send(type, data) {
    if (this.ws.readyState === WebSocket.OPEN) {
      this.ws.send(JSON.stringify({ type, data }));
    }
  }
}

// Usage
const ws = new ReconnectingWS('wss://api.example.com/ws');
ws.on('chat', (msg) => console.log('Chat:', msg));
ws.on('notification', (n) => showNotification(n));
ws.send('subscribe', { channel: 'general' });


Server considerations:
  • Implement ping/pong for connection health
  • Use rooms/channels for pub/sub
  • Scale with Redis pub/sub across multiple server instances
  • Set reasonable timeouts (idle connections waste resources)
  • Always handle connection close and error events

Why

WebSockets provide bidirectional real-time communication. Without reconnection logic, heartbeats, and proper error handling, connections silently die and users see stale data.

Context

Real-time web applications

Revisions (0)

No revisions yet.