Skip to content
Get started
Get started
Worker Reliability: Shutdown, Heartbeats and Stall Detection
View Markdown
guide · worker

Never lose an in-flight job.

Graceful deploys drain active work cleanly; on crashes, heartbeats, lease tokens, and two-phase stall detection recover jobs and fence out stale completions.

Lease & Stall Protection

Heartbeats keep active locks alive; dead workers are fenced and requeued

renew LOCK Active Lease lockDuration (30s) missed HB Heartbeat auto-renews lock reclaim DEAD Crash / Hang lock expires SWEEP Fenced Requeue new owner claims Stale ACK from old worker token is rejected safely (fenced)
At-least-once safety: if a worker freezes or crashes without heartbeating, the stall sweeper reclaims the job and fences any late ACK from the old owner.

Handle SIGINT and SIGTERM so deployments let active jobs finish and commit before exiting.

// Bun: 'bunqueue/client' (+ embedded: true for in-process). Node/Deno: 'bunqueue-client'.
import { Worker, shutdownManager, closeAllSharedPools } from 'bunqueue/client';
const worker = new Worker('downloads', async (job, context) => {
const res = await fetch(job.data.url, { signal: context?.signal });
return { bytes: (await res.arrayBuffer()).byteLength };
});
// Runtime pause/resume and cooperative cancellation
worker.pause(); // stop new pulls; active finish and buffered keep heartbeating
worker.resume(); // process buffered jobs and resume pulling
worker.cancelJob(jobId, 'request withdrawn'); // aborts context.signal, emits 'cancelled'
worker.cancelAllJobs('draining service');
async function shutdown() {
await worker.close(); // drain active jobs (keeping leases renewed), close Worker TCP pool
shutdownManager(); // embedded Bun only: flush SQLite buffer and close DB
closeAllSharedPools(); // TCP: close pools shared by Queue, FlowProducer, SandboxedWorker
process.exit(0);
}
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);
  • close() vs close(true): close() returns unstarted buffered jobs to the queue and keeps renewing active leases until every running handler settles. close(true) stops renewing and relinquishes active leases immediately (without killing running JS), discarding any late return or throw so the broker recovers the job cleanly.
  • Cooperative cancellation: cancelJob(id, reason) returns false unless this Worker is actively running that job. Pass context?.signal to cancellable APIs or check signal.aborted; resulting rejections follow normal retry rules.
Inspection memberTypeMeaning
worker.waitUntilReady()Promise<void>Resolves immediately embedded; over TCP pings pool and waits for stalled subscription
worker.isRunning()booleantrue while polling and processing
worker.isPaused()booleantrue while paused and not closed
worker.isClosed()booleantrue after shutdown finishes
worker.closingPromise<void> | nullActive shutdown promise once close() begins, else null

With useLocks: true (default), every pulled job carries a unique lease token with TTL lockDuration (30000 ms). Automatic heartbeats run every heartbeatInterval (10000 ms) to renew the lock and refresh stall liveness.

const worker = new Worker('video', async (job) => {
for (const chunk of job.data.chunks) {
await transcodeChunk(chunk);
await job.updateProgress(chunk.pct); // also resets the stall timer
}
if (job.token) await job.extendLock(job.token, 120_000); // optional explicit extension
return { done: true };
}, {
heartbeatInterval: 10_000, // keep well below lockDuration and stallInterval
lockDuration: 60_000,
});
// Batch-extend multiple active locks
await worker.extendJobLocks([jobId1, jobId2], [token1, token2], 60_000);
  • Token fencing: After lease expiry, redelivery assigns a fresh token and local generation. Only the active generation heartbeats and settles the job—late work from a stale handler cannot touch the new lease.
  • Embedded opt-out & SDKs: Embedded single-process Bun can set useLocks: false for slightly higher throughput while keeping stall detection active. External SDKs always use lock ownership (lockTtlMs / lock_ttl_ms / lock_ttl); Go disables heartbeats unless HeartbeatIntervalS > 0.

Stall detection is enabled by default on every queue, so jobs can run for hours while heartbeats or job.updateProgress() calls arrive. Tune the queue policy when an uninterrupted block may exceed 30 seconds or when you want a stricter stall budget.

import { Queue } from 'bunqueue/client';
const queue = new Queue('video');
await queue.setStallConfigAsync({
enabled: true, // default: true
stallInterval: 300_000, // 5 min without heartbeat before stall candidate (default: 30000)
maxStalls: 2, // move to DLQ after 2 stalls (default: 3)
gracePeriod: 60_000, // skip stall checks for first 60s (default: 5000)
});
const activeConfig = await queue.getStallConfigAsync();
OptionDefaultDescription
enabledtrueEnable/disable stall detection (and the 30-minute broker safety net) for this queue
stallInterval30000Heartbeat silence threshold in ms (confirmed over two consecutive 5s sweeps, ~35–40s earliest)
maxStalls3Max cumulative stall recoveries before moving the job to the DLQ
gracePeriod5000Initial grace window in ms after a job becomes active
  • Server-side persistence: Stall policy and each job’s cumulative stalledCounter persist in SQLite and PostgreSQL across all SDKs. Update via HTTP (PUT /queues/:queue/stall-config) for languages without a helper.
  • attempts vs maxStalls tie-breaker: Every stall recovery consumes one stallCount and one attempts slot; hitting either moves the job to the DLQ (emitting stalled then failed). Attempts wins ties, so defaults (maxStalls: 3, attempts: 3) report DLQ reason max_attempts_exceeded; stalled appears when maxStalls is lower than remaining attempts.

Subscribe via worker.on('stalled', ...) or QueueEvents in TypeScript, or consume SSE (GET /events/queues/:queue, event job:stalled) from any runtime. Inspect stalled DLQ entries with queue.getDlqStatsAsync() (stats.byReason.stalled) and queue.getDlqAsync({ reason: 'stalled' }); stall webhooks are not emitted.

Broker safety net, disconnect cleanup, and cron preventOverlap
  • 30-minute safety net: Periodic cleanup (every 10s) recovers an active job when stall detection is enabled, gracePeriod elapsed, no lock is live, and no heartbeat/progress/renewal arrived for max(30 min, stallTimeout || stallInterval). With enabled: false, only lock expiry, timeout, disconnect, or manual removal recovers the job.
  • Connection detachment: Once recovered, a job detaches from the silent TCP connection so a delayed disconnect from the dead worker cannot release the new delivery.
  • Cron preventOverlap: Memory/SQLite discard stalled or disconnect-released cron jobs with preventOverlap so the next tick recreates them cleanly; PostgreSQL preserves dependency-protected IDs via normal lease recovery.

Keep these six timer scopes separate when diagnosing stalls or TCP disconnects:

SettingScopeWhat happens when it expires
heartbeatInterval / SDK equivalentWorkerLease renewal and stall-timer refresh cadence (0 disables where supported)
lockDuration / lockTtlMsJob leaseOwnership token expires if not renewed
stallInterval (or job stallTimeout)Queue / Job policySilent job becomes a stall candidate and is retried or sent to DLQ
timeout (on JobOptions)Job executionBroker fails active attempt at the exact deadline with reason timeout
commandTimeoutTCP commandUnanswered command rejects; maxCommandTimeouts consecutive timeouts reconnect
pingIntervalTCP connectionPeriodic connection health probe; unrelated to job runtime (idle connections never drop)

Next steps: Keep heavy computation off the event loop in CPU-Intensive Workers, or inspect failed jobs in the Dead Letter Queue.