Skip to content
matthewcm.dev

    ↑ ↓ move · ↵ open · tab scopeopen graph →

    HTTP Long Polling

    The "hanging GET" — the server holds a request open until there's news, then the client asks again. Near-real-time over plain HTTP, and still the universal fallback.

    Growingtended planted 1 min read
    On this page

    Long polling is the clever hack that made real-time web apps possible before browsers had a proper way to do it. The client makes a request; if the server has nothing new, instead of replying empty it holds the request open until there’s data (or a timeout). As soon as the client gets a response, it immediately asks again — so there’s almost always a waiting request the server can answer the moment something happens.

    The loop

    async function subscribe(cursor = "") {
      while (true) {
        const res = await fetch(`/events?since=${cursor}`); // server waits up to ~30s
        if (res.status === 200) {
          const { events, next } = await res.json();
          handle(events);
          cursor = next;
        } else if (res.status !== 204) {
          await sleep(backoff()); // error: back off before retrying
        }
      }
    }

    The details that bite

    • Timeouts. Proxies and load balancers often kill idle connections at around a minute. Hold for less than that, and return an empty 204 on timeout so the client simply loops.
    • Gaps between polls. Events that arrive between one response and the next request can be lost. Always send a cursor (?since=…) so the server can replay anything missed. This is the same idea as Last-Event-ID in Server-Sent Events (SSEs).
    • Server resources. Every waiting client holds a connection. That’s cheap with async I/O and painful with thread-per-request servers.

    Where it fits now

    SSE standardised the server-to-client half of this, and WebSockets cover two-way traffic. Long polling remains the fallback when long-lived connections are blocked by corporate proxies, and it’s still a sensible choice for “poll for jobs” APIs. Compare all four techniques in AJAX Polling.

    • #long-polling
    • #real-time
    • #http

    ↪ Links to (3)