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

Polling: 가장 단순한 답

~12 min · foundations, polling

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

Polling 이 뭐야

Polling 은 'update 받고 싶다' 에 대한 가장 단순한 답이야. 타이머 걸고, request 쏘고, 응답 보고, 자고, 반복. 유치원 버전의 real-time 이야. 그리고 여전히 엄청 많은 문제에 대해 이게 옳은 답이야.

Polling 이 낭비인 이유 — 그리고 아닐 때

실제 update 하나마다 빈 응답이 수십 개 있어. 빈 응답 하나마다 bandwidth, 서버 CPU, 모바일에선 라디오 wakeup 까지 태워. 만약 update 빈도가 polling 빈도보다 훨씬 낮으면 polling 은 대부분의 시간을 아무 것도 안 묻는 데 써. 근데 update 가 분당 한 번 떨어지고 30초 지연이 ok 이면, polling 이 가능한 가장 단순한 기술이고, 부끄러워하지 말고 손 가져가도 돼.

Smart polling

'since' timestamp 나 sequence number 추가하면 서버는 새로운 것만 돌려줘. 할 말 없는 round trip 도 싸게 끝나.

Code

Naive setInterval poll — dashboard 엔 충분·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
Watermark 있는 smart polling·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

아무 HTTP API 골라 (또는 https://api.github.com/repos/anthropics/claude-code 같은 public 한 거). 30초마다 fetch 해서 *바뀐 것만* 로그하는 polling loop 20줄 짜로 써. 5분 돌려. 쓸데없는 polling 몇 번이었는지 세어봐 — 그게 비용이야.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.