How to Build an Async Concurrency Limiter (Task Pool) in JavaScript

Step-by-step guide to implementing an async concurrency limiter (promise pool) in JavaScript with clean code, queue execution, and optimal time complexity.

Pairlet Team•Published:

In production web applications, firing hundreds of concurrent HTTP requests simultaneously can overwhelm browser network pools or hit API rate limits. Building an Async Concurrency Limiter (Task Pool) is a classic senior live coding interview task.

Problem Statement

Write a function mapConcurrent(items, limit, asyncFn) that executes asyncFn for every item in items, ensuring at most limit promises execute concurrently.

Optimal Solution

JAVASCRIPT
async function mapConcurrent(items, limit, asyncFn) {
  const results = [];
  const executing = new Set();

  for (const [index, item] of items.entries()) {
    const p = Promise.resolve().then(() => asyncFn(item, index));
    results[index] = p;
    executing.add(p);

    const clean = () => executing.delete(p);
    p.then(clean, clean);

    if (executing.size >= limit) {
      await Promise.race(executing);
    }
  }

  return Promise.all(results);
}

Try this Problem Live on Pairlet

Practice the Concurrency Limiter coding challenge live in a collaborative interview session.
Practice Relevant Coding Problems
Practice Live Coding

Conduct Live Coding Interviews in the Browser

No candidate sign-up required. Create a room, share the link, and code together in real time with shared code execution.

Related Articles