How-To Guide

How to Implement HTTP Long Polling

Hold requests open until data arrives or a timeout fires, loop with AbortController and backoff, and respect connection budgets under HTTP/1.1.

On this page

  1. Introduction
  2. Semantics of a hold
  3. Implement the hanging server
  4. Implement the client loop
  5. Connection budgets and HTTP/1.1
  6. Test the three outcomes
  7. When to choose long polling
  8. Common pitfalls
  9. Conclusion

Introduction

Long polling is the oldest server-push technique that still works everywhere: the client requests updates, and the server holds the request open until something worth sending exists or a timeout expires, then answers and the client immediately asks again. The effect is near-real-time delivery with nothing but ordinary HTTP: no upgrade handshake, no special content type, no protocol besides a cursor the client echoes back. That compatibility is its enduring value, because restrictive corporate proxies, older load balancers, and odd server runtimes will happily serve a slow GET while breaking Server-Sent Events buffering or stripping WebSocket upgrade headers. The cost is equally concrete: every message costs a full request cycle, the client must own the reconnect loop that SSE gives for free, and each open hold occupies a connection, which interacts with browser connection limits. This tutorial implements both ends, chooses hold timeouts against real proxy limits, handles the empty-response case cleanly, and closes with the decision of when long polling is the right tool rather than the familiar one.

Semantics of a hold

A long poll is defined by three contracts. The cursor contract: the client sends the position it has consumed, a timestamp, sequence number, or opaque token, and the server sends only newer items. The wait contract: the server holds up to a bounded timeout, and if nothing arrives it answers empty rather than holding forever, so both sides rediscover each other periodically and proxies see activity. The reconnect contract: the client treats every response, data or empty, as the trigger for the next request, and treats errors with backoff instead of hammering. The empty answer deserves deliberate design. A 204 with no body is unambiguous and cheap; a 200 with an empty array preserves a single response schema at the cost of a few bytes; a 304 pairs naturally with an ETag cursor. Any of the three works, but pick one and document it, because clients written against one interpretation quietly mishandle the others. The hold timeout itself should sit in the twenty-five to sixty second range: long enough that empty cycles are uncommon, short enough to stay below the idle timeouts of proxies and load balancers that commonly sit at thirty to sixty seconds.

Implement the hanging server

The server parks each request on a per-topic waiter list with a timer. When an event is published, every waiter on the topic is answered immediately with the new events; when the timer fires, the waiter is answered empty. The critical details are flushing headers before parking, so intermediaries see a live response, and cleaning waiters up on client disconnect, which fires when the user closes the tab.

import { EventEmitter } from 'node:events';

const bus = new EventEmitter();
const HOLD_MS = 25_000;

export function longPollHandler(req, res) {
 const topic = req.query.topic;
 const cursor = String(req.query.cursor ?? '');

 res.writeHead(200, {
  'content-type': 'application/json',
  'cache-control': 'no-store',
  'x-accel-buffering': 'no',
 });

 const waiters = [];
 const send = (events) => {
  cleanup();
  res.end(JSON.stringify({ events, cursor: lastCursor(events, cursor) }));
 };

 const onEvent = (ev) => {
  waiters.push(ev);
  if (waiters.length >= 1) send(waiters.splice(0));
 };
 const onTimeout = () => send([]);
 const cleanup = () => {
  bus.off(topic, onEvent);
  clearTimeout(timer);
 };

 const timer = setTimeout(onTimeout, HOLD_MS);
 bus.on(topic, onEvent);
 req.on('close', cleanup);

 const backlog = drainBacklog(topic, cursor);
 if (backlog.length > 0) send(backlog);
}

The backlog drain before parking matters: events published between the client’s last response and this new request would otherwise be invisible until the next event arrives, creating gaps precisely where the technique promises continuity. The x-accel-buffering header disables buffering on nginx-derived proxies for this route; equivalent directives exist for other front-ends and belong in the deployment checklist.

Implement the client loop

The client is a sequential loop: one request at a time, echoing the cursor from the previous response. Sequential is the point, because parallel polls on one topic produce reordering and duplicated work. AbortController gives the client a way to stop cleanly when the page changes, and the loop distinguishes the three outcomes: events, empty, and error.

export async function longPoll(
 url: string,
 onEvents: (events: unknown[]) => void,
 signal: AbortSignal,
) {
 let cursor = '';
 let backoff = 1_000;

 while (!signal.aborted) {
  const timeout = AbortSignal.timeout(30_000);
  try {
   const res = await fetch(url + '&cursor=' + encodeURIComponent(cursor), {
    signal: AbortSignal.any([signal, timeout]),
   });
   if (res.status === 429 || res.status === 503) {
    const wait = Number(res.headers.get('retry-after') ?? backoff);
    backoff = Math.min(backoff * 2, 30_000);
    await sleep(wait * (0.5 + Math.random() * 0.5), signal);
    continue;
   }
   if (!res.ok) throw new Error('poll failed: ' + res.status);
   const body = await res.json() as { events: unknown[]; cursor: string };
   if (body.events.length > 0) onEvents(body.events);
   cursor = body.cursor;
   backoff = 1_000;
  } catch (err) {
   if (signal.aborted) return;
   await sleep(backoff * (0.5 + Math.random() * 0.5), signal);
   backoff = Math.min(backoff * 2, 30_000);
  }
 }
}

Resetting backoff on any successful exchange, including an empty one, keeps transient errors from ratcheting the delay upward during healthy operation. The jitter factor prevents a fleet of clients from re-attacking a recovering server in lockstep, the same herd discipline any reconnect loop needs.

Connection budgets and HTTP/1.1

Every held long poll is an open connection, and browsers cap connections per origin: six on HTTP/1.1, shared across all requests to that origin. A page holding three topic polls has half its budget consumed before any image, script, or fetch happens, and a fourth topic can starve ordinary navigation entirely. The mitigations are ordered. Consolidate topics: one poll carrying a multiplexed event stream for several topics costs one connection instead of several. Move long polls to a dedicated origin or subdomain, which resets the budget at the cost of an extra connection setup. Deploy HTTP/2, where multiplexing removes the per-connection cap and makes the whole concern mostly vanish. Server capacity deserves the same audit: each hold occupies a socket and, in thread-per-request runtimes, a thread, so the maximum concurrent holds the server can park must be sized explicitly, and event-driven runtimes or async handlers convert that occupancy from a thread into a cheap promise, which is why Node, Go, and async Python host long polling comfortably while classic thread pools do not.

Test the three outcomes

Long polling logic hides in timing, so tests need controllable clocks and controllable event buses rather than real sleeps. Outcome one, events: publish to the topic while a request is parked and assert the response carries the event and the advanced cursor. Outcome two, empty: advance the fake clock past the hold timeout and assert the response is the documented empty shape, 204 or empty array, and that the waiter was removed. Outcome three, disconnect: abort the client mid-hold and assert the server waiter list shrinks and no further events are routed to the dead request. Client-side, assert the loop re-requests immediately after an events response, waits backoff after an error, honors Retry-After when given, and stops entirely when the outer signal aborts. A final integration check through the real production proxy chain, answering within the hold window and streaming without buffering, catches the deployment issues that localhost never shows.

vi.useFakeTimers();
const poll = longPoll(url, collector.push, controller.signal);
bus.emit('orders', event);
await vi.waitFor(() => expect(collector.events).toHaveLength(1));
vi.advanceTimersByTime(25_000);
await vi.waitFor(() => expect(collector.empties).toBe(1));

When to choose long polling

Choose long polling deliberately for three situations. Compatibility-first environments: intranet proxies, embedded webviews, and appliance HTTP stacks that mangle streaming content types or upgrade headers, where a slow ordinary GET is the only shape guaranteed to survive. Sparse update patterns: a page that expects an event every few minutes gains little from SSE infrastructure and pays nothing for a poll cycle that is usually empty. And migration scaffolding: a long-poll endpoint with a cursor is one refactor away from SSE, since the event bus, cursor, and backlog logic transfer directly. Choose against it when updates are frequent, every message costs a request cycle including headers and connection overhead, when the client needs binary or bidirectional flow, or when HTTP/2 and friendly proxies make SSE available with less client code. Write the choice down with the constraint that drove it, because long polling chosen for familiarity tends to persist after the constraint that justified it has gone.

Common pitfalls

  • Holding past proxy idle timeouts. The proxy answers 504 on your behalf and the client sees errors forever; hold below the shortest path timeout.
  • Forgetting the backlog drain. Events published between polls are invisible until the next event, silently breaking continuity.
  • Buffering middleware. Headers must flush before parking, or the client waits on a response the proxy has swallowed.
  • Parallel polls per topic. Sequential echoing of one cursor is the protocol; parallel calls reorder and duplicate.
  • Counting against the HTTP/1.1 budget. Several held polls starve ordinary requests; consolidate or deploy HTTP/2.
  • Backoff that never resets. Transient errors during healthy operation ratchet the delay upward permanently unless success resets it.

Conclusion

Long polling trades elegance for reachability: near-real-time delivery over nothing but ordinary HTTP, surviving infrastructure that breaks every fancier transport. Implement the three contracts precisely, a cursor that defines what is new, a bounded hold with a documented empty response, and a client loop that treats every completion as the next request. Flush before parking, drain the backlog before waiting, and keep the hold below the shortest proxy timeout on the path. Respect connection budgets by consolidating topics or moving to HTTP/2, and test the events, empty, and disconnect outcomes with fake clocks. Then keep it in the toolbox for the compatibility-first, sparse-update, and migration cases where it is genuinely the right answer rather than merely the familiar one.

Sources: MDN: AbortController, MDN: Fetch API, MDN: Retry-After header.

FAQ

Is long polling still worth building?
As a deliberate choice, yes: it works everywhere HTTP works, including restrictive proxies that break SSE or WebSocket upgrades. As a default, no: SSE gives the same semantics with browser-managed reconnection when the infrastructure supports it.
How long should the server hold the request?
Twenty-five to sixty seconds is typical. The ceiling is set by intermediary timeouts, commonly 30 to 60 seconds, and the floor by how often you are willing to answer empty. Hold below the shortest timeout on the path.
Why does my long poll return immediately with nothing?
Something in the chain buffers or converts the response, or the server answered before parking the request. Flush headers immediately, disable response buffering for the route, and confirm no middleware short-circuits the wait.

Related Examples