// Compare load balancing strategies with variable-cost work. // Requires Node v24+. // // Run: node examples/load-balancing/main.ts import { setTimeout } from 'node:timers/promises'; import { workers, roundRobin, leastBusy } from '../../src/index.ts'; import { Balancer, Runner, WorkerHandle, Task } from '../../src/index.ts'; import { work } from './work.ts'; // Lopsided task costs (ms) — round-robin assigns by position and // ignores how long each worker has been busy, so one worker gets // all the heavy items. Least-busy routes to whichever worker has // fewer in-flight tasks, spreading the load more evenly. const tasks = [300, 30, 300, 30, 300, 30]; async function bench(label: string, run: Runner): Promise { const promises: Promise[] = []; const start = performance.now(); for (const ms of tasks) { promises.push(run(work(ms))); // Small delay so short tasks can complete between dispatches, // giving least-busy useful active-count information. await setTimeout(40); } await Promise.all(promises); const elapsed = (performance.now() - start).toFixed(0); console.log(`${label}: ${elapsed}ms`); } { using run = workers(2, { balance: roundRobin() }); await bench('Round-robin', run); } { using run = workers(2, { balance: leastBusy() }); await bench('Least-busy', run); }