Wirebook › Bonus lesson
Does the app keep peeking, or does the website ring a doorbell?
A brand-new lesson appears on a website. How does a news app on your phone find out? Does it keep peeking, again and again, or does the website ring a tiny doorbell? Race three messengers through a pretend day, count the wasted trips, then try being the peeker yourself.
Three ways to hear about something new
- Peeking (polling). The app asks the website “anything new?” on a timer. Simple and works everywhere, but there's a trade-off you can't escape: peek often and most trips come back empty; peek rarely and news sits waiting. Slide the peeker to 1 minute, then to 4 hours, and watch the two numbers swap places.
- Waiting at the door (long polling). The app asks once and the website holds the question open until there's news, or until half an hour passes and it says “still nothing, ask again.” News arrives almost instantly with far fewer trips, but the website has to keep a line open for every waiting app.
- A doorbell (push). The app tells the website once where its doorbell is. When something new appears, the website rings it. One ring per piece of news, no wasted trips. Phones use a push service run by the phone's maker as a post office: when your phone is asleep or offline, it holds the rings and delivers them when the phone wakes. Tick “Phone asleep” to see that.
So which is best?
It depends on who needs to be told and how fast. A chat app needs news in a second, so it uses push or keeps a connection open. A recipe blog's feed can be peeked at every hour by thousands of readers, and if each peek gets a 304, that costs almost nothing. Websites can also offer both: a feed for peekers, plus a hub that pings subscribed readers the moment the feed changes (one standard for this is called WebSub). Developers call the website-rings-another-server version a webhook: when your payment goes through or someone comments, one server calls a web address the other server gave it.
Doorbells need a bit of trust and setup: the website must keep a list of who to ring, and a doorbell address that leaked could let a stranger ring it too, so real webhooks are signed. Peeking needs no list at all, which is also why it's the private choice: the website doesn't learn who is waiting.
Peeking on a strict timetable is also how a game controller keeps the console up to date, hundreds of times a second: see how a game controller talks to a console.
Grown-up twin: Tooltern's help pages on 304 Not Modified and cron schedules (the timers that drive a lot of polling) show the same ideas with real headers.