🔄 Fix a Long-Polling Request Silently Piling Up Duplicate Connections Because the Previous One Was Never Aborted Before Starting the Next
Long polling works by holding a request open until the server has something new to report, then immediately firing off a fresh request to go back to waiting — and that “immediately fire off a fresh request” step is exactly where a missing cleanup step causes trouble. If the code that starts a new long-poll request doesn’t first make sure the previous one is actually finished (or explicitly abort it when it isn’t), a reconnect triggered by something other than a clean server response — a page regaining focus, a network blip, a reconnect button — can leave the old request still open on the server side while a brand new one starts stacking on top of it, and the browser quietly accumulates open connections that never get cleaned up until they individually time out.
🔎 The Problem
// Bug: no record of the in-flight request, nothing to abort
function startLongPoll() {
fetch('/poll').then(res => res.json()).then(data => {
handleUpdate(data);
startLongPoll(); // chains cleanly on a real response
});
}
window.addEventListener('focus', startLongPoll);
// Every time the tab regains focus, this starts ANOTHER poll loop
// on top of whichever one (if any) is already running - nothing
// here ever stops the previous one.
✅ The Fix
- Keep a single module-level AbortController for the current long-poll request, and call .abort() on the previous one before creating a new controller and starting a fresh request, so there’s never more than one in-flight poll at a time.
- Guard the reconnect trigger itself with a simple in-progress flag (or check the AbortController’s signal) so a focus event or reconnect button firing while a poll is already active doesn’t start a second loop stacked on top of the first.
- Watch your server’s open-connection count during a quick manual test where you rapidly switch tabs or toggle network conditions — a correct implementation’s connection count stays flat; a leaking one climbs with every reconnect trigger.
🚨 Why This Is Dangerous
- Each duplicate connection consumes a server-side worker, socket, or thread for as long as it stays open, and on a server with a fixed connection pool, enough accumulated duplicates from enough clients switching tabs can exhaust that pool for everyone, not just the clients that caused it.
Long polling’s whole model depends on there being exactly one open request per client at a time — nothing enforces that for you, and a missing abort is how it quietly becomes two, then three, then more.

