cloudflare-parallel
Composed-topology parallel computing for Cloudflare Workers. N parallel V8 isolates per request — one job per leaf Durable Object — with hierarchical tree scaling beyond.
npm install cloudflare-parallel
# or: bun add cloudflare-parallel
# or: pnpm add cloudflare-parallel
import { Parallel } from 'cloudflare-parallel';
const pool = Parallel.pool(env);
// Mandelbrot escape-time across 128 image rows. Each isolate computes
// one row independently. ~15 ms per row of CPU; 128 rows fan out to
// 128 leaf Durable Objects, each running one row in its own V8 isolate
// on its own workerd process — that's where the CPU parallelism comes
// from. The tree topology kicks in past `maxFanOut` (default 32) so a
// 128-job request becomes a root coordinator → 8 sub-coordinators →
// 128 leaf DOs.
const rows = await pool.map((y: number) => {
const out = new Uint8Array(640);
for (let x = 0; x < 640; x++) {
let zx = 0, zy = 0;
const cx = (x - 320) / 200, cy = (y - 64) / 200;
let i = 0;
while (i < 1024 && zx * zx + zy * zy < 4) {
const t = zx * zx - zy * zy + cx;
zy = 2 * zx * zy + cy;
zx = t;
i++;
}
out[x] = i & 255;
}
return Array.from(out);
}, Array.from({ length: 128 }, (_, y) => y));
128 image rows in flight, on 128 leaf DOs, each a separate workerd process. No queue, no orchestration code, no infrastructure. The library picks the topology.
Why
This library is for CPU-bound parallelism on Cloudflare Workers. If you're awaiting I/O (fetch, KV reads, AI calls, R2 GETs, D1 queries), Promise.all on a single isolate already gives you that — the JavaScript event loop interleaves I/O for free. Where this library shines is offloading CPU-heavy work — embeddings, hashing, image transforms, parsing, simulation, codegen — to N parallel V8 isolates so the single-threaded event loop doesn't bottleneck you.
- N parallel V8 isolates per request. Each task in a
pool.map lands on its own leaf Durable Object — and each leaf DO is its own workerd process with its own V8 scheduler thread. CPU parallelism scales linearly with DO count, not with loaders-per-DO (loaders inside one process share that process's thread and serialize on CPU).
- Tree scaling beyond
maxFanOut. Once the fan-out exceeds the per-coordinator RPC cap (default 32), the auto-selector promotes to a multi-tier coordinator → sub-coordinator → leaf shape with branching factor F, keeping each coordinator tier under the fan-out cap while preserving one job per leaf.
- Real
AbortSignal cancellation. Token cancel propagates end-to-end across the RPC boundary; pending awaits inside the loaded isolate reject with the cancel reason.
- Reactive scheduler. Durable job queue with retries, deadlines, fair per-tenant queueing, idempotency keys.
- Live demo: cloudflare-parallel.ashishkmr472.workers.dev (deployed) · bench numbers.
When to use this library
- ✅ Embeddings / hashing / cryptographic chains across thousands of inputs.
- ✅ Image transforms, raytracing, mandelbrot tiles, dither passes.
- ✅ Parsing / linting / minifying / building hundreds of source files.
- ✅ Genetic / evolutionary search, Monte Carlo, simulated annealing.
- ✅ Pure-JS regex or AST work over a corpus that doesn't fit in one isolate's CPU budget.
- ✅ Any user fn where you'd reach for a worker pool on Node and feel the pain of single-threaded JS.
When NOT to use this library
- ❌ Fetching N URLs / calling N AI endpoints / reading N KV entries. Use plain
Promise.all. A single isolate's event loop interleaves I/O concurrently for free — you don't need separate V8 heaps to wait on the network.
- ❌ Sub-millisecond per-task work. Dispatch + DO RPC overhead is ≥ 5-15 ms; per-task CPU should be ≥ 10 ms before fan-out pays off.
- ❌ Workloads that fit comfortably on one isolate's
cpuMs budget. The library exists to escape the single-isolate CPU ceiling, not to add ceremony.
If your task awaits I/O for most of its duration, the JavaScript event loop is already the parallelism primitive. This library is for the case where each task burns CPU on a separate V8 thread.
Install
bun add cloudflare-parallel
# or: npm install cloudflare-parallel
Quickstart
wrangler.toml:
name = "my-worker"
main = "src/index.ts"
compatibility_date = "2026-01-20"
# Enables `ctx.exports.<WorkerEntrypoint>` loopback bindings — used by the
# in-process coordinator below to skip the DO hop for single-job dispatches.
# https://developers.cloudflare.com/workers/configuration/compatibility-flags/#enable-ctxexports
compatibility_flags = ["enable_ctx_exports"]
[[worker_loaders]]
binding = "LOADER"
[[durable_objects.bindings]]
name = "CfpCoordinator"
class_name = "CfpCoordinator"
[[durable_objects.bindings]]
name = "CfpWorkerDO"
class_name = "CfpWorkerDO"
[[durable_objects.bindings]]
name = "CfpSubCoord"
class_name = "CfpSubCoord"
[[migrations]]
tag = "v1"
new_sqlite_classes = ["CfpCoordinator", "CfpWorkerDO", "CfpSubCoord"]
src/index.ts:
import { Parallel, type WorkerLoader } from 'cloudflare-parallel';
export {
CfpCoordinator,
CfpWorkerDO,
CfpSubCoord,
CfpInProcessCoordinator,
} from 'cloudflare-parallel/durable-objects';
interface Env {
LOADER: WorkerLoader;
CfpCoordinator: DurableObjectNamespace;
CfpWorkerDO: DurableObjectNamespace;
CfpSubCoord: DurableObjectNamespace;
}
export default {
async fetch(req: Request, env: Env, ctx: ExecutionContext) {
const pool = Parallel.pool(env, {
// Skip the DO hop for single-shot submits — same-process
// dispatch via the auto-generated `ctx.exports` loopback.
// https://developers.cloudflare.com/workers/runtime-apis/context/
inProcess: ctx.exports.CfpInProcessCoordinator,
// Colocate freshly-created leaf DOs with the request's incoming
// colo. Best-effort placement hint, honored on first DO access only.
// https://developers.cloudflare.com/durable-objects/reference/data-location/
requestColo: req.cf?.colo as string | undefined,
});
const sums = await pool.map((n: number) => n * n, [1, 2, 3, 4, 5]);
return Response.json(sums);
},
};
Five primitives
| Factory |
Returns |
What it's for |
Parallel.pool |
Pool |
CPU-bound fan-out. The main surface. |
Parallel.loaderOnly |
LoaderOnlyPool |
Fan-out without a Coordinator DO. Capped at 3 from a fetch handler. |
Parallel.actor |
ActorHandle |
Long-lived stateful actor with pinned SQLite state. |
Parallel.scheduler |
Scheduler |
Durable job queue: retries, deadlines, fair-tenancy, idempotency. |
Parallel.vm |
VMHandle |
HTTP submit-code surface with required policy field. |
Pool — every method
Every method below is on the Pool class. Same options pattern (closure-free user fn + optional trailing SubmitOptions bag) across the surface.
pool.submit(fn, ...args, opts?) — single CPU task
const digest = await pool.submit((seed: number) => {
let buf = new TextEncoder().encode(`seed-${seed}`);
for (let i = 0; i < 5000; i++) buf = new Uint8Array(/* hash */ buf);
return buf[0];
}, 42);
pool.submitSource(fnSource, args, opts?) — submit code as a string
The source is shipped straight to the loader (no eval in the parent
Worker). Used by the HTTP submit-code surface; also handy for codegen
or persisted user code.
const code = `(a, b) => a * b * Math.PI`;
const result = await pool.submitSource<number>(code, [3, 4]);
pool.submitStream(fn, ...args, opts?) — single task that returns a stream
submitStream is currently a single submit that expects the user fn
to return a ReadableStream. It does not yet implement a separate
multi-hop streaming protocol for fan-out or backpressure coordination.
const stream = await pool.submitStream((n: number) => {
const { readable, writable } = new TransformStream();
const writer = writable.getWriter();
(async () => {
for (let i = 0; i < n; i++) {
await writer.write(new TextEncoder().encode(`chunk-${i}\n`));
}
writer.close();
})();
return readable;
}, 16);
pool.map(fn, items, opts?) — fan out one fn over N items
const tiles = await pool.map((y: number) => renderRow(y), [0, 1, 2, ..., 191]);
Auto-topology: 1 → in-do (single-isolate fast path); 2..32 → hybrid (N leaf DOs, one job each); >32 → tree (root → sub-coords → leaves).
pool.mapStream(fn, items, opts?) — yield results in completion order
for await (const { index, value } of pool.mapStream(renderRow, rows)) {
// value is the result for `rows[index]`; faster items arrive first.
}
pool.mapOrdered(fn, items, opts?) — yield results in input order
for await (const value of pool.mapOrdered(renderRow, rows)) {
// results arrive in row order even if some isolates finish out-of-order.
}
pool.scatter(fn, items, chunks, opts?) + pool.gather(promises) — explicit scatter-gather
const histograms = await pool.scatter(
(chunk: number[]) => chunk.reduce((h, n) => ((h[n & 7] = (h[n & 7] ?? 0) + 1), h), [] as number[]),
largeArray,
16, // 16 chunks
);
const merged = await pool.gather(histograms.map(async (h) => h));
gather is Promise.all for stylistic uniformity with the fan-out
surface. Use it when you've kicked off multiple pool.submit calls.
pool.pmap(fn) — curried batched map
const embed = pool.pmap((batch: string[]) => batch.map(embedOne));
const vectors = await embed(documents, { chunks: 16 });
pool.reduce(fn, items, initial, opts?) — tournament reduce
const totalEnergy = await pool.reduce(
(a: number, b: number) => combineEnergies(a, b),
candidates,
0,
);
pool.warm() + pool.stats() + pool.handle({ policy })
await pool.warm(); // absorb DO cold-start (~300–400 ms)
await pool.warm({ isolates: 8 }); // also pre-spin 8 V8 isolates
const stats = await pool.stats(); // { topology, fanOutPerLevel, treeDepth, ... }
const handler = pool.handle({ policy: { kind: 'auth', auth: bearerAuth(token) } });
return handler(req); // HTTP submit-code endpoint
autoWarm: true is the default — the first submit fires warm()
implicitly in parallel with the real dispatch, so most callers never
need to call warm() directly. Use it explicitly when you want to pay
the cold-start cost at Worker startup rather than on first request.
pool.restrictTo(allowedKeys) — capability-narrow the bindings
const safePool = pool.restrictTo(['KV']); // user fns see only env.KV.
Binding model
On Parallel.loaderOnly, bindings values are passed directly into the
loaded isolate. On DO-backed paths (Pool, Actor, Scheduler), the
receiving DO resolves binding values from its own env; the
bindings: object declares the keys to allow through. If bindings is
omitted, the library preserves the historical behavior and forwards all
safe env keys after stripping LOADER, Cfp*, and internal cfp*
bindings. Use pickBindings(env, [...]) when you want an explicit
allow-list.
Cancellation: SubmitOptions.cancel: CancelToken
import { CancelToken } from 'cloudflare-parallel';
const cancel = CancelToken.withTimeout(30_000);
const result = await pool.submit(async (n: number, env: { signal: AbortSignal }) => {
for (let i = 0; i < n; i++) {
env.signal.throwIfAborted(); // cooperative cancel point
await heavyStep(i);
}
}, 1_000_000, { cancel });
env.signal is a real AbortSignal. Pass it to any Web API that
accepts one: fetch(url, { signal }), setTimeout via AbortController,
ReadableStream.cancel. The token also supports .fromAbortSignal(req.signal)
for adapting an inbound request's cancel.
Parallel.loaderOnly — for the cheap path
When you don't want to deploy the Coordinator DO and you can live with
the 3-loader-from-fetch-handler cap. Same submit / map / scatter
/ gather / pmap / reduce surface; no submitSource and no
mapStream / mapOrdered / submitStream / warm / drain / stats
/ handle (those need the coordinator).
const lop = Parallel.loaderOnly(env);
const sums = await lop.map((n: number) => n * n, [1, 2, 3]);
Parallel.actor — long-lived stateful actor
State pinned in a Coordinator DO's SQLite. User fn signature is
(state, sql, ...args, env) — mutate state in place; the runtime
structured-clone-snapshots it after each submit.
const counter = Parallel.actor(env, { id: 'cart-42', initialState: { items: [] as string[] } });
await counter.submit((state, _sql, item: string) => {
state.items.push(item);
return state.items.length;
}, 'apple');
Parallel.scheduler — durable job queue
Reactive dispatch (no alarm-batched delays). Retries with exponential
backoff, fair per-tenant queueing, idempotency keys.
const scheduler = Parallel.scheduler(env, {
id: 'embeddings',
retry: { max: 3, backoff: 'exponential', baseMs: 200 },
});
const handle = await scheduler.enqueue({
fn: async (docId: number) => embedDocument(docId),
args: [42],
tenantId: 'acme',
idempotencyKey: 'embed-doc-42',
});
const value = await handle.result(); // long-poll until done
Parallel.vm — HTTP submit-code
Sandboxed per-request user code with required auth policy.
submitCodeHandler and Parallel.vm