21. Polling vs WebSockets vs Push
1
The picture to keep in your head2
21.1 What's the problem: the server has news for you?3
21.2 What are the options?4
21.3 How do you scale millions of open connections?5
21.4 How do heartbeats, reconnects and missed messages work?6
21.5 How do you choose?7
Memory card and where the analogy breaks8
Practice: five levels9
Interview questions10
Solutions11
Sources12
Code lab21. Polling vs WebSockets vs Push
Memory card and where the analogy breaks
3 min read+10 XP
The memory card (tear this page out)
| # | Question | Memory code |
|---|---|---|
| 21.1 | The problem? | The server knows first, but only the client can dial |
| 21.2.1 | Short polling? | Ask often and waste, or ask rarely and wait |
| 21.2.2 | Long polling? | Stay on the line until there's news, then call straight back |
| 21.2.3 | SSE? | Switch on the radio: the server talks, you listen |
| 21.2.4 | WebSockets? | An open phone line: either side can talk, anytime |
| 21.2.5 | Mobile push? | A note in the letterbox: short, maybe late, but it reaches you when you're out |
| 21.3 | Millions of connections? | Gateways hold the lines; the backplane knows who's on which |
| 21.4 | Heartbeats and reconnects? | Ping to check, wait a random bit to redial, then ask "where were we?" |
| 21.5 | How to choose? | Out? Push. Talking? WebSocket. Listening? SSE. Rarely? Poll |
The whole chapter in one line: The client opens the line; poll if updates are rare, stream with SSE if only the server talks, use WebSockets if both do, push when the app is closed, and always be ready to reconnect and catch up.
Where the analogy breaks
- A phone call costs you. An idle connection costs the server: memory and a file descriptor for every user, all the time, even when nothing is said.
- When a phone call drops, you notice. A network connection can die silently, which is why heartbeats exist.
- A note in the letterbox always arrives. Push notifications may not: no delivery guarantee, so the app must re-fetch the truth when opened.
Quick check
Five questions on this chapter. Pick an answer, then check it.
quiz