Menu
Course/Networking & Communication/Long Polling vs Short Polling

Long Polling vs Short Polling

When WebSockets are overkill: understanding short polling, long polling, and how to choose the right approach for your latency requirements.

8 min read

Why Polling?

WebSockets and SSE are powerful, but they require persistent connections and specialized infrastructure. Polling is the oldest and simplest approach to near-real-time data: the client periodically asks the server if anything has changed. Despite being less efficient than push-based approaches, polling remains relevant in many real-world situations.

ℹ️

When polling is the right choice

Polling is appropriate when: WebSockets are blocked by corporate firewalls or proxies, the update frequency is low (every few minutes), you're building a simple internal tool where infrastructure simplicity outweighs efficiency, or you're supporting very old browser environments. For anything requiring updates faster than every 30 seconds with meaningful traffic, prefer SSE or WebSockets.

Short Polling

Short polling sends an HTTP request to the server at a fixed interval. The server responds immediately with whatever data is available (even if nothing has changed), and the client schedules the next request.

Loading diagram...
Short polling: client makes requests at fixed intervals regardless of whether new data exists
javascript
// Short polling: check every 5 seconds
function startShortPolling(userId) {
  const poll = async () => {
    try {
      const response = await fetch(`/api/notifications/${userId}`);
      const data = await response.json();
      if (data.notifications.length > 0) {
        renderNotifications(data.notifications);
      }
    } catch (err) {
      console.error('Poll failed:', err);
    }
  };

  poll(); // Immediate first call
  return setInterval(poll, 5000); // Then every 5s
}
  • Simplicity: Standard HTTP request — works everywhere, easy to implement, easy to cache.
  • Predictable server load: Requests arrive at a fixed rate, making capacity planning straightforward.
  • Wasteful: Most requests return nothing, burning server CPU, network bandwidth, and client battery.
  • Latency: On average, the user waits `interval / 2` time after an event before seeing it. At 5-second intervals, average latency is 2.5 seconds.

Long Polling

Long polling improves on short polling by having the server hold the request open until new data is available. The client sends a request; the server doesn't respond until it has something to send or a timeout (typically 30-60 seconds) expires. When the response arrives, the client immediately sends another request.

Loading diagram...
Long polling: server holds request until data arrives or timeout, then client immediately reconnects
javascript
// Long polling client implementation
async function longPoll(userId, lastEventId = null) {
  while (true) {
    try {
      const url = new URL(`/api/events/${userId}`);
      if (lastEventId) url.searchParams.set('since', lastEventId);

      const response = await fetch(url, {
        signal: AbortSignal.timeout(65000) // Slightly over server timeout
      });

      if (response.ok) {
        const data = await response.json();
        if (data.events.length > 0) {
          lastEventId = data.events.at(-1).id;
          processEvents(data.events);
        }
        // Immediately reconnect
      }
    } catch (err) {
      if (err.name !== 'TimeoutError') {
        // Exponential backoff on real errors
        await sleep(Math.min(retries++ * 1000, 30000));
      }
    }
  }
}

Comparing All Approaches

AspectShort PollingLong PollingSSEWebSocket
LatencyUp to full interval (high)Near-real-time (low)Near-real-time (low)Real-time (lowest)
Server connections at 10K usersLow (bursty)High (10K open connections)High (10K open connections)High (10K open connections)
Server complexityVery lowMediumLowHigh
HTTP proxy/firewall compatibilityUniversalUsually fineUsually fineSometimes blocked
Auto-reconnectN/A (client controls)ManualBuilt-inManual
BidirectionalNoNo (workaround: separate POST)NoYes
Browser supportUniversalUniversalAll modern browsersAll modern browsers

Decision Framework

Use this mental model when choosing a real-time mechanism in an interview:

  1. Do you need sub-second bidirectional communication? → WebSocket (gaming, collaborative editing, live chat with user input).
  2. Is it server-to-client only with near-real-time needs? → SSE (notifications, live dashboards, order tracking).
  3. Are WebSockets/SSE blocked or unsupported? → Long polling (enterprise environments, legacy systems).
  4. Is the update frequency low (> 1 minute)? → Short polling (build status, email sync, weather updates).
  5. Is push completely overkill? → Webhooks + pull on demand (third-party integrations, batch jobs).
📌

Historical: How Gmail used long polling

Before WebSockets were standardized, Gmail used long polling to deliver new email notifications. The client would make an HTTP request that the server held open for up to 60 seconds. When a new email arrived, the server would respond, and the client would immediately reconnect. This gave near-real-time email delivery without persistent connections. Today, Gmail uses a combination of WebSockets and SSE for different features.

💡

Interview Tip

Interviewers rarely ask you to implement polling directly, but they do ask 'how would you handle real-time updates?' Demonstrate you know the trade-off spectrum: short polling (simplest, most wasteful), long polling (better latency, more server resources), SSE (server-push simplicity with auto-reconnect), WebSocket (full-duplex power). Show that you choose based on requirements — bidirectionality, latency, client constraints — not just defaulting to WebSocket for everything.

📝

Knowledge Check

5 questions

Test your understanding of this lesson. Score 70% or higher to complete.

Ask about this lesson

Ask anything about Long Polling vs Short Polling