Polling, long polling, SSE and WebSocket: Real time compared
In short: For live data on the web there are polling (asking regularly), long polling (holding back the response), server-sent events (server pushes events) and WebSockets (two-way connection).
In more detail: HTTP classically works as question and answer: the client asks, the server replies. For chats, notifications, live results or dashboards you want the server to send news by itself. There are four common techniques.
In Depth
Polling (short polling)
The client asks regularly (every 5 seconds) “Is there anything new?”.
setInterval(async () => {
const r = await fetch('/api/notifications');
show(await r.json());
}, 5000);Simple, works everywhere and with caching/proxies. Disadvantages: delay until the next query, many empty requests, load and database wake-ups. Good for rare changes; adapt the interval (only when the tab is visible, with backoff).
Long polling
The server keeps the request open until there is news (or a timeout), replies, and the client immediately asks again. Fewer empty requests and lower latency than polling, works over normal HTTP, but each open request occupies server resources; it was widespread before WebSockets.
Server-sent events (SSE)
A persistent HTTP connection over which the server sends events in one direction:
const es = new EventSource('/stream');
es.onmessage = (e) => show(JSON.parse(e.data));Advantages: simple, automatic reconnection, text format, efficient over HTTP/2. Only server → client. Ideal for notifications, live feeds, progress indicators, AI responses (streaming).
WebSocket
A bidirectional connection (client ↔ server) after an HTTP upgrade, low overhead, text and binary data:
const ws = new WebSocket('wss://example.com/chat');
ws.onmessage = (e) => show(e.data);
ws.send('Hello');Ideal for chats, games, collaborative work, live trading. Effort: connection management (reconnecting, heartbeats), scaling (many open connections, sticky sessions, pub/sub), firewall/proxy problems.
Choosing
- Rare updates → polling (simple, robust).
- Only server messages → SSE.
- Back and forth, low latency → WebSocket.
- Old environments → long polling. Consider server load, costs (for example serverless platforms with limited connection times) and database load. For phone battery and privacy: query sparingly, close connections when not needed.
See also: WebSockets, Server-sent events and real time, Webhooks, HTTP keep-alive