Why you need it
Chats, live scores and delivery maps must show news the moment it happens. On the web the browser normally asks and the server answers, so the server has no way to say "something new!" by itself. Three ways around that cost very different amounts.
Think of it like this
Waiting for a parcel. You can open the door every five minutes to check (polling). You can ask the courier to text you (server-sent events). Or you can stay on a phone call where either of you can talk at any time (WebSocket).
Where you’ll find it
- Discord: Keeps one WebSocket connection open per app, carrying every message and typing indicator both ways.
- Slack: Delivers new messages over WebSockets to millions of open apps at once.
- Chat AI apps: Stream answers word by word with server-sent events, as in Claude's API.
What to know first
Connection. An open line between your device and a server. Opening one takes a few round trips; keeping one open costs the server a little memory.
HTTP. The normal web rule: the browser asks, the server answers, and that exchange is over.
How it works
- Polling: keep asking. Ask "anything new?" every few seconds. Simple and works everywhere, but almost every answer is "no", and news waits until the next ask.
- Long polling: ask and wait. Ask, and the server holds the question open until there is news or about 30 seconds pass. Fewer empty answers, still plain HTTP. An old but sturdy trick.
- Server-sent events: the server talks. One line stays open and the server sends news down it whenever it has some. One way only, but it is plain HTTP and the browser reconnects by itself. Good for feeds, scores and streaming text.
- WebSocket: both talk. One open line, and both sides can send at any time. Needed when the user sends a lot too: chat, games, editing a document together.
- Open lines change how you scale. A server may hold 100,000 open lines, and a message for Ana must reach whichever server holds her line. That usually needs a shared message system between servers (see Publish and subscribe), and care when a server restarts and everyone reconnects at once.
An example
10,000 people watch a live score. With polling every 2 seconds, that is 5,000 requests a second, nearly all answered "no change". A goal still shows up to 2 seconds late.
With server-sent events: 10,000 open lines and no requests at all while nothing happens. When the goal is scored, 10,000 small messages go out at once, and everyone sees it within a fraction of a second.
Further reading
- Using server-sent events, MDN. The simplest real-time option, with a working example in a few lines. Start with this one.
- The WebSocket API, MDN. How a two-way line is opened and used in the browser.
- Long polling, javascript.info. A short chapter on the old trick that still works everywhere.
- Real-time Messaging, Slack Engineering. How a real chat app moves messages between millions of open connections.