# Worker Reliability: Shutdown, Heartbeats and Stall Detection

Shut down bunqueue workers gracefully without dropping jobs, keep leases alive with heartbeats and locks, and configure automatic stall detection and recovery.

Canonical: https://bunqueue.dev/guide/worker/reliability/

---

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

**In 30 seconds**

- **Drain on deploy:** call `await worker.close()` on `SIGINT`/`SIGTERM` so active jobs finish and stay heartbeated; use `close(true)` only to drop leases immediately.
- **Protected by default:** `useLocks: true`, `heartbeatInterval: 10s`, `lockDuration: 30s`, and stall detection (`stallInterval: 30s`, `maxStalls: 3`, `gracePeriod: 5s`) run out of the box.
- **At-least-once with fencing:** recovered jobs get a fresh lock token (lock expiry re-queues immediately; heartbeat stalls trigger after two 5s sweeps, ~35–40s) so late zombies cannot overwrite new leases. Keep handlers idempotent.

*[Interactive doc iso diagram: Heartbeats keep active locks alive; dead workers are fenced and requeued - 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 - open the HTML page to view it.]*

## Graceful Shutdown and Cancellation

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

```typescript
// 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 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

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.

```typescript
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 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.

```typescript
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 `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`.

### 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, `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.

## 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](https://bunqueue.dev/guide/cpu-intensive-workers/), or inspect failed jobs in the [Dead Letter Queue](https://bunqueue.dev/guide/dlq/).
