A naive implementation creates one worker for every batch or posts thousands of jobs immediately. Both approaches admit work without a resource budget. Our scheduler keeps at most one active job per worker and creates the next batch only when a worker becomes free. Pending work is represented by an index, rather than by thousands of preallocated buffers. This is backpressure: production follows consumption capacity.
The pool below is a complete, intentionally small coordinator for one run. It expects makeBatch(id) to return a fresh Uint32Array. It checks request identity, bounds worker count, settles once, cleans up all workers, and puts a timeout on each dispatched batch. A production reusable pool can retain workers between runs, but then it must add generation IDs and an explicit reset protocol.
export function runPool({ batchCount, makeBatch, size = 2, signal }) {
if (!Number.isInteger(batchCount) || batchCount < 0) {
return Promise.reject(new RangeError("Invalid batch count"));
}
if (!Number.isInteger(size) || size < 1 || size > 8) {
return Promise.reject(new RangeError("Pool size must be from 1 to 8"));
}
return new Promise((resolve, reject) => {
const slots = [];
const partials = new Array(batchCount);
let next = 0;
let completed = 0;
let settled = false;
function finish(error, result) {
if (settled) return;
settled = true;
signal?.removeEventListener("abort", abort);
for (const slot of slots) {
clearTimeout(slot.timer);
slot.worker.terminate();
}
if (error !== null) reject(error);
else resolve(result);
}
function abort() {
finish(new DOMException("Run cancelled", "AbortError"));
}
function dispatch(slot) {
if (settled || next === batchCount) return;
try {
const id = next++;
const rows = makeBatch(id);
if (!(rows instanceof Uint32Array)) throw new TypeError("Expected Uint32Array");
if (settled) return;
slot.id = id;
slot.timer = setTimeout(() => finish(new Error("Batch timed out")), 10000);
slot.worker.postMessage({ type: "batch", id, rows }, [rows.buffer]);
} catch (error) {
finish(error instanceof Error ? error : new Error(String(error)));
}
}
if (signal?.aborted) return abort();
if (batchCount === 0) return finish(null, { count: 0, totalCents: 0 });
signal?.addEventListener("abort", abort, { once: true });
try {
for (let i = 0; i < Math.min(size, batchCount) && !settled; i++) {
const worker = new Worker(new URL("./batch.worker.js", import.meta.url), {
type: "module",
});
const slot = { worker, id: -1, timer: undefined };
slots.push(slot);
worker.addEventListener("error", () => finish(new Error("Worker failed")));
worker.addEventListener("messageerror", () => finish(new Error("Invalid response")));
worker.addEventListener("message", ({ data }) => {
if (settled) return;
if (data?.id !== slot.id || data.type !== "result") {
return finish(new Error(data?.message || "Unexpected batch response"));
}
const { count, totalCents } = data.result ?? {};
if (!Number.isSafeInteger(count) || count < 0 ||
!Number.isSafeInteger(totalCents) || totalCents < 0) {
return finish(new Error("Invalid partial aggregate"));
}
clearTimeout(slot.timer);
slot.id = -1;
partials[data.id] = { count, totalCents };
completed += 1;
if (completed === batchCount) {
const result = partials.reduce((sum, part) => ({
count: sum.count + part.count,
totalCents: sum.totalCents + part.totalCents,
}), { count: 0, totalCents: 0 });
if (!Number.isSafeInteger(result.totalCents) ||
!Number.isSafeInteger(result.count)) {
return finish(new RangeError("Combined result is too large"));
}
finish(null, result);
} else {
dispatch(slot);
}
});
dispatch(slot);
}
} catch (error) {
finish(error instanceof Error ? error : new Error(String(error)));
}
});
}
import { summarizePacked } from "./packed-orders.js";
self.addEventListener("message", ({ data }) => {
if (data?.type !== "batch") return;
try {
const result = summarizePacked(data.rows);
self.postMessage({ type: "result", id: data.id, result });
} catch (error) {
self.postMessage({
type: "failure",
id: data.id,
message: error instanceof Error ? error.message : String(error),
});
}
});
Suppose workers A and B receive batches 0 and 1. B finishes first, so B immediately gets batch 2. Results are stored by batch ID, not completion order. The next free worker gets the next batch without waiting for a slow neighbor. This dynamic assignment reduces idle time when batches vary in cost, though very small batches can lose that benefit to scheduling overhead.
For exact integer sums below the safe limit, these partials can be combined in any order. For floating-point statistics, combination order can change rounding. Keep a fixed merge order and a defined numerical tolerance when the problem requires it. Average also needs both sum and count: averaging worker averages gives the wrong weighting when batch sizes differ.