17 Maret 20269 min read

Building Low-Latency Realtime Collaborative Experiences with WebSockets

Implementing multi-user presence, state synchronization with CRDTs, binary message packing, and audio streaming over WebRTC data channels.

WebSocketsWebRTCRealtimeNode.jsSystem Design

From multiplayer code editors to live AI interview simulations, modern web apps require bidirectional, sub-50ms latency channels between clients and servers.


WebSocket vs WebRTC Data Channels

  • WebSockets: Ideal for server-brokered state updates, chat messages, and presence indicators.
  • WebRTC Data Channels: Peer-to-peer transport over UDP, minimizing overhead for streaming voice, video, and gaming telemetry.

Resilient WebSocket Client in TypeScript

export class ResilientWebSocket {
  private ws: WebSocket | null = null;
  private reconnectAttempts = 0;
  private maxAttempts = 5;

  constructor(private url: string, private onMessage: (data: unknown) => void) {
    this.connect();
  }

  private connect() {
    this.ws = new WebSocket(this.url);

    this.ws.onmessage = (event) => {
      const data = JSON.parse(event.data);
      this.onMessage(data);
    };

    this.ws.onclose = () => {
      if (this.reconnectAttempts < this.maxAttempts) {
        const timeout = Math.min(1000 * Math.pow(2, this.reconnectAttempts), 10000);
        setTimeout(() => {
          this.reconnectAttempts++;
          this.connect();
        }, timeout);
      }
    };
  }

  public send(payload: object) {
    if (this.ws?.readyState === WebSocket.OPEN) {
      this.ws.send(JSON.stringify(payload));
    }
  }
}

Handling reconnection with exponential backoff ensures an uninterrupted user experience even on unstable mobile networks.

Bagikan

Artikel lainnya