Skip to content
Get started
Get started
SandboxedWorker: Isolated Job Processing
guide · worker

Handlers in their own thread.

CPU-bound work starves an event loop. SandboxedWorker moves the handler into a Bun Worker thread so the main thread can keep heartbeating, at the cost of using bunqueue’s experimental worker-pool implementation.

SandboxedWorker runs a processor module in Bun Worker threads. The queue and heartbeat loop stay in the parent thread. A per-job timeout terminates a stuck thread, and a crashed thread is restarted only while autoRestart is enabled and its restart budget remains.

This is execution separation, not a security sandbox. Threads share the same OS process and authority; do not use it to run untrusted code, and do not assume an out-of-memory failure is contained to one thread.

import { SandboxedWorker } from 'bunqueue/client';
const worker = new SandboxedWorker('cpu-intensive', {
processor: './processor.ts', // Path to processor file
concurrency: 4, // 4 parallel worker threads
timeout: 60000, // Per-job timeout (default: 30000, 0 = disabled)
maxMemory: 256, // compatibility hint; <= 64 enables smol mode
});
await worker.start();

The remaining API on this page is Bun-only.

Processor file (processor.ts):

export default async (job: {
id: string;
data: any;
queue: string;
attempts: number;
parentId?: string;
progress: (value: number) => void;
log: (message: string) => void;
fail: (error: string | Error) => void;
}) => {
job.progress(50);
const result = await heavyComputation(job.data);
job.progress(100);
return result;
};

To connect to a remote server instead of running embedded, pass a connection option (host, port, token); otherwise the shared embedded manager is used.

await worker.start();
worker.isRunning();
const stats = worker.getStats(); // { total, busy, idle, recycled, restarts }
await worker.stop(); // Graceful (waits for busy workers)
await worker.stop(true); // Force

getStats() reports pool bookkeeping in the current process. It is not a broker metrics snapshot.

OptionTypeDefaultDescription
processorstring(required)Path to processor file
concurrencynumber1Parallel worker threads
maxMemorynumber256Compatibility hint: values <= 64 enable Bun’s smol Worker mode. This implementation does not enforce an MB memory limit
timeoutnumber30000Per-job timeout in ms (0 = disabled)
autoRestartbooleantrueAuto-restart crashed threads
maxRestartsnumber10Max restart attempts per thread
pollIntervalnumber10Job poll interval in ms
heartbeatIntervalnumber5000 (embedded) / 10000 (TCP)Heartbeat for stall detection and lock renewal; non-positive disables it
idleTimeoutnumber0Stop the pool after this many idle ms (0 = disabled)
idleRecycleMsnumber30000Recycle idle threads after this many ms (0 = disabled)
autoStartbooleanfalseRestart the pool when new jobs arrive after an idle shutdown
autoStartPollMsnumber5000Poll interval while idle-stopped
connectionConnectionOptions-TCP connection (omit for embedded)

SandboxedWorker emits eight local events: ready, active, completed, failed, progress, log, error, and closed. It does not emit stalled, drained, or cancelled. completed/failed describe the local processor outcome; the implementation sends the broker ACK/FAIL asynchronously, so observe queue state or QueueEvents when broker confirmation matters.

WorkerSandboxedWorker
Production ready✅ Stable⚠️ Experimental bunqueue implementation
I/O-bound tasks (HTTP, DB, APIs)✅ Best choiceOverkill
CPU-intensive tasks⚠️ Blocks event loop✅ Runs in separate thread
Untrusted code❌ Not isolated❌ Thread separation is not a security boundary
Per-thread memory limitmaxMemory does not enforce one
Events11 events8 events
Concurrency, retries, heartbeats✅ Supported through a separate implementation

Most workloads are I/O-bound (API calls, database queries, file operations); for those, Worker is the right choice. For CPU-heavy work, see CPU-Intensive Workers for the supported offloading and lease-sizing patterns.

WorkerCreate a worker and process your first job
Worker Concurrency and Batch PullingRun jobs in parallel and pull them in batches
The Job Object Inside a Worker ProcessorEverything the processor receives and can do
Worker Eventscompleted, failed, stalled and the rest
Worker Error Handling, Retries and BackoffRetries, backoff, timeouts and giving up
Worker LifecyclePause, resume and shut down without losing work
Heartbeats, Stall Detection and Lock OwnershipHeartbeats, stall recovery and lock ownership
WorkerOptions ReferenceEvery WorkerOptions field, with defaults