{"id":"6b093dddbd4755deb67ee052","slug":"async-task-pool","title":"Async task pool with a limit","summary":"Run thousands of async tasks, but no more than N at a time – as when downloading files or calling a rate-limited API. Promises, result order and stopping at the first error.","servedLang":"en","availableLangs":["pl","en"],"kind":"code","category":"algorithms","status":"published","difficulty":"medium","topics":[],"techs":["typescript","javascript"],"tags":["javascript","node","promises","async","concurrency","event-loop"],"languages":[{"lang":"typescript","runner":"browser","starter":"/**\n * Runs task functions with at most `limit` in flight; resolves to results in task order.\n * Rejects with the first error (and starts no new tasks), RangeError for an invalid limit.\n */\nfunction runWithLimit<T>(tasks: Array<() => T | Promise<T>>, limit: number): Promise<T[]> {\n  // TODO\n  return Promise.reject(new Error('Not implemented'));\n}\n","testCount":9,"tests":"function deferred() {\n  let resolve, reject;\n  const promise = new Promise((res, rej) => {\n    resolve = res;\n    reject = rej;\n  });\n  return { promise, resolve, reject };\n}\n\nconst tick = () => new Promise((resolve) => setTimeout(resolve, 0));\n\nfunction controlledTasks(n) {\n  const started = [];\n  const controls = Array.from({ length: n }, () => deferred());\n  const tasks = controls.map((d, i) => () => {\n    started.push(i);\n    return d.promise;\n  });\n  return { tasks, controls, started };\n}\n\ntest('results come in task order, not completion order', async () => {\n  const { tasks, controls } = controlledTasks(3);\n  const pool = runWithLimit(tasks, 3);\n  controls[2].resolve('c');\n  controls[0].resolve('a');\n  controls[1].resolve('b');\n  expect(await pool).toEqual(['a', 'b', 'c']);\n});\n\ntest('never more than `limit` tasks in flight', async () => {\n  let running = 0;\n  let maxRunning = 0;\n  const tasks = Array.from({ length: 20 }, (_, i) => async () => {\n    running++;\n    maxRunning = Math.max(maxRunning, running);\n    await new Promise((resolve) => setTimeout(resolve, (i * 7) % 5));\n    running--;\n    return i * i;\n  });\n  const results = await runWithLimit(tasks, 3);\n  expect(maxRunning).toBe(3);\n  expect(results).toEqual(Array.from({ length: 20 }, (_, i) => i * i));\n});\n\ntest('the next task starts as soon as a slot frees up', async () => {\n  const { tasks, controls, started } = controlledTasks(4);\n  const pool = runWithLimit(tasks, 2);\n  await tick();\n  expect(started).toEqual([0, 1]);\n  controls[1].resolve('B');\n  await tick();\n  expect(started).toEqual([0, 1, 2]);\n  controls[2].resolve('C');\n  await tick();\n  expect(started).toEqual([0, 1, 2, 3]);\n  controls[3].resolve('D');\n  controls[0].resolve('A');\n  expect(await pool).toEqual(['A', 'B', 'C', 'D']);\n});\n\ntest('empty task list and a limit larger than the list', async () => {\n  expect(await runWithLimit([], 5)).toEqual([]);\n  const { tasks, controls, started } = controlledTasks(3);\n  const pool = runWithLimit(tasks, 10);\n  await tick();\n  expect(started).toEqual([0, 1, 2]);\n  controls.forEach((d, i) => d.resolve(i));\n  expect(await pool).toEqual([0, 1, 2]);\n});\n\ntest('plain values and synchronous task functions work', async () => {\n  expect(await runWithLimit([() => 1, () => Promise.resolve(2), async () => 3], 2)).toEqual([1, 2, 3]);\n});\n\ntest('the first error rejects the pool and stops new tasks', async () => {\n  const { tasks, controls, started } = controlledTasks(4);\n  const pool = runWithLimit(tasks, 2);\n  await tick();\n  const boom = new Error('boom');\n  controls[1].reject(boom);\n  let caught = null;\n  try {\n    await pool;\n  } catch (e) {\n    caught = e;\n  }\n  expect(caught).toBe(boom);\n  controls[0].resolve('late');\n  await tick();\n  expect(started).toEqual([0, 1]);\n});\n\ntest('a task function that throws synchronously rejects the pool', async () => {\n  const error = new TypeError('bad task');\n  let caught = null;\n  try {\n    await runWithLimit([() => 1, () => { throw error; }, () => 3], 1);\n  } catch (e) {\n    caught = e;\n  }\n  expect(caught).toBe(error);\n});\n\ntest('invalid limit gives RangeError', async () => {\n  for (const limit of [0, -1, 1.5, NaN]) {\n    let caught = null;\n    try {\n      await runWithLimit([() => 1], limit);\n    } catch (e) {\n      caught = e;\n    }\n    expect(caught).toBeInstanceOf(RangeError);\n  }\n});\n\ntest('performance: 20 000 tasks with limit 50', async () => {\n  let running = 0;\n  let maxRunning = 0;\n  const tasks = Array.from({ length: 20000 }, (_, i) => () => {\n    running++;\n    maxRunning = Math.max(maxRunning, running);\n    return Promise.resolve(i).then((v) => {\n      running--;\n      return v;\n    });\n  });\n  const results = await runWithLimit(tasks, 50);\n  expect(results).toHaveLength(20000);\n  expect(results[19999]).toBe(19999);\n  expect(results.reduce((a, b) => a + b, 0)).toBe((19999 * 20000) / 2);\n  expect(maxRunning).toBeLessThanOrEqual(50);\n});\n"},{"lang":"javascript","runner":"browser","starter":"/**\n * Runs task functions with at most `limit` in flight; resolves to results in task order.\n * Rejects with the first error (and starts no new tasks), RangeError for an invalid limit.\n * @param {Array<() => any>} tasks\n * @param {number} limit\n * @returns {Promise<any[]>}\n */\nfunction runWithLimit(tasks, limit) {\n  // TODO\n  return Promise.reject(new Error('Not implemented'));\n}\n","testCount":9,"tests":"function deferred() {\n  let resolve, reject;\n  const promise = new Promise((res, rej) => {\n    resolve = res;\n    reject = rej;\n  });\n  return { promise, resolve, reject };\n}\n\nconst tick = () => new Promise((resolve) => setTimeout(resolve, 0));\n\nfunction controlledTasks(n) {\n  const started = [];\n  const controls = Array.from({ length: n }, () => deferred());\n  const tasks = controls.map((d, i) => () => {\n    started.push(i);\n    return d.promise;\n  });\n  return { tasks, controls, started };\n}\n\ntest('results come in task order, not completion order', async () => {\n  const { tasks, controls } = controlledTasks(3);\n  const pool = runWithLimit(tasks, 3);\n  controls[2].resolve('c');\n  controls[0].resolve('a');\n  controls[1].resolve('b');\n  expect(await pool).toEqual(['a', 'b', 'c']);\n});\n\ntest('never more than `limit` tasks in flight', async () => {\n  let running = 0;\n  let maxRunning = 0;\n  const tasks = Array.from({ length: 20 }, (_, i) => async () => {\n    running++;\n    maxRunning = Math.max(maxRunning, running);\n    await new Promise((resolve) => setTimeout(resolve, (i * 7) % 5));\n    running--;\n    return i * i;\n  });\n  const results = await runWithLimit(tasks, 3);\n  expect(maxRunning).toBe(3);\n  expect(results).toEqual(Array.from({ length: 20 }, (_, i) => i * i));\n});\n\ntest('the next task starts as soon as a slot frees up', async () => {\n  const { tasks, controls, started } = controlledTasks(4);\n  const pool = runWithLimit(tasks, 2);\n  await tick();\n  expect(started).toEqual([0, 1]);\n  controls[1].resolve('B');\n  await tick();\n  expect(started).toEqual([0, 1, 2]);\n  controls[2].resolve('C');\n  await tick();\n  expect(started).toEqual([0, 1, 2, 3]);\n  controls[3].resolve('D');\n  controls[0].resolve('A');\n  expect(await pool).toEqual(['A', 'B', 'C', 'D']);\n});\n\ntest('empty task list and a limit larger than the list', async () => {\n  expect(await runWithLimit([], 5)).toEqual([]);\n  const { tasks, controls, started } = controlledTasks(3);\n  const pool = runWithLimit(tasks, 10);\n  await tick();\n  expect(started).toEqual([0, 1, 2]);\n  controls.forEach((d, i) => d.resolve(i));\n  expect(await pool).toEqual([0, 1, 2]);\n});\n\ntest('plain values and synchronous task functions work', async () => {\n  expect(await runWithLimit([() => 1, () => Promise.resolve(2), async () => 3], 2)).toEqual([1, 2, 3]);\n});\n\ntest('the first error rejects the pool and stops new tasks', async () => {\n  const { tasks, controls, started } = controlledTasks(4);\n  const pool = runWithLimit(tasks, 2);\n  await tick();\n  const boom = new Error('boom');\n  controls[1].reject(boom);\n  let caught = null;\n  try {\n    await pool;\n  } catch (e) {\n    caught = e;\n  }\n  expect(caught).toBe(boom);\n  controls[0].resolve('late');\n  await tick();\n  expect(started).toEqual([0, 1]);\n});\n\ntest('a task function that throws synchronously rejects the pool', async () => {\n  const error = new TypeError('bad task');\n  let caught = null;\n  try {\n    await runWithLimit([() => 1, () => { throw error; }, () => 3], 1);\n  } catch (e) {\n    caught = e;\n  }\n  expect(caught).toBe(error);\n});\n\ntest('invalid limit gives RangeError', async () => {\n  for (const limit of [0, -1, 1.5, NaN]) {\n    let caught = null;\n    try {\n      await runWithLimit([() => 1], limit);\n    } catch (e) {\n      caught = e;\n    }\n    expect(caught).toBeInstanceOf(RangeError);\n  }\n});\n\ntest('performance: 20 000 tasks with limit 50', async () => {\n  let running = 0;\n  let maxRunning = 0;\n  const tasks = Array.from({ length: 20000 }, (_, i) => () => {\n    running++;\n    maxRunning = Math.max(maxRunning, running);\n    return Promise.resolve(i).then((v) => {\n      running--;\n      return v;\n    });\n  });\n  const results = await runWithLimit(tasks, 50);\n  expect(results).toHaveLength(20000);\n  expect(results[19999]).toBe(19999);\n  expect(results.reduce((a, b) => a + b, 0)).toBe((19999 * 20000) / 2);\n  expect(maxRunning).toBeLessThanOrEqual(50);\n});\n"}],"questionCount":null,"xp":20,"stats":{"attempts":0,"solves":0,"solutions":0,"comments":0},"solveRate":null,"publishedAt":"2026-11-27T08:22:53.138Z","requestedLang":"en","statement":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"A migration script has to call an external API for 20,000 records. "},{"type":"text","text":"Promise.all(records.map(call))","marks":[{"type":"code"}]},{"type":"text","text":" starts everything at once and the API answers 429 or falls over. We need a "},{"type":"text","text":"pool","marks":[{"type":"bold"}]},{"type":"text","text":" – at most "},{"type":"text","text":"limit","marks":[{"type":"code"}]},{"type":"text","text":" tasks in flight, with the next one starting as soon as a slot frees up. The task is about JavaScript/TypeScript (Node.js, browser) – promises and the event loop."}]},{"type":"heading","attrs":{"level":2,"id":"task"},"content":[{"type":"text","text":"Task"}]},{"type":"paragraph","content":[{"type":"text","text":"runWithLimit(tasks, limit)","marks":[{"type":"code"}]},{"type":"text","text":" – "},{"type":"text","text":"tasks","marks":[{"type":"code"}]},{"type":"text","text":" is an array of "},{"type":"text","text":"functions","marks":[{"type":"bold"}]},{"type":"text","text":" (not promises!), each returning a promise or a plain value when called. The function returns a promise that:"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"resolves to an array of results in "},{"type":"text","text":"task order","marks":[{"type":"bold"}]},{"type":"text","text":" (not completion order),"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"starts tasks in array order and never has more than "},{"type":"text","text":"limit","marks":[{"type":"code"}]},{"type":"text","text":" in flight,"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"starts the next task "},{"type":"text","text":"immediately","marks":[{"type":"bold"}]},{"type":"text","text":" when one finishes (without waiting for a whole \"batch\"),"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"on the first error (a rejected promise or an exception thrown by a task function) rejects with that error and "},{"type":"text","text":"starts no","marks":[{"type":"bold"}]},{"type":"text","text":" new tasks; running ones may finish, but their results are ignored,"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"resolves to "},{"type":"text","text":"[]","marks":[{"type":"code"}]},{"type":"text","text":" for an empty array,"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"rejects with a "},{"type":"text","text":"RangeError","marks":[{"type":"code"}]},{"type":"text","text":" when "},{"type":"text","text":"limit","marks":[{"type":"code"}]},{"type":"text","text":" is not a positive integer."}]}]}]},{"type":"heading","attrs":{"level":2,"id":"example"},"content":[{"type":"text","text":"Example"}]},{"type":"paragraph","content":[{"type":"text","text":"limit = 2","marks":[{"type":"code"}]},{"type":"text","text":", tasks take: A – 300 ms, B – 100 ms, C – 100 ms, D – 50 ms:"}]},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Time [ms]"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Event"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"0"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"A and B start"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"100"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"B ends → C starts"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"200"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"C ends → D starts"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"250"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"D ends"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"300"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"A ends → result "},{"type":"text","text":"[A, B, C, D]","marks":[{"type":"code"}]}]}]}]}]},{"type":"heading","attrs":{"level":2,"id":"constraints"},"content":[{"type":"text","text":"Constraints"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Up to 20,000 tasks, "},{"type":"text","text":"1 ≤ limit ≤ 1,000","marks":[{"type":"code"}]},{"type":"text","text":"."}]}]}]},{"type":"heading","attrs":{"level":2,"id":"expected-complexity"},"content":[{"type":"text","text":"Expected complexity"}]},{"type":"paragraph","content":[{"type":"text","text":"Pool overhead "},{"type":"text","text":"O(n)","marks":[{"type":"bold"}]},{"type":"text","text":" time and "},{"type":"text","text":"O(n)","marks":[{"type":"bold"}]},{"type":"text","text":" memory (for results); no sorting and no "},{"type":"text","text":"shift()","marks":[{"type":"code"}]},{"type":"text","text":" in a loop."}]}]},"hints":[],"hintsCount":3,"quiz":null,"solutionNotes":null,"unlocked":false,"external":[{"provider":"leetcode","url":"https://leetcode.com/problems/promise-pool/","title":"LeetCode 2636 – Promise Pool","difficulty":null}],"articles":[],"topicsInfo":[],"author":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","community":false},"capabilities":{"judge0":false,"aiReview":false},"createdAt":"2026-11-27T08:22:53.147Z","updatedAt":"2026-11-27T08:22:53.147Z"}