Skip to the solution
MediumFrontend6 min read

Implement p-limit — concurrency limiter for async tasks

61 views

The problem

Problem, as an interviewer would state it: "Implement pLimit(concurrency) — it returns a function you wrap around any async task, guaranteeing no more than concurrency tasks are ever running at the same time, queueing the rest until a slot frees up."

Examples:

Code
const limit = pLimit(2);
await Promise.all([1,2,3,4,5].map(id => limit(() => doWork(id))));
// never more than 2 doWork() calls genuinely running at once

Clarifying questions expected:

  • Do queued (not-yet-started) tasks need to run in the order they were submitted?
  • Should a task that throws affect the limiter's ability to keep processing the rest of the queue?
  • Is there a way to inspect how many tasks are currently active or queued?

Code / implementation expected: Yes — real, direct proof with a live execution log that the number of simultaneously active tasks never exceeds the configured limit.

  • concurrency
  • p-limit
  • promises

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

6 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: with a concurrency limit of 2 and 5 real tasks queued, the maximum simultaneously active tasks measured is exactly 2

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 125 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextHard

JSON.stringify Polyfill

Continue