When you wrap an asynchronous operation with AbortSignal.timeout() inside a pooled batch or worker queue, memory usage creeps upward and timed-out HTTP sockets quietly stay open. Under load, your service runs out of file descriptors, Node throws ERR_HTTP_REQUEST_TIMEOUT or socket hang-up errors, and heap snapshots show thousands of unresolved listeners pinned to the process event loop.
The problem: signals that outlive the work
The modern fetch implementation in Node 18+ accepts an AbortSignal. Developers frequently reach for AbortSignal.timeout(ms) or combine external cancellations with timeout signals via AbortSignal.any().
The breakdown happens when you queue these jobs using concurrency pools (like processing 500 items, 5 at a time) or when you chain external operations. The signal created by AbortSignal.timeout() schedules an internal timer on the Node libuv event loop. If your task finishes early, that timer stays active until the full millisecond duration expires unless you clean it up or allow garbage collection to sever the reference. Worse, if you link a persistent signal to an operation using signal.addEventListener('abort', ...), you attach an uncollected reference to an object that lives as long as the parent runner.
Here is the common pattern that leaks memory and pins sockets under load:
javascript// bad-batch.mjs
import { setTimeout as sleep } from 'node:timers/promises';
async function fetchWithPool(urls, concurrency = 5, timeoutMs = 30000) {
const results = [];
let index = 0;
async function worker() {
while (index < urls.length) {
const currentIndex = index++;
const url = urls[currentIndex];
// A 30s timer is instantiated for every task immediately upon worker acquisition.
// If the fetch takes 50ms, this timeout object and its callbacks remain in memory
// for another 29.95 seconds.
const signal = AbortSignal.timeout(timeoutMs);
try {
const res = await fetch(url, { signal });
results[currentIndex] = await res.json();
} catch (err) {
results[currentIndex] = { error: err.message };
}
}
}
const workers = Array.from({ length: concurrency }, () => worker());
await Promise.all(workers);
return results;
}
If you process 10,000 requests at a concurrency of 10, you do not have 10 timers running. You quickly accumulate hundreds or thousands of live timer handles on the event loop because the loop completes tasks faster than the 30-second window expires.
Run a script like this with node --trace-gc or check process._getActiveHandles().length, and you will see the active handle count scale with the number of processed requests rather than your concurrency cap.
text[11:42:01.102] Processing items... Active handles: 12
[11:42:05.340] Processed 100 items... Active handles: 108
[11:42:10.892] Processed 500 items... Active handles: 504
[11:42:20.115] Processed 1200 items... Active handles: 1198
node:internal/process/promises:391
triggerUncaughtException(err, true /* fromPromise */);
^
DOMException [TimeoutError]: The operation was aborted due to timeout
The process is spending memory keeping timer objects alive. Even more dangerous: if an unhandled rejection occurs inside one worker, other active sockets do not abort immediately. They hang until their independent timers trigger.
The fix: manual AbortController with explicit timer clearing
AbortSignal.timeout() is convenient for one-off CLI scripts, but long-lived batch loops and production servers require deterministic lifetime management. You must manage the timeout with a native setTimeout whose handle can be cancelled inside a finally block via clearTimeout.
Here is the production-grade implementation for managing pooled requests with absolute cancellation control and zero timer lingering.
javascript// safe-batch.mjs
import { EventEmitter } from 'node:events';
/**
* Executes an async task with a strict timeout and guaranteed resource cleanup.
* @template T
* @param {(signal: AbortSignal) => Promise<T>} taskFn
* @param {number} timeoutMs
* @param {AbortSignal} [parentSignal]
* @returns {Promise<T>}
*/
export async function runWithTimeout(taskFn, timeoutMs, parentSignal) {
// If the parent job already aborted, exit before doing any work
if (parentSignal?.aborted) {
throw parentSignal.reason ?? new Error('Operation aborted');
}
const controller = new AbortController();
let timerId = null;
// Propagate cancellation from an external parent context if provided
const onParentAbort = () => {
controller.abort(parentSignal.reason);
};
if (parentSignal) {
parentSignal.addEventListener('abort', onParentAbort, { once: true });
}
// Set the fallback timer
timerId = setTimeout(() => {
controller.abort(new DOMException('Request timed out', 'TimeoutError'));
}, timeoutMs);
try {
return await taskFn(controller.signal);
} finally {
// 1. Clear the timer immediately so libuv drops the event handle
if (timerId !== null) {
clearTimeout(timerId);
}
// 2. Remove the listener to avoid memory pinning on long-running parent signals
if (parentSignal) {
parentSignal.removeEventListener('abort', onParentAbort);
}
}
}
Notice the pattern: clearTimeout(timerId) is inside finally. Whether the network call resolves, rejects with a 500 error, or throws a DNS lookup error, the timer stops taking up memory immediately.
Now wrap this cleanly inside a worker-based concurrency queue:
javascript// queue-runner.mjs
import { runWithTimeout } from './safe-batch.mjs';
/**
* Runs tasks over an array of items with bounded concurrency and explicit timeouts.
* @template T, R
* @param {T[]} items
* @param {number} concurrency
* @param {number} itemTimeoutMs
* @param {(item: T, signal: AbortSignal) => Promise<R>} workerFn
* @returns {Promise<R[]>}
*/
export async function mapConcurrent(items, concurrency, itemTimeoutMs, workerFn) {
const results = new Array(items.length);
let currentIndex = 0;
// Master controller to kill all remaining operations if needed
const masterController = new AbortController();
async function worker() {
while (currentIndex < items.length) {
if (masterController.signal.aborted) {
return;
}
const index = currentIndex++;
const item = items[index];
try {
results[index] = await runWithTimeout(
(signal) => workerFn(item, signal),
itemTimeoutMs,
masterController.signal
);
} catch (err) {
results[index] = { error: err };
// If an unexpected, fatal error occurs (like an authentication failure),
// you can call masterController.abort() here to drain workers cleanly.
}
}
}
const workers = Array.from(
{ length: Math.min(concurrency, items.length) },
() => worker()
);
await Promise.all(workers);
return results;
}
To use it across standard fetch tasks:
javascript// run.mjs
import { mapConcurrent } from './queue-runner.mjs';
const urls = Array.from({ length: 1000 }, (_, i) => `https://httpbin.org/delay/1?id=${i}`);
const data = await mapConcurrent(urls, 10, 3000, async (url, signal) => {
const res = await fetch(url, { signal });
if (!res.ok) {
throw new Error(`HTTP ${res.status}`);
}
return res.json();
});
console.log(`Processed ${data.length} requests successfully.`);
Verifying active handle counts
You can verify that your Node process is freeing timer handles properly by inspecting internal handles directly during runtime. Run this diagnostic loop in your entry point:
javascript// debug-handles.mjs
setInterval(() => {
const handles = process._getActiveHandles();
const requests = process._getActiveRequests();
console.log(`Active handles: ${handles.length} | Active async requests: ${requests.length}`);
}, 1000).unref();
With the fixed implementation, the active handles remain flat, pegged roughly to your pool size plus your open debug handles:
textActive handles: 12 | Active async requests: 10
Active handles: 12 | Active async requests: 10
Active handles: 12 | Active async requests: 10
Processed 1000 requests successfully.
If you switch back to AbortSignal.timeout(), the handle count will scale linear to your request volume until items pass their timeout durations.
Edge case 1: AbortSignal.any() listener leaks
Node 20 added AbortSignal.any([signalA, signalB]). It returns an AbortSignal that triggers if any input signal fires. It makes composition simple, but it carries a severe trap when mixing long-lived signals with short-lived ones.
javascript// Leaky implementation with AbortSignal.any()
async function fetchItem(url, parentSignal) {
// If parentSignal lives for the entire application (e.g. an app-level shutdown signal),
// AbortSignal.any adds listeners to parentSignal that CANNOT be garbage collected
// until parentSignal itself is garbage collected.
const timeoutSignal = AbortSignal.timeout(5000);
const combinedSignal = AbortSignal.any([parentSignal, timeoutSignal]);
return fetch(url, { signal: combinedSignal });
}
If your application handles 200,000 requests across its lifetime, and all of them compose against an application-level shutdownSignal, that root signal accumulates 200,000 listeners. Node will warn you:
text(node:48123) MaxListenersExceededWarning: Possible EventEmitter memory leak detected.
11 abort listeners added to [AbortSignal]. Use emitter.setMaxListeners() to increase limit
Do not increase setMaxListeners. Instead, avoid AbortSignal.any() when passing long-lived parent signals into short-lived tasks. Stick to the runWithTimeout pattern shown earlier, which registers an abort listener on the parent and removes that exact listener within finally.
Edge case 2: Unconsumed response bodies on aborted requests
Aborting a fetch stops incoming bytes on the network layer, but how you handle the rejection changes whether Node destroys the underlying socket or leaves it in limbo.
If you abort while headers are arriving, Node rejects the fetch promise immediately with an AbortError. If you abort while the body is streaming, and you catch the error without calling response.body.cancel(), the underlying undici connection can stall before it returns to the connection pool.
javascriptlet response;
try {
response = await fetch(url, { signal });
const data = await response.json();
return data;
} catch (err) {
if (response && response.body && !response.body.locked) {
// Ensure the stream is drained and the underlying socket closed or pooled
await response.body.cancel().catch(() => {});
}
throw err;
}
If your network pipeline parses streams or buffers large responses, always issue cancel() on the readable stream in the event of an abort. Leaving a stream unconsumed prevents Node’s HTTP agent from reusing that socket for subsequent requests in the queue, forcing unnecessary TCP handshakes and triggering socket exhaustion.