Worker pools and cancellation
Prerequisites: previous curriculum lessons on Node streams, HTTP, buffers and asynchronous errors. Local lab baseline: Node.js 22.16.0, Linux, ESM. Use a disposable directory. Static examples are not ByteMind interactive execution. Each example is independent; save the named files together and run node main.mjs. The author harness imposes a five-second process deadline.
How it works
Define maximum workers, maximum queued tasks, per-task deadline and a result/error protocol. If the queue is full, reject or apply backpressure instead of allowing unlimited waiting. Cooperative cancellation requires the worker to check a cancellation signal or shared flag at safe points; a CPU-bound loop cannot process ordinary cancellation messages until it yields. worker.terminate() stops a worker and is asynchronous; use it for an abandoned dedicated worker or replace a terminated pool worker. Termination can interrupt work, so it is not a graceful transaction rollback. Track cleanups and settle every pending promise exactly once.
Terminate a waiting worker and observe exit
import {Worker} from 'node:worker_threads';import {once} from 'node:events';const worker=new Worker(new URL('./worker.mjs',import.meta.url));try {await once(worker,'message');console.log('ready');await worker.terminate();console.log('terminated');}finally{await worker.terminate();}import {parentPort} from 'node:worker_threads';parentPort.on('message',()=>{});parentPort.postMessage('ready');Expected output:
readyterminatedA readiness message synchronizes the parent with a worker awaiting tasks. The parent waits for termination rather than merely abandoning a Promise.
Model bounded worker admission
const workerLimit=2,queueLimit=1;let active=0,queued=0;function submit(){if(active<workerLimit){active++;return 'start';}if(queued<queueLimit){queued++;return 'queue';}return 'reject';}function complete(){if(active===0)throw new Error('no active job');active--;if(queued>0){queued--;active++;}}console.log([submit(),submit(),submit(),submit()].join(' '));complete();console.log(active,queued);Expected output:
start start queue reject2 0This is a finite admission model, not an actual worker pool. Completion promotes one queued task while maintaining the concurrency bound.
Common mistakes
Do not implement timeouts only with Promise.race and forget the active worker. Do not silently drop tasks on shutdown or recreate failed workers without a restart budget.
Practice
Adjust the admission limit in the worksheet. State whether to reject the fourth task and what happens to an active task on shutdown.
Further reading
Official documentation: worker_threads. Internal reference candidate: node-worker-pools-and-cancellation-lookup (route not verified).
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Worker pools and cancellation — knowledge check
Apply the lesson to a fresh scenario and explain the resource or protocol boundary.
Does Promise.race with a timeout cancel an active worker?
What should a full bounded queue do?
Why await worker.terminate()?