C.W.K.
Stream
Lesson 02 of 08 · published

Polling: The Naive Approach

~12 min · foundations, polling

Level 0Poller
0 XP0/60 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

What polling is

Polling is the simplest possible answer to "I want updates": ask repeatedly. Set a timer, fire a request, look at the response, sleep, repeat. It is the kindergarten version of real-time, and it is also still the right answer for an enormous range of problems.

Why polling is wasteful — except when it is not

For every actual update there are dozens of empty responses. Every empty response burned bandwidth, server CPU, and on mobile a radio wakeup. If your update frequency is much lower than your poll frequency, polling spends most of its time asking nothing. But if updates only land once a minute and a 30-second delay is fine, polling is the simplest technology that could possibly work, and you should reach for it without apology.

Smart polling

Add a "since" timestamp or sequence number, and the server can return only what is new — the round trip stays cheap even when there is nothing to say.

Code

Naive setInterval poll — fine for dashboards·javascript
// Refresh a dashboard every 30 seconds
async function refresh() {
  try {
    const res = await fetch('/api/dashboard');
    const data = await res.json();
    renderDashboard(data);
  } catch (err) {
    console.warn('Refresh failed, will retry next tick', err);
  }
}

setInterval(refresh, 30_000);
refresh(); // also do an immediate one
Smart polling with a watermark·javascript
let lastSeq = 0;

async function pollOnce() {
  const res = await fetch(`/api/messages?since=${lastSeq}`);
  if (!res.ok) return;
  const { messages, latestSeq } = await res.json();
  if (messages.length) {
    lastSeq = latestSeq;
    renderMessages(messages);
  }
}

// Poll, then schedule the next one — never overlap requests
async function loop() {
  await pollOnce();
  setTimeout(loop, 3_000);
}
loop();

External links

Exercise

Take any HTTP API you have (or a public one like https://api.github.com/repos/anthropics/claude-code). Write a 20-line polling loop that fetches it every 30 seconds and logs only when something *changes*. Run it for five minutes. Notice how many polls produced no useful output — that is the cost.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.