,

Contents · WebSockets, SSE, WebRTC


Realtime transport choices on the web

  • Polling/long-polling → SSE → WebSockets → WebRTC data/media channels.
  • Trade-offs: duplex vs simplex, browser support, intermediaries, latency.
  • HTTP/2 and HTTP/3 add alternatives (server push deprecated; bidirectional streams via gRPC-web over H/2 limited).

WebSockets: full-duplex over a single TCP connection

  • Upgrade from HTTP using a handshake with Sec-WebSocket-Key/Accept.
  • Frames: text/binary, masking from client, ping/pong for keepalive.
  • Good for chat, multiplayer state, dashboards; load balance with sticky sessions.
// Browser
const ws = new WebSocket('wss://example.com/socket');
ws.onmessage = e => console.log(e.data);
ws.send(JSON.stringify({ type: 'ping' }));

Server-Sent Events: unidirectional streams

  • Simple, text/event-stream over HTTP; reconnect semantics built-in.
  • Great for notifications, feeds, logs; not for high-frequency duplex messaging.
  • Works through many proxies/CDNs; backpressure handled via HTTP.
// Browser
const es = new EventSource('/events');
es.onmessage = e => console.log('event', e.data);

WebRTC: media + data channels (P2P)

  • Peer-to-peer audio/video with SRTP; DTLS-SRTP for keying; SFU/MCU topologies.
  • DataChannel over SCTP/DTLS; reliable or partial-reliability modes.
  • Great for conferencing, low-latency gaming, file transfer; needs signaling infra.
// Data channel setup
const pc = new RTCPeerConnection();
const dc = pc.createDataChannel('chat');
dc.onmessage = e => console.log(e.data);
// exchange SDP via your signaling server

Signaling, STUN/TURN/ICE

  • ICE gathers candidates; STUN discovers public reflexive addresses.
  • TURN relays when direct connectivity fails; required for strict NATs/firewalls.
  • Signaling is app-defined (WebSocket/HTTP); exchange SDP offers/answers and ICE candidates.

Security, CORS, and auth

  • Always use TLS (wss://); authenticate during upgrade/signaling.
  • Protect against cross-tenant leakage; validate origins; rate-limit.
  • Handle key rotation and token expiry; prefer short-lived credentials.

Architecture patterns and when to use what

  • Notifications/feeds → SSE; interactive messaging → WebSockets; media/P2P → WebRTC.
  • At scale: shard by tenant/user; use message queues; backpressure clients.
  • Support graceful reconnects and idempotent semantics on resume.

Operational considerations

  • Load balancers: L4 vs L7, sticky sessions, WebSocket proxying, idle timeouts.
  • Metrics: connection count, reconnects, message latency, buffer sizes.
  • Test with network emulation (loss/latency/jitter) and chaos scenarios.

Exercises

  1. Build a chat prototype with WebSockets; add heartbeats and reconnect logic.
  2. Stream server events to a dashboard with SSE; implement last-event-id resume.
  3. Create a WebRTC data-channel demo that transfers a large file with partial reliability.
Choose the right real-time primitive for your use-case—optimize for simplicity, reliability, and observability.