- Docs
- Core Guides
- Inspect & Control Queues
Inspect, control, and measure.
Operate a live queue from code: read job state and counts, pause or clean backlogs, track progress and logs, await results, and query per-minute metrics.
Inspect counts, pause intake, promote delayed jobs, or clean old rows
Querying Jobs and Counts
Section titled “Querying Jobs and Counts”Read single jobs, state snapshots, paginated job lists, or aggregate counts from the broker. Returned jobs reflect the authoritative generation in both embedded and TCP modes (returnvalue, progress, attemptsMade, attemptsStarted, stalledCounter, priority, timestamps, and toJSON() / asJSON()).
// Bun: 'bunqueue/client' (+ embedded: true for in-process). Node/Deno: 'bunqueue-client'.const job = await queue.getJob('job-id');const state = await queue.getJobState('job-id');// 'waiting' | 'prioritized' | 'delayed' | 'active' | 'completed' | 'failed' | 'waiting-children' | 'unknown'
const counts = await queue.getJobCountsAsync();// { waiting, prioritized, active, completed, failed, delayed, 'waiting-children', paused }const byPriority = await queue.getCountsPerPriorityAsync(); // Record<number, number>
// Filtered lists and state shortcutsconst failed = await queue.getJobsAsync({ state: 'failed', start: 0, end: 50 });const allFailed = await queue.getFailedAsync(0, -1); // exhaustive traversalconst prioritized = await queue.getPrioritized(0, 10);const waitingChildren = await queue.getWaitingChildren(0, 10);
// Individual async state counts (also: getWaitingCount, getActiveCount,// getCompletedCount, getDelayedCount, getWaitingChildrenCount)const failedCount = await queue.getFailedCount();const prioritizedCount = await queue.getPrioritizedCount();Sync vs async readers and pagination bounds
- Sync vs async:
getJobs(),getCountsPerPriority(),count(),isPaused(), andgetWaiting()/getActive()/getCompleted()/getFailed()/getDelayed()are embedded-only sync helpers (getJobCounts()delegates async over TCP and returns a Promise). Use*Asyncvariants for portable code. - Exhaustive reads (
end: -1): Supported bygetJobs,getJobsAsync, state shortcuts,getPrioritized, andgetWaitingChildren. Over TCP,end: -1drains 1,000-row pages and deduplicates IDs defensively. - Finite bounds: Omitting
endingetJobsAsync()defaults to100embedded and1000over TCP. Finiteendis exclusive ongetJobsAsyncand state shortcuts, exceptgetWaitingChildren(start, end)which is inclusive ((0, 10)returns up to 11 jobs).asc: falsereverses deterministiccreatedAt/jobIdorder before paging; offset pagination can shift under concurrent writes.
Queue Control
Section titled “Queue Control”Pause, drain, clean, retry, or mutate individual jobs on a live queue. Prefer *Async over TCP when callers need broker confirmation: sync variants (pause(), drain(), obliterate(), remove()) are fire-and-forget and log background failures instead of throwing.
// Queue-wide lifecycleawait queue.pauseAsync();await queue.resumeAsync();const drained = await queue.drainAsync(); // delete waiting/delayed jobs, return countawait queue.obliterateAsync(); // delete ALL queue data, metrics, and event history
// Single removal and bulk maintenanceawait queue.removeAsync('job-id');const cleaned = await queue.cleanAsync(3_600_000, 100, 'completed'); // older than 1h, max 100const promoted = await queue.promoteJobs({ count: 50 }); // delayed -> waitingawait queue.retryJobs({ state: 'failed', count: 100 });await queue.retryJobs({ state: 'completed', count: 100, timestamp: Date.now() - 3_600_000 });const retried = await queue.retryCompletedAsync('job-id-123'); // omit ID for all completed
// Single-job mutations (embedded and TCP)await queue.promoteJob('job-id');await queue.retryJob('job-id');await queue.updateJobData('job-id', { updated: true });await queue.changeJobDelay('job-id', 10_000);await queue.changeJobPriority('job-id', { priority: 20 });await queue.extendJobLock('job-id', token, 30_000);await queue.clearJobLogs('job-id', 50);
// Clean shutdownawait queue.waitUntilReady();await queue.disconnect(); // TCP: flush buffered autoBatch adds, then close// queue.close() closes immediately (embedded flushes SQLite; TCP rejects buffered adds)Removing one job safely
Section titled “Removing one job safely”removeAsync(id) and job.remove() delete waiting, delayed, prioritized, waiting-children, and completed jobs (clearing payload and stored result while keeping a payload-free completion record if flow dependents need it). Removing an already-absent ID resolves cleanly.
Active and failed (DLQ) jobs are never deleted by removeAsync(): it rejects with the current state (for example Job cannot be cancelled: not in queue (current state: active)). Remove failed jobs via DLQ operations; on PostgreSQL, a waiting job depended on by another live job is also refused until the dependent is removed.
Cleanup (cleanAsync) and completed-job retry internals
- Accepted
cleanAsync(grace, limit, type?)states:'completed','wait','waiting','prioritized','paused','delayed','failed', or'active'. Omittingtypecleans waiting, delayed, prioritized, and paused jobs older thangracems;'active'is always a no-op returning[]so leases, concurrency slots, and dedup ownership cannot leak. - SQLite completed cleanup: Queries SQLite directly in deterministic oldest-first
idorder and deletes job rows, results, and flow-failure rows in one transaction, skipping completed dependencies still needed by live consumers. - Retrying completed jobs:
retryCompletedAsync()andretryJobs({ state: 'completed' })clearreturnvalue, progress,processedOn, andfinishedOnand reset attempts to0while keeping stacktrace/timeline history; state reset and result removal commit atomically on SQLite and PostgreSQL. - Event journal: Removing a job does not rewrite entries already in
queue_events/bunqueue_events; callqueue.trimEvents(maxLength)to drop older entries sooner.
Progress, Logs and Waiting
Section titled “Progress, Logs and Waiting”Report progress and per-job logs, inspect flow dependencies, or block until a job reaches its terminal outcome.
import { QueueEvents } from 'bunqueue/client';
await queue.updateJobProgress('job-id', 75);await queue.addJobLog('job-id', 'Step 3 completed');const { logs, count } = await queue.getJobLogs('job-id', 0, 100);
// Flow dependency introspectionconst childValues = await queue.getChildrenValues('parent-job-id');const deps = await queue.getJobDependencies('job-id');const processed = await queue.getDependencies('parent-id', 'processed', 0, 10);
// Wait for final completion or terminal failure (pass QueueEvents, or null without one)const queueEvents = new QueueEvents('emails', { embedded: false, connection: { host: '127.0.0.1', port: 6789 },});await queueEvents.waitUntilReady();const result = await queue.waitJobUntilFinished('job-id', queueEvents, 30_000);queue.waitJobUntilFinished(id, queueEvents, ttl) and job.waitUntilFinished(queueEvents, ttl) share one implementation and settle only on the final outcome (retryable failures emit terminal: false on QueueEvents). Omitting ttl waits indefinitely with QueueEvents and defaults to 30 seconds with null; ttl <= 0 disables the timeout in both cases.
Manual state transitions
Section titled “Manual state transitions”Custom worker loops can drive BullMQ-compatible state transitions directly. Pass the active lock token whenever locks are enabled (useLocks: false jobs do not require one):
await queue.moveJobToCompleted('job-id', { ok: true }, token);await queue.moveJobToFailed('job-id', new Error('reason'), token);await queue.moveJobToWait('job-id', token);await queue.moveJobToDelayed('job-id', Date.now() + 60_000, token);await queue.moveJobToWaitingChildren('job-id', token);Wait resilience, removeOnComplete retention, and TCP WaitJob pool limits
- Outage resilience: Rejects with
Job <id> not foundif the job is removed, drained, or obliterated; transient rate limits, timeouts, and disconnects retry until reconnection orttlexpiry. removeOnComplete: truerequest/reply: The broker retains removed-on-complete results in memory for 60 seconds / 1,000 jobs by default (removedResultRetentionMs/maxRemovedResultsin Configuration) so late waits still resolve (getJobState()reports'unknown', directGetResultstays empty; PostgreSQL stores its own record).- TCP
WaitJobpool limit withoutQueueEvents: Each pooled TCP connection caps concurrentWaitJobcalls at 40 (160 on the default 4-connection pool) so other commands keep slots free; excess waits queue and check failures periodically. Pass aQueueEventsinstance for high-concurrency request/reply over one event stream.
Metrics and Event Trimming
Section titled “Metrics and Event Trimming”Inspect registered workers, read queue-scoped one-minute throughput buckets, and bound the event journal. For server-wide Prometheus (/prometheus) and JSON (/metrics) metrics, see Monitoring.
const workers = await queue.getWorkers();const workerCount = await queue.getWorkersCount();
const completed = await queue.getMetrics('completed', 0, 59); // newest 60 minutesconst failed = await queue.getMetrics('failed', 0, -1); // all retained bucketsconst trimmed = await queue.trimEvents(1000); // keep newest 1,000 journal entriesgetMetrics(type, start = 0, end = -1) is queue-scoped in embedded and TCP modes:
interface QueueMetrics { meta: { count: number; // Cumulative terminal jobs for this queue and type prevTS: number; // Timestamp of most recent terminal job prevCount: number; // Count in its one-minute bucket }; data: number[]; // One-minute buckets, newest first (0 = current partial minute) count: number; // Total available buckets before pagination}startandendare inclusive (0is the current partial minute,end: -1reads all retained minutes); empty minutes appear as0.- Retains up to 20,160 points (14 days) per queue and state while
meta.countstays cumulative. trimEvents(maxLength)bounds only this queue’s lifecycle event journal (persisted in SQLite/PostgreSQL, auto-capped at 10,000 entries, ephemeral in memory-only mode) and returns deleted rows (0on repeated calls).obliterateAsync()deletes both metrics and the journal.
Next steps: Control throughput with Rate Limiting & Concurrency, isolate tenants with Job Groups & Namespaces, or inspect terminal failures in the Dead Letter Queue.