Course outline

Node.js / Advanced: reliable Node.js services / Lesson 21

Bound asynchronous batch concurrency

Limit concurrent asynchronous work while preserving result order and explicitly handling failure and resource ownership.

About 19 min read20 worked examples20 practice exercisesContent reviewed
On this page

Lesson goals

  • Distinguish concurrency limits from sequential execution.
  • Preserve input-to-result correspondence.
  • Test limits, failures, and outstanding work.
  • Bound active asynchronous work and preserve input-to-result correspondence.
  • Specify and test failure, cancellation, queue capacity and resource ownership.

Set a resource budget

Launching every item at once can overload a remote service, exhaust connections, or allocate too much memory. Sequential processing avoids overlap but can underuse available capacity. A concurrency limit provides a deliberate upper bound on active operations. Choose the limit from measured service and client constraints, not from a universal constant, and also bound input size and queue growth when work arrives continuously.

Implement bounded workers

The function creates at most limit worker loops. Each loop claims the next index before awaiting work, and writes its result at that index. In this single JavaScript execution context the synchronous index claim completes before the next await; this is not a shared-memory worker-thread algorithm. An invalid limit is rejected. Empty input returns an empty array without starting a worker. The example assumes work is an asynchronous function.

javascript Limit active asynchronous workers
async function mapLimit(items, limit, work) {
  if (!Number.isInteger(limit) || limit < 1) throw new RangeError("invalid limit");
  const results = new Array(items.length);
  let next = 0;
  async function worker() {
    while (next < items.length) {
      const index = next++;
      results[index] = await work(items[index]);
    }
  }
  await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
  return results;
}

Each worker claims one index at a time; results are stored at the matching input index.

Preserve result correspondence

Workers can complete in a different order from input, but storing by claimed index preserves the returned array’s input order. The second block calls the function with three synthetic values and a limit of two. Put both blocks in the same Node program. Result order does not establish the order of side effects inside work; operations that must be serialized need a different contract.

javascript Map a small batch
mapLimit([1, 2, 3], 2, async value => value * 2)
  .then(result => console.log(result))
  .catch(error => { console.error(error.message); process.exitCode = 1; });

The returned array corresponds to the original order even if work completes out of order.

Own failures and cancellation

Promise.all rejects when a worker rejects, but it does not cancel the other worker loops. Consequently other claimed or later work may still run after the caller sees failure in this teaching implementation. A production design must define whether to stop claiming new items, propagate an AbortSignal to cooperative work, and wait for owned operations to settle before releasing resources. Cancellation cannot guarantee a remote write was reversed.

Measure and verify

Use a controlled work function that increments an active counter at start and decrements it in finally. Hold completions until the test releases them, then assert that the maximum active count never exceeds the limit and that output remains in input order. Test empty input, limit one, an invalid limit, and a rejection while another operation is active. Verify the documented failure and cleanup behavior instead of assuming rejection cancels every operation.

Choose a bounded workload

Launching a promise for every input at once can exhaust a connection pool, overload a dependency or retain too much memory. Running everything sequentially bounds active work to one but may leave useful capacity idle. Choose a concurrency limit from measured client and service constraints, including rate limits, connection pools and memory. A limit on active work does not automatically bound an incoming queue or the input array itself.

Define whether the limit counts started operations, waiting tasks or worker loops. Reject a nonpositive or noninteger limit before starting work. An empty batch should return an empty result without invoking its work function. Test with controlled operations rather than relying on short timers or assuming a particular machine schedules work at a fixed speed.

Claim indexes before awaiting

A worker loop can claim the next input index synchronously, await one operation, then claim another. In a single JavaScript execution context, the claim happens before that worker yields at await, so other loops observe the updated index. This is not a shared-memory worker-thread algorithm; shared threads require their own synchronization. Start at most the lesser of the limit and the number of items.

Each worker owns at most one pending operation in this design. A limit of two permits up to two active calls, not necessarily two at every moment; an empty input starts none. A limit of one gives sequential work in input order. Verify the actual maximum with a counter incremented at start and decremented in finally, using gates to hold operations until the test releases them.

Preserve correspondence separately from effects

Completion order can differ from input order when operations overlap. Store each result at its claimed input index, rather than pushing results when they finish. For inputs a and b, b may complete first while the returned array still has the result for a at index zero. Tests should deliberately complete operations in reverse order and check both the completion events and the final array.

An ordered result array does not establish the order of external writes or other side effects inside the work function. If a later operation depends on an earlier write, serialize that dependency or design a stronger protocol. Stable identifiers can help associate results with inputs, but duplicate identifiers require their own policy. Separate result ordering from effect ordering in the public contract.

Own failure and cancellation

Promise.all rejects when an input promise rejects; it does not cancel other promises. In the basic teaching worker loop, another worker may continue its current operation and even claim later items after the caller has observed a rejection. Do not release shared resources merely because the first error was reported while owned work is still running. Define whether failure stops new claims and how the caller observes outstanding work.

A stronger policy can set a stop flag on failure, signal cooperative work with AbortController and await settlement of all workers before cleanup. Already-started operations may finish despite the signal, and aborting a client request cannot guarantee reversal of a remote write. Preserve the original failure while making cleanup failures observable according to the documented contract. Test rejection while another operation is held active.

Test limits and cleanup with controlled gates

Instrument the work function: increment active when it starts, update the maximum, and decrement active in finally even when it rejects or aborts. Hold work with explicit deferred promises so the test can assert the number started before allowing completion. Release gates in a deliberate order, then verify the maximum never exceeds the limit and the results correspond to input indexes.

Cover empty input, a limit of one, invalid zero or fractional limits, a limit larger than the batch, and failure while another task is active. Check that no new work starts after a stop-claiming policy takes effect and that all owned operations settle before resources close. For continuous arrivals, add an independent queue capacity and an overload response; a bounded worker count alone cannot prevent unbounded waiting memory.

20 worked examples

1. Validate a zero limit

Problem: Reject zero before launching a worker.

  1. Zero fails the positive integer rule, so the batch must reject the limit before starting work.
  2. A zero limit would create no worker capable of processing a nonempty batch, so validation rejects it rather than leaving work unstarted.
javascript Validate a zero limit
const limit = 0;
console.log(Number.isInteger(limit) && limit >= 1);
Expected output
false

Why this result follows: Zero fails the positive integer rule, so the batch must reject the limit before starting work.

2. Validate a fractional limit

Problem: Reject a limit of 1.5.

  1. A fractional value is not an integer even though it is positive, so it is not a valid worker count.
  2. Worker loops are discrete units; accepting 1.5 would leave the number of loops ambiguous and violate the integer contract.
javascript Validate a fractional limit
const limit = 1.5;
console.log(Number.isInteger(limit) && limit >= 1);
Expected output
false

Why this result follows: A fractional value is not an integer even though it is positive, so it is not a valid worker count.

3. Bound worker creation

Problem: Choose the worker count for five items and a limit of two.

  1. The lesser of the five inputs and limit two is two, so at most two worker loops are created.
  2. Two worker loops each await one operation at a time, so the configured limit bounds simultaneous work even though five items remain to process.
javascript Bound worker creation
console.log(Math.min(5, 2));
Expected output
2

Why this result follows: The lesser of the five inputs and limit two is two, so at most two worker loops are created.

4. Handle an empty batch

Problem: Choose the worker count for no items and limit three.

  1. The empty batch needs no workers and should return an empty result without calling work.
  2. Taking the minimum with zero yields no loops, which prevents the supplied work function from being invoked for a nonexistent item.
javascript Handle an empty batch
console.log(Math.min(0, 3));
Expected output
0

Why this result follows: The empty batch needs no workers and should return an empty result without calling work.

5. Preserve indexes on reverse completion

Problem: Store b before a but return values in input order.

  1. Writing to each claimed index preserves a then b in the array even though b completed first.
  2. The array positions represent input identity, not completion time, so assigning index one first cannot move B ahead of A.
javascript Preserve indexes on reverse completion
const result = new Array(2);
result[1] = "B";
result[0] = "A";
console.log(result.join(","));
Expected output
A,B

Why this result follows: Writing to each claimed index preserves a then b in the array even though b completed first.

6. Run a bounded mapper

Problem: Map three values with two worker loops and preserve their positions.

  1. The workers claim distinct indexes before awaiting and place doubled values at their original positions.
  2. The shared next counter advances synchronously before either worker awaits, and each computed value is written back to the index that worker claimed.
javascript Run a bounded mapper
async function mapLimit(items, limit, work) {
  const result = new Array(items.length); let next = 0;
  async function worker() { while (next < items.length) { const i = next++; result[i] = await work(items[i]); } }
  await Promise.all(Array.from({length: Math.min(limit, items.length)}, worker)); return result;
}
console.log((await mapLimit([1, 2, 3], 2, async x => x * 2)).join(","));
Expected output
2,4,6

Why this result follows: The workers claim distinct indexes before awaiting and place doubled values at their original positions.

7. Observe a controlled active limit

Problem: Start two held calls and verify the maximum active count.

  1. Both calls remain active at the gate, then finally decrements each count after the gate is released.
  2. The unresolved gate prevents either call from decrementing active before the first log, and releasing it permits both finally blocks to run.
javascript Observe a controlled active limit
let active = 0, max = 0;
let release; const gate = new Promise(resolve => { release = resolve; });
async function work() { active++; max = Math.max(max, active); try { await gate; } finally { active--; } }
const calls = [work(), work()];
console.log(active, max);
release(); await Promise.all(calls);
console.log(active);
Expected output
2 2
0

Why this result follows: Both calls remain active at the gate, then finally decrements each count after the gate is released.

8. Release work in reverse order

Problem: Complete b before a while storing results by input index.

  1. The b gate is released first, but writing each value to its original index returns A before B.
  2. Releasing b resolves its promise first and records its completion; the separate indexed assignments preserve the input-to-result correspondence.
javascript Release work in reverse order
let a, b;
const pa = new Promise(resolve => { a = resolve; });
const pb = new Promise(resolve => { b = resolve; });
const result = []; const events = [];
const tasks = [pa.then(v => { events.push("a"); result[0] = v; }), pb.then(v => { events.push("b"); result[1] = v; })];
b("B"); await pb; await Promise.resolve(); a("A"); await Promise.all(tasks);
console.log(events.join(","), result.join(","));
Expected output
b,a A,B

Why this result follows: The b gate is released first, but writing each value to its original index returns A before B.

9. Observe Promise.all rejection

Problem: Show that a second promise can finish after the aggregate rejects.

  1. The aggregate rejects on the first failure, but it does not cancel the separately held promise.
  2. Rejecting the aggregate reports the error without changing the later promise, whose resolver can still fulfill it afterward.
javascript Observe Promise.all rejection
let finish; const later = new Promise(resolve => { finish = resolve; });
const combined = Promise.all([Promise.reject(new Error("failed")), later]);
try { await combined; } catch (error) { console.log(error.message); }
finish("done");
console.log(await later);
Expected output
failed
done

Why this result follows: The aggregate rejects on the first failure, but it does not cancel the separately held promise.

10. Stop claiming after failure

Problem: Set a stop flag before another claim.

  1. The stop flag prevents incrementing the next index, so this guard does not claim another item.
  2. The guard checks stopped before advancing next, leaving index one available but unclaimed after the failure policy activates.
javascript Stop claiming after failure
let stopped = false; let next = 1;
stopped = true;
if (!stopped) next++;
console.log(next);
Expected output
1

Why this result follows: The stop flag prevents incrementing the next index, so this guard does not claim another item.

11. Signal cooperative cancellation

Problem: Notify a work function through an AbortSignal.

  1. Aborting the controller marks its signal aborted; a work function must cooperate by observing that signal.
  2. The signal exposes the cancellation state to work that chooses to observe it; changing the signal alone does not undo an external effect.
javascript Signal cooperative cancellation
const controller = new AbortController();
controller.abort();
console.log(controller.signal.aborted);
Expected output
true

Why this result follows: Aborting the controller marks its signal aborted; a work function must cooperate by observing that signal.

12. Wait for all owned outcomes

Problem: Observe both a rejection and a fulfilled held operation.

  1. allSettled waits for both promises and records each outcome instead of returning on the first rejection.
  2. The aggregate completes only after each input settles, making both the failed and successful operation available for cleanup decisions.
javascript Wait for all owned outcomes
const outcomes = await Promise.allSettled([Promise.reject(new Error("x")), Promise.resolve("ok")]);
console.log(outcomes.map(x => x.status).join(","));
Expected output
rejected,fulfilled

Why this result follows: allSettled waits for both promises and records each outcome instead of returning on the first rejection.

13. Decrement active on failure

Problem: Use finally to release a counter when work throws.

  1. The finally block decrements active while the error propagates, so the observed counter returns to zero.
  2. The thrown error enters finally before reaching catch, ensuring the counter is released even on the exceptional path.
javascript Decrement active on failure
let active = 0;
try { active++; try { throw new Error("failed"); } finally { active--; } }
catch (error) { console.log(error.message, active); }
Expected output
failed 0

Why this result follows: The finally block decrements active while the error propagates, so the observed counter returns to zero.

14. Bound the waiting queue separately

Problem: Reject an arrival when two waiting slots are full.

  1. The waiting queue has reached its separate capacity, so c is rejected without increasing its length.
  2. The capacity check occurs before insertion, so a full queue neither accepts c nor retains an additional waiting item.
javascript Bound the waiting queue separately
const queue = ["a", "b"];
const capacity = 2;
const accepted = queue.length < capacity;
if (accepted) queue.push("c");
console.log(accepted, queue.length);
Expected output
false 2

Why this result follows: The waiting queue has reached its separate capacity, so c is rejected without increasing its length.

15. Run a sequential batch

Problem: Use a loop that awaits each work call before the next.

  1. The loop awaits completion of a before starting b, giving sequential side-effect order in this example.
  2. The await inside the loop prevents the next start event until the prior operation completes, unlike parallel indexed result placement.
javascript Run a sequential batch
const events = [];
for (const item of ["a", "b"]) { events.push(`start-${item}`); await Promise.resolve(); events.push(`end-${item}`); }
console.log(events.join(","));
Expected output
start-a,end-a,start-b,end-b

Why this result follows: The loop awaits completion of a before starting b, giving sequential side-effect order in this example.

16. Cap workers at batch size

Problem: Choose workers for two inputs with limit five.

  1. Only two items exist, so creating more than two worker loops provides no additional item to claim.
  2. The minimum avoids idle worker loops when the input has fewer elements than the permitted concurrency.
javascript Cap workers at batch size
console.log(Math.min(2, 5));
Expected output
2

Why this result follows: Only two items exist, so creating more than two worker loops provides no additional item to claim.

17. Check input-result correspondence

Problem: Place transformed values at indexes claimed in a different order.

  1. Although claims are processed in the order c, a, b, assignment by input index yields A, B, C.
  2. Each value uses the same index for reading input and writing output, so the order of processing indexes does not change correspondence.
javascript Check input-result correspondence
const inputs = ["a", "b", "c"];
const result = new Array(inputs.length);
for (const index of [2, 0, 1]) result[index] = inputs[index].toUpperCase();
console.log(result.join(","));
Expected output
A,B,C

Why this result follows: Although claims are processed in the order c, a, b, assignment by input index yields A, B, C.

18. Avoid a duplicate index claim

Problem: Advance the next index synchronously before any await.

  1. Each synchronous increment advances next before the following claim in this single execution context.
  2. In one JavaScript execution context each postfix increment completes before a later synchronous claim, assigning two distinct indexes.
javascript Avoid a duplicate index claim
let next = 0;
const first = next++;
const second = next++;
console.log(first, second);
Expected output
0 1

Why this result follows: Each synchronous increment advances next before the following claim in this single execution context.

19. Retain the original error

Problem: Keep the work failure when cleanup also reports a problem.

  1. The two errors remain distinguishable so the policy can preserve the work failure and report cleanup failure.
  2. Keeping separate error objects lets the caller identify the primary failure and also record that resource cleanup failed.
javascript Retain the original error
const workError = new Error("work failed");
const cleanupError = new Error("cleanup failed");
console.log(workError.message, cleanupError.message);
Expected output
work failed cleanup failed

Why this result follows: The two errors remain distinguishable so the policy can preserve the work failure and report cleanup failure.

20. Check a positive integer limit

Problem: Accept a limit of three for a bounded worker pool.

  1. Three is an integer and at least one, so it satisfies the stated worker-limit contract.
  2. An integer limit of three can create three whole worker loops, subject to the separate cap imposed by batch size.
javascript Check a positive integer limit
const limit = 3;
console.log(Number.isInteger(limit) && limit >= 1);
Expected output
true

Why this result follows: Three is an integer and at least one, so it satisfies the stated worker-limit contract.

Common errors and fixes

A batch overwhelms the service

Why it happens
All operations were launched without an active-work limit.
How to fix it
Introduce a bounded pool and choose its size from measured constraints.
Prevent it next time
Load-test with realistic latency and enforce queue limits.

Results are assigned to the wrong input

Why it happens
Results were appended in completion order rather than stored by input index.
How to fix it
Associate every result with its claimed index or stable identifier.
Prevent it next time
Complete test operations in reverse order and check correspondence.

A rejected batch is assumed to have cancelled all work

Why it happens
Promise.all rejection does not stop the other promises.
How to fix it
Define cancellation, stop-claiming, and settlement behavior for owned work.
Prevent it next time
Test a rejection while another operation remains active.

20 practice exercises

1. With five items and limit two, how many work calls can be active at once?

Show hint

Each worker awaits its current call before claiming another.

Show worked solution

At most two calls are active in this implementation, because each of two workers awaits its current call before claiming another. The actual overlap depends on when each call settles.

With five items and limit two, at most two work calls can be active simultaneously. Actual overlap may be lower if a call settles before another begins; verify the maximum with controlled gates.

Check your solution

  • The maximum active count is two.
  • The limit does not guarantee constant overlap.

2. Does output order prove remote writes happened in order?

Show hint

Separate indexed result placement from external side effects.

Show worked solution

No. The array is ordered by input index, while the work calls can overlap and finish in any order. If writes require ordering, serialize the dependent operations and test their actual side effects.

No. Results are stored by input index even when work overlaps, so remote writes can happen in a different order. Serialize dependent writes or define another ordering protocol and test the actual effects.

Check your solution

  • Ordered output is not taken as proof of ordered writes.
  • Dependent side effects have an explicit ordering policy.

3. A batch has six items and limit three. What is the maximum active work count?

Show hint

Each worker awaits one call.

Show worked solution

At most three calls can be active at once because three workers each own one pending call. Actual overlap may be lower depending on when calls settle.

Check your solution

  • Maximum active work is three
  • Each worker owns at most one pending call

4. A batch has two items and limit five. How many workers are needed?

Show hint

Use the lesser of items and limit.

Show worked solution

Two worker loops are sufficient because only two items can be claimed. The configured limit remains five, but it does not require creating workers with no work.

Check your solution

  • Two workers are created
  • The limit is an upper bound

5. An empty batch has limit four. How many calls to work should occur?

Show hint

There are no items to claim.

Show worked solution

No worker needs to start and work is called zero times. Return an empty array and test that the supplied work function was never invoked.

Check your solution

  • The result is an empty array
  • The work call count is zero

6. The limit is zero. When should the mapper reject it?

Show hint

Validate before starting operations.

Show worked solution

Reject zero as an invalid positive integer before starting any work. Test that the work call count stays zero and the caller receives the documented error.

Check your solution

  • Zero is rejected
  • No work starts before rejection

7. The limit is 1.5. Why is it invalid?

Show hint

A worker count must be an integer.

Show worked solution

Although 1.5 is positive, it is not an integer and cannot specify a whole number of worker loops. Reject it before launching operations.

Check your solution

  • The fractional limit is rejected
  • No worker starts

8. With inputs a and b, b finishes before a. How can results remain [A, B]?

Show hint

Associate each result with its input index.

Show worked solution

Store B at index one and A at index zero. The completion events can be b then a while the final array still corresponds to the input order.

Check your solution

  • B is stored at index one
  • The final array is [A, B]

9. Two remote writes run concurrently and the returned array is ordered. Does that prove write order?

Show hint

Result placement and external side effects differ.

Show worked solution

No. The writes may have occurred in either order despite ordered result placement. Serialize dependent writes or use a stronger remote ordering contract and test the actual effects.

Check your solution

  • Ordered output does not prove effect order
  • Dependent writes receive an explicit ordering policy

10. Two workers are held at gates with limit two. What should an active counter show?

Show hint

Both calls have started but neither has settled.

Show worked solution

The active count and observed maximum should be two before release. After both settle, finally must reduce active to zero; no third call should start while both remain held.

Check your solution

  • Active and maximum are two before release
  • Active is zero after settlement

11. A work function throws after incrementing active. Where should it decrement?

Show hint

Cleanup belongs in finally.

Show worked solution

Decrement in a finally block so both successful and failing work release the active count. Assert that the error remains visible and the final count is zero.

Check your solution

  • The decrement runs in finally
  • The failure remains observable

12. One worker rejects while another is held. Does Promise.all cancel the held work?

Show hint

Aggregate rejection is not cancellation.

Show worked solution

No. Promise.all rejects but the held operation can continue until released or cooperatively aborted. Track and settle owned work before releasing resources it uses.

Check your solution

  • The held operation is not automatically cancelled
  • Owned work is settled before cleanup

13. A failure policy says stop claiming new items. How should a worker behave after the stop flag is set?

Show hint

Check the flag before claiming the next index.

Show worked solution

Do not claim a new index after observing the stop flag. Already claimed work needs its own cancellation and settlement policy; test a held operation and an unclaimed item.

Check your solution

  • No new index is claimed after the stop flag
  • Already claimed work is accounted for

14. An AbortSignal is set while a remote write is in flight. Is the remote write guaranteed undone?

Show hint

Cancellation requires cooperation and is not rollback.

Show worked solution

No. The remote service may already have committed the write, even if the client observes an abort. Use the operation’s idempotency and reconciliation contract to resolve uncertainty.

Check your solution

  • Abort is not treated as remote rollback
  • The uncertain effect has a reconciliation policy

15. Two worker promises reject and fulfill respectively. Which aggregate waits for both outcomes?

Show hint

Choose an API that collects every settlement.

Show worked solution

Promise.allSettled waits for both and reports each status. Inspect the rejected outcome and apply the documented error policy rather than treating settlement as success.

Check your solution

  • Both outcomes are observed
  • The rejection remains visible

16. A worker limit is two but an incoming queue grows to one million entries. Is memory bounded by the worker limit?

Show hint

Active and waiting work have separate bounds.

Show worked solution

No. The active limit does not bound waiting items or their retained data. Add queue capacity and a documented overload response, then test arrivals beyond that capacity.

Check your solution

  • The waiting queue is independently bounded
  • An overload response is defined

17. Three items use limit one. What ordering property does a single worker provide?

Show hint

The worker awaits its current call before claiming the next.

Show worked solution

In this implementation it starts the items sequentially in input order and waits for each before claiming the next. Verify the work function does not itself launch unowned side effects.

Check your solution

  • Only one call is active
  • The next item starts after the previous call settles

18. A worker claims next++ synchronously before await in one JavaScript context. Why do two claims differ?

Show hint

The index changes before the worker yields.

Show worked solution

Each synchronous claim increments next before another worker resumes at its own claim, producing different indexes. This reasoning does not establish safety for shared-memory worker threads.

Check your solution

  • The index advances before await
  • Shared-memory threads are not assumed safe

19. A work failure and a cleanup failure both occur. What should the policy preserve?

Show hint

Do not silently discard either outcome.

Show worked solution

Keep the original work failure identifiable and make the cleanup failure observable according to the contract. Test both errors and ensure remaining owned operations have settled.

Check your solution

  • The original failure is identifiable
  • The cleanup failure is reported

20. A test uses tiny timers to assume b always finishes before a. How can it become deterministic?

Show hint

Control completion with deferred gates.

Show worked solution

Hold both operations on separate promises, release b first and then a, and assert the completion events and indexed results. This avoids relying on scheduler timing.

Check your solution

  • Separate gates control the completion order
  • Both events and input-order results are checked

Key takeaways

  • Bound active work and retain a stable input-to-result mapping.
  • Define failure, cancellation, and cleanup separately from result ordering.
  • A worker limit bounds active work, not an independent waiting queue.
  • Input-ordered results do not prove side-effect order.
  • Promise.all rejection does not cancel outstanding work.

Official references