WebSockets vs Server-Sent Events vs polling: when to use each
WebSocket full-duplex, WebSocket handshake, SSE unidirectional, EventSource API, long polling, short polling, use case comparison, browser support
Real-Time Communication Options
Not every web feature needs WebSockets. Choosing the right real-time mechanism affects server resource usage, implementation complexity, and reliability under reconnect scenarios.
Short polling
Client sends a request on a timer โ every N seconds โ and checks for updates. Simple to implement with setInterval and fetch. Generates unnecessary requests when nothing has changed. Acceptable for low-frequency background sync (every 30โ60 seconds). Poor choice for sub-second latency requirements.
Server-Sent Events (SSE)
One persistent HTTP connection where the server streams events to the client. The client uses the native EventSource API. Unidirectional โ server to client only. Auto-reconnects on drop. Works over HTTP/2 multiplexing without extra connections.
// Client
const es = new EventSource('/events');
es.onmessage = e => console.log(e.data);
es.addEventListener('price', e => updatePrice(e.data));
// Server (Node.js)
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.write('event: price
data: {"symbol":"BTC","price":42000}
');WebSockets
Full-duplex: both client and server can send messages at any time over one persistent TCP connection. Required when the client also needs to push real-time data โ keystrokes, cursor positions, game actions.
const ws = new WebSocket('wss://example.com/ws');
ws.onmessage = e => console.log(e.data);
ws.send(JSON.stringify({type: 'cursor', x: 120, y: 340}));Decision rule: live feed (notifications, prices) โ SSE. Interactive bidirectional (chat, collaborative tools, games) โ WebSockets. Infrequent background sync โ polling.
