- Docs
- Core Guides
- Heartbeats, Locks & Stalls
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.
Heartbeats keep active locks alive; dead workers are fenced and requeued
Graceful Shutdown and Cancellation
Section titled “Graceful Shutdown and Cancellation”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 cancellationworker.pause(); // stop new pulls; active finish and buffered keep heartbeatingworker.resume(); // process buffered jobs and resume pullingworker.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()vsclose(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)returnsfalseunless this Worker is actively running that job. Passcontext?.signalto cancellable APIs or checksignal.aborted; resulting rejections follow normal retry rules.
| Inspection member | Type | Meaning |
|---|---|---|
worker.waitUntilReady() | Promise<void> | Resolves immediately embedded; over TCP pings pool and waits for stalled subscription |
worker.isRunning() | boolean | true while polling and processing |
worker.isPaused() | boolean | true while paused and not closed |
worker.isClosed() | boolean | true after shutdown finishes |
worker.closing | Promise<void> | null | Active shutdown promise once close() begins, else null |
Heartbeats and Lock Leases
Section titled “Heartbeats and Lock Leases”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 locksawait 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: falsefor slightly higher throughput while keeping stall detection active. External SDKs always use lock ownership (lockTtlMs/lock_ttl_ms/lock_ttl); Go disables heartbeats unlessHeartbeatIntervalS > 0.
Stall Detection Configuration
Section titled “Stall Detection Configuration”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();| Option | Default | Description |
|---|---|---|
enabled | true | Enable/disable stall detection (and the 30-minute broker safety net) for this queue |
stallInterval | 30000 | Heartbeat silence threshold in ms (confirmed over two consecutive 5s sweeps, ~35–40s earliest) |
maxStalls | 3 | Max cumulative stall recoveries before moving the job to the DLQ |
gracePeriod | 5000 | Initial grace window in ms after a job becomes active |
- Server-side persistence: Stall policy and each job’s cumulative
stalledCounterpersist in SQLite and PostgreSQL across all SDKs. Update via HTTP (PUT /queues/:queue/stall-config) for languages without a helper. attemptsvsmaxStallstie-breaker: Every stall recovery consumes onestallCountand oneattemptsslot; hitting either moves the job to the DLQ (emittingstalledthenfailed). Attempts wins ties, so defaults (maxStalls: 3,attempts: 3) report DLQ reasonmax_attempts_exceeded;stalledappears whenmaxStallsis lower than remainingattempts.
Monitoring stalls
Section titled “Monitoring stalls”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,
gracePeriodelapsed, no lock is live, and no heartbeat/progress/renewal arrived formax(30 min, stallTimeout || stallInterval). Withenabled: 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 withpreventOverlapso the next tick recreates them cleanly; PostgreSQL preserves dependency-protected IDs via normal lease recovery.
What Each Timeout Controls
Section titled “What Each Timeout Controls”Keep these six timer scopes separate when diagnosing stalls or TCP disconnects:
| Setting | Scope | What happens when it expires |
|---|---|---|
heartbeatInterval / SDK equivalent | Worker | Lease renewal and stall-timer refresh cadence (0 disables where supported) |
lockDuration / lockTtlMs | Job lease | Ownership token expires if not renewed |
stallInterval (or job stallTimeout) | Queue / Job policy | Silent job becomes a stall candidate and is retried or sent to DLQ |
timeout (on JobOptions) | Job execution | Broker fails active attempt at the exact deadline with reason timeout |
commandTimeout | TCP command | Unanswered command rejects; maxCommandTimeouts consecutive timeouts reconnect |
pingInterval | TCP connection | Periodic 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.