Part I β The Pipes Β· Lesson 2.3
Long Polling
In one lineThe client asks, and the server holds the request open until it actually has news.
Where you've seen itOld Facebook Chat β messages appeared instantly, years before WebSockets existed in browsers.
Diagram
Client Server
β β
βββββ GET /messages ββββββββββββΊβ
β β holds... (no data yet)
β (waiting 25s) β
β β βββ new message arrives
βββββββββ 200 [msg] βββββββββββββ
β β
βββββ GET /messages ββββββββββββΊβ client immediately re-asks
β β holds...
ββββββββ 204 timeout ββββββββββββ after 30s, empty
βββββ GET /messages ββββββββββββΊβ re-asks againSAME WALL CLOCK, FAR FEWER ROUND TRIPS
SHORT POLL 0sββββ5sββββ10sβββ15sβββ20sβββ25s
REQ REQ REQ REQ REQ REQβ
6 requests, 1 useful
LONG POLL 0sβββββββββββββββββββββββββββββ25s
REQ ββββββββ held βββββββββββββΊβ
1 request, 1 usefulTHE GAP β where messages get lost
ββββ 200 [msg 7] ββββ response in flight
β β β msg 8 arrives HERE, no open request
ββββ GET βββββββββββΊβ client re-asks
msg 8 must be replayed, not dropped
Fix: client sends its last seen id β GET /messages?since=7How it works
- Client sends a request.
- Server does not respond; it parks the request and registers the client as a listener.
- On new data β respond immediately. On a 25β30s timeout β respond empty.
- Client immediately opens the next request, passing the last id it saw.
- Server replays anything that arrived during the gap.
Trade-offs
| Use when | Avoid when |
|---|---|
| Updates are infrequent and unpredictable | Updates are constant β WebSocket |
| Proxies or firewalls block WebSockets | You need client β server push too |
| You want plain HTTP infrastructure | Server can't hold many open connections |
Server-side cost: every waiting client occupies a connection. A thread-per-request server dies at a few thousand; an event-loop server (Node, Go, nginx) handles far more. This is a backend constraint you should name out loud.
Interview angle
"Why not just poll every second instead?"
- Short polling burns requests when nothing changed; long polling only answers when there's news.
- The cost moves from bandwidth to held server connections and requires a non-blocking server.
- Past roughly one update per second, reconnect churn beats the savings β switch to WebSocket or SSE.
Recap
- Long polling is pull that feels like push.
- Always pass a cursor (
?since=) β the gap between responses drops messages otherwise. - Bridge technology: correct when WebSockets aren't available, not when they are.