Real-Time Communication: WebSockets and SSE

Push live updates to the browser with WebSockets or Server-Sent Events, handling reconnection, state and scaling concerns.

Intermediate · about 4 hours · difficulty 3/5

Learn first: Server State with TanStack Query, Effects and Synchronisation

Chat, notifications, live dashboards, collaborative editing and multiplayer games need the server to push data without the client repeatedly asking. The browser offers several options.

The options

  • Polling: fetch every few seconds. Simple and fine for low-frequency updates, wasteful for high frequency.
  • Server-Sent Events (SSE): new EventSource("/events") opens a long-lived HTTP response that streams text events from server to client. One direction only, automatic reconnection built in, works through most proxies. Ideal for notifications, feeds and streaming AI responses.
  • WebSockets: new WebSocket("wss://...") gives a full-duplex, low-latency channel for messages in both directions. Ideal for chat, games and collaboration.
  • WebRTC: peer-to-peer audio, video and data. Optional and specialised.
  • WebTransport: a newer HTTP/3-based option; niche for now.

Doing it well

  • Reconnect with exponential backoff and jitter; WebSockets do not reconnect on their own.
  • On reconnect, resync missed data (send the last event id or refetch).
  • Send heartbeats to detect dead connections.
  • Define a message format (type plus payload), validate incoming messages and authenticate the connection (cookie or a short-lived token, never a long-lived secret in the URL).
  • Integrate with your state: push updates into the TanStack Query cache or a store rather than keeping a separate copy.
  • Close connections on unmount and when the tab is hidden if appropriate.
  • Libraries and services such as Socket.IO, Ably, Pusher, Supabase Realtime and Liveblocks handle many of these concerns.

Good enough to move on

You can build a small chat with WebSockets that reconnects and resyncs, and a notification feed with SSE, and explain when to choose each.

Key concepts

  • Polling and long polling
  • Server-Sent Events
  • WebSocket API
  • Reconnection, backoff and resync
  • Authenticating real-time connections
  • Syncing pushed data with the query cache
  • Socket.IO and hosted realtime services
  • WebRTC

Mini project

Build a live auction page: bids arrive over a WebSocket with reconnect and resync, an SSE stream shows outbid notifications, and incoming bids update the TanStack Query cache.

Check yourself

When would you choose Server-Sent Events over WebSockets?

Free resources