21. Polling vs WebSockets vs Push
The picture to keep in your head
Every question below is answered twice: first at the gate, so you can picture it, then in the system, so you know exactly how it works. Each answer ends with a memory code to lock it in.
The picture to keep in your head
You've ordered groceries and you're waiting. How do you find out when they're coming?
You could call the courier every 5 seconds: "Any update?" "No." "Any update?" "No." Tiring for both of you, and most calls are wasted. You could call once and say "call me back when there's news", and they stay on the line until there is. You could switch on a radio that the shop broadcasts on, and just listen. You could keep a phone line open where either of you can talk at any time. Or, if you've gone out, the shop can drop a note in your letterbox that you'll see when you get home.
Each of these is a real way for a server to tell an app "something happened". They differ in who keeps the line open, for how long, and whether you can talk back.
Our running example: the grocery app's live order tracking. An order goes through five updates over about 20 minutes (placed, packed, rider assigned, out for delivery, delivered), plus the rider's position on a map. At the evening peak, about 100,000 customers are tracking orders at once (an assumption for practice).
| At the gate | In the system |
|---|---|
| Calling every 5 seconds: "any update?" | Short polling |
| "Call me back when there's news" | Long polling |
| Listening to the shop's radio | Server-sent events (SSE) |
| An open phone line, both can talk | WebSockets |
| A note in the letterbox when you're out | Mobile push (APNs, FCM) |
| A call centre with thousands of open lines | Scaling millions of connections |
| "Are you still there?" | Heartbeats |
| "Sorry, we got cut off. Where were we?" | Reconnects and catching up |
Figure: the server has news; the only question is who keeps the line open, and for how long.