WebSockets vs Server-Sent Events vs Polling
On this page
Learning Objective
Choose between polling, long polling, server-sent events and WebSockets for live data, implement reconnection with backoff and resumption, integrate real-time messages with the client cache, and handle authentication, ordering, duplicates and background tabs.
Concept Explanation
Many interfaces need data that changes while the user is looking at it: order status, notifications, chat, live dashboards, collaborative editing, prices. HTTP is request and response, so the client normally only learns about changes when it asks. There are four main ways to get updates, with increasing complexity and capability.
Polling asks the server at a fixed interval. It is simple, works through every proxy and uses ordinary caching and authentication, but it trades freshness for load: a short interval wastes requests when nothing changes and a long one shows stale data. It is often the right choice for data that changes every few minutes and for small user counts, especially with a query library's refetchInterval that pauses in background tabs. Long polling holds each request open until there is news or a timeout, then the client immediately asks again, which reduces latency but is mostly superseded by the next two options.
Server-sent events, SSE, keep one HTTP response open and let the server push a stream of text events to the client through the EventSource API. They are one-directional, server to client, which fits notifications, feeds, progress updates and streamed AI responses. They run over normal HTTP, work well with HTTP/2 multiplexing, reconnect automatically and support resumption: each event can carry an id, and after a reconnect the browser sends the last id in a Last-Event-ID header so the server can replay what was missed. The native EventSource cannot send custom headers, so it relies on cookies for authentication, or you can read a streaming fetch response instead.
WebSockets upgrade an HTTP connection to a persistent, full-duplex channel where both sides can send messages at any time with very low overhead. They suit chat, multiplayer games, collaborative editing and trading screens. The flexibility comes with responsibilities the protocol leaves to you: reconnection with exponential backoff and jitter so thousands of clients do not reconnect at the same instant after a server restart, heartbeats to detect dead connections, resubscription and catching up on missed messages after reconnecting, message ordering and deduplication, and authentication, since browser WebSockets cannot set headers, so authentication usually relies on cookies or a short-lived token sent in the first message. Servers must check the Origin header during the handshake, because cookies are sent with cross-site WebSocket connections.
Whatever the transport, real-time messages should feed the same client cache as ordinary requests. A message that an order shipped can update the cached order with setQueryData or invalidate the order queries so they refetch. Treat messages as hints that are idempotent: duplicates and out-of-order delivery happen, so include versions or timestamps and ignore older updates. When a tab is hidden, consider closing the connection or slowing polling, and on visibility return, refetch to catch up, which also covers missed messages during sleep or network changes.
| Approach | Direction | Strengths | Weaknesses |
|---|---|---|---|
| Polling | Client asks repeatedly | Simple, cacheable, robust | Wasted requests or stale data |
| Long polling | Client asks, server waits | Lower latency than polling | Many open requests, legacy |
| Server-sent events | Server to client | HTTP, auto reconnect, resume by id | One direction, text only |
| WebSockets | Both directions | Low latency, bidirectional | Reconnect, auth and scaling are yours |
| Streaming fetch | Server to client | Custom headers, any method | Manual parsing and reconnects |
Worked Example: SSE Notifications into the Cache and a Resilient WebSocket
Server-sent events update cached orders and notifications. The WebSocket client reconnects with jittered backoff, sends heartbeats and resubscribes after reconnecting.
// Server-sent events: one-way updates, resumable by event id
export function useOrderEvents() {
const qc = useQueryClient();
useEffect(() => {
const es = new EventSource('/api/events', { withCredentials: true }); // cookie auth
es.addEventListener('order.updated', (e) => {
const order = OrderSchema.parse(JSON.parse((e as MessageEvent).data));
qc.setQueryData(['order', order.id], (old: Order | undefined) =>
!old || order.version > old.version ? order : old); // ignore stale or duplicate events
qc.invalidateQueries({ queryKey: ['orders', 'list'] });
});
return () => es.close(); // the browser reconnects on its own until closed
}, [qc]);
}
// WebSocket with backoff, jitter, heartbeats and resubscription
export function connectChannel(url: string, onMessage: (m: unknown) => void, topics: string[]) {
let ws: WebSocket; let attempt = 0; let heartbeat: number; let closed = false;
const open = () => {
ws = new WebSocket(url);
ws.onopen = () => {
attempt = 0;
ws.send(JSON.stringify({ type: 'subscribe', topics })); // resubscribe after every reconnect
heartbeat = window.setInterval(() => ws.send('{"type":"ping"}'), 25_000);
};
ws.onmessage = (e) => onMessage(JSON.parse(e.data));
ws.onclose = () => {
clearInterval(heartbeat);
if (closed) return;
const delay = Math.min(30_000, 1000 * 2 ** attempt++) * (0.5 + Math.random() / 2); // backoff with jitter
setTimeout(open, delay);
};
};
open();
return () => { closed = true; ws.close(); };
}Version checks make the handlers idempotent, so a duplicated or delayed event can never move an order back to an older state. After a reconnect, the client resubscribes and lets queries refetch to fill any gap.
Real-World Examples
- Streaming AI chat interfaces commonly use server-sent events or streamed fetch responses to deliver tokens as they are generated, and the HTML specification's EventSource interface, with automatic reconnection and Last-Event-ID resumption, has been supported in all major browsers for years.
- Slack's engineering blog has described how its desktop and web clients maintain WebSocket connections to receive real-time events and how it rebuilt its real-time infrastructure to handle reconnection storms and very large numbers of concurrent connections.
Review Questions & Answers
When updates flow only from server to client, such as notifications, live feeds, progress or streamed responses. SSE works over plain HTTP, reconnects automatically and can resume from the last event id, so it needs far less custom infrastructure than WebSockets.
When a server restarts, every connected client disconnects at the same moment. Without jitter, they would all retry at the same intervals and overwhelm the server repeatedly. Random variation spreads the reconnections over time.
Messages can be delivered twice or out of order, especially around reconnections. If each update carries a version and handlers ignore older or equal versions, duplicates and delayed messages cannot overwrite newer data.
Browsers cannot set custom headers on WebSocket connections, so authentication relies on cookies sent with the handshake or a short-lived token sent in the first message. Because cookies are sent even for cross-site connections, the server must validate the Origin header to prevent cross-site WebSocket hijacking.