Offload functions to worker threads with shared memory primitives for Node.js.
1// Compare load balancing strategies with variable-cost work.
2// Requires Node v24+.
3//
4// Run: node examples/load-balancing/main.ts
5
6import { setTimeout } from 'node:timers/promises';
7import { workers, roundRobin, leastBusy } from '../../src/index.ts';
8import { Balancer, Runner, WorkerHandle, Task } from '../../src/index.ts';
9import { work } from './work.ts';
10
11// Lopsided task costs (ms) — round-robin assigns by position and
12// ignores how long each worker has been busy, so one worker gets
13// all the heavy items. Least-busy routes to whichever worker has
14// fewer in-flight tasks, spreading the load more evenly.
15const tasks = [300, 30, 300, 30, 300, 30];
16
17async function bench(label: string, run: Runner): Promise<void> {
18 const promises: Promise<number>[] = [];
19 const start = performance.now();
20 for (const ms of tasks) {
21 promises.push(run(work(ms)));
22 // Small delay so short tasks can complete between dispatches,
23 // giving least-busy useful active-count information.
24 await setTimeout(40);
25 }
26 await Promise.all(promises);
27 const elapsed = (performance.now() - start).toFixed(0);
28 console.log(`${label}: ${elapsed}ms`);
29}
30
31{
32 using run = workers(2, { balance: roundRobin() });
33 await bench('Round-robin', run);
34}
35
36{
37 using run = workers(2, { balance: leastBusy() });
38 await bench('Least-busy', run);
39}