Something went wrong. Try again.
Offload functions to worker threads with shared memory primitives for Node.js.
Something went wrong. Try again.
1.3 kB · 38 lines
TypeScript
at main
123456789101112131415161718192021222324252627282930313233343536373839// Worker affinity via a custom balancer + isTask().//// Each worker keeps its own in-memory counter map. The keyAffinity balancer// uses isTask() to inspect a task's args and route by a consistent hash of// the key, so successive operations on the same key always hit the worker// that already has that key's state.//// Requires Node v24+.// Run: node examples/worker-affinity/main.ts
import { workers, roundRobin } from '../../src/index.ts';import type { Balancer } from '../../src/index.ts';import { increment, read } from './counter.ts';import { keyAffinity } from './key-affinity.ts';
const operations = [ ['a', 1], ['b', 1], ['a', 2], ['c', 1], ['b', 3], ['a', 1], ['c', 4], ['b', 1],] as const;const expected = { a: 4, b: 5, c: 5 };
async function demo(label: string, balance: Balancer) { using run = workers(4, { balance }); await run(operations.map(([k, n]) => increment(k, n))); const [a, b, c] = await run([read('a'), read('b'), read('c')]); const got = { a, b, c }; const ok = got.a === expected.a && got.b === expected.b && got.c === expected.c; console.log(`${label.padEnd(16)} got=${JSON.stringify(got)} ${ok ? 'OK' : 'WRONG (counts split across workers)'}`);}
await demo('round-robin', roundRobin());await demo('keyAffinity()', keyAffinity());