WebSockets vs SSE vs long polling
HTTP was designed for the browser to ask and the server to answer. But a lot of products need the server to speak first: a new WhatsApp Web message, a wicket in the IPL final, a Swiggy order that just left the restaurant, a stock price tick. There are four ways to do it, and they trade simplicity against cost and against which direction data needs to flow.
During an India vs Pakistan match, 50 million people have a live score page open. The score changes about once every 30 seconds, and nobody sends anything back. Would you hold 50 million WebSocket connections? What else could work?
The four options#
Short polling is a timer. It is trivially simple, works through every proxy and caches well, but most requests return nothing and updates arrive late by up to one interval.
Long polling is a polite trick on plain HTTP: the server holds the request until it has something to say. Near real time, works everywhere, but every message costs a new request, and you must handle the gap between one response and the next request.
Server sent events (SSE) keep one HTTP response open and stream text events down it. The
browser's EventSource handles parsing and reconnects automatically, resuming from the
last event id. It only goes from server to client, which is all a score feed, a notification
bell or a token by token AI answer needs. (ChatGPT style streaming responses use exactly this
format.)
WebSockets upgrade an HTTP connection into a full duplex channel. Either side sends messages at any time with tiny overhead. They are the right tool when the client talks a lot too: chat, multiplayer games, collaborative editors, trading screens. You get no automatic reconnection, no resume and no HTTP caching or semantics; you build those yourself or use a library like Socket.IO.
const events = new EventSource('/matches/ind-pak/stream')
events.onmessage = (e) => render(JSON.parse(e.data))
// Dropped connection? EventSource reconnects by itself and sends Last-Event-ID.