How do you implement a concurrency-limited asynchronous task runner (Parallel Worker Pool)?
In Simple Words:
A concurrency-limited task runner (asyncPool) processes a large collection of asynchronous tasks with an upper bound on simultaneous active executions (e.g. at most 3 requests concurrently), preserving the original result order without overloading servers or rate limits.
Why Concurrency Control is Essential
When making 500 API calls, running Promise.all(tasks.map(t => t())) launches 500 simultaneous socket connections, crashing Node.js with socket exhaustion or provoking HTTP 429 Too Many Requests errors. Sequential execution (for (const t of tasks) await t()) is too slow. A worker pool balances throughput and stability.
Complete Implementation
async function asyncPool(limit, tasks) {
const results = new Array(tasks.length);
const executing = new Set();
let currentIndex = 0;
async function enqueue() {
if (currentIndex >= tasks.length) {
return;
}
const index = currentIndex++;
const task = tasks[index];
// Wrap execution into a promise that cleans itself from active set on completion
const p = Promise.resolve().then(() => task());
results[index] = p; // Store promise in slot
executing.add(p);
const clean = () => executing.delete(p);
p.then(clean, clean);
// If active worker pool is saturated, wait for at least one worker to finish
let r = Promise.resolve();
if (executing.size >= limit) {
r = Promise.race(executing);
}
await r;
return enqueue();
}
// Launch initial batch of workers up to limit
const initialBatch = [];
while (currentIndex < limit && currentIndex < tasks.length) {
initialBatch.push(enqueue());
}
await Promise.all(initialBatch);
// Await all queued promises to resolve their final values
return Promise.all(results);
}
// Verification:
const delay = (ms, val) => () =>
new Promise((res) => {
console.log(`Starting: ${val} (Active: ${Date.now() % 10000}ms)`);
setTimeout(() => {
console.log(`Finished: ${val}`);
res(val);
}, ms);
});
const tasks = [
delay(300, 'Task 1'),
delay(100, 'Task 2'),
delay(200, 'Task 3'),
delay(150, 'Task 4'),
delay(50, 'Task 5')
];
// Run with concurrency limit of 2:
asyncPool(2, tasks).then((results) => {
console.log('All completed in order:', results);
// ['Task 1', 'Task 2', 'Task 3', 'Task 4', 'Task 5']
});