Skip to content
Get started
Get started
Querying, Control, Progress and Metrics
View Markdown
guide · queue

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.

Queue Operations

Inspect counts, pause intake, promote delayed jobs, or clean old rows

Inspect APIs counts · getJobs · state Control APIs pause · promote · clean admin commands Hot Memory instant O(1) counts Durable Store SQLite / PG cleanup atomic update Queue State live counters & rows Use cleanAsync() to prune old completed rows directly from storage
Full lifecycle control: every inspection and maintenance action works identically from TypeScript, Python, Go, Rust, HTTP, and the CLI.

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 shortcuts
const failed = await queue.getJobsAsync({ state: 'failed', start: 0, end: 50 });
const allFailed = await queue.getFailedAsync(0, -1); // exhaustive traversal
const 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(), and getWaiting() / getActive() / getCompleted() / getFailed() / getDelayed() are embedded-only sync helpers (getJobCounts() delegates async over TCP and returns a Promise). Use *Async variants for portable code.
  • Exhaustive reads (end: -1): Supported by getJobs, getJobsAsync, state shortcuts, getPrioritized, and getWaitingChildren. Over TCP, end: -1 drains 1,000-row pages and deduplicates IDs defensively.
  • Finite bounds: Omitting end in getJobsAsync() defaults to 100 embedded and 1000 over TCP. Finite end is exclusive on getJobsAsync and state shortcuts, except getWaitingChildren(start, end) which is inclusive ((0, 10) returns up to 11 jobs). asc: false reverses deterministic createdAt/jobId order before paging; offset pagination can shift under concurrent writes.

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 lifecycle
await queue.pauseAsync();
await queue.resumeAsync();
const drained = await queue.drainAsync(); // delete waiting/delayed jobs, return count
await queue.obliterateAsync(); // delete ALL queue data, metrics, and event history
// Single removal and bulk maintenance
await queue.removeAsync('job-id');
const cleaned = await queue.cleanAsync(3_600_000, 100, 'completed'); // older than 1h, max 100
const promoted = await queue.promoteJobs({ count: 50 }); // delayed -> waiting
await 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 shutdown
await queue.waitUntilReady();
await queue.disconnect(); // TCP: flush buffered autoBatch adds, then close
// queue.close() closes immediately (embedded flushes SQLite; TCP rejects buffered adds)

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'. Omitting type cleans waiting, delayed, prioritized, and paused jobs older than grace ms; '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 id order and deletes job rows, results, and flow-failure rows in one transaction, skipping completed dependencies still needed by live consumers.
  • Retrying completed jobs: retryCompletedAsync() and retryJobs({ state: 'completed' }) clear returnvalue, progress, processedOn, and finishedOn and reset attempts to 0 while 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; call queue.trimEvents(maxLength) to drop older entries sooner.

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 introspection
const 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.

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 found if the job is removed, drained, or obliterated; transient rate limits, timeouts, and disconnects retry until reconnection or ttl expiry.
  • removeOnComplete: true request/reply: The broker retains removed-on-complete results in memory for 60 seconds / 1,000 jobs by default (removedResultRetentionMs / maxRemovedResults in Configuration) so late waits still resolve (getJobState() reports 'unknown', direct GetResult stays empty; PostgreSQL stores its own record).
  • TCP WaitJob pool limit without QueueEvents: Each pooled TCP connection caps concurrent WaitJob calls at 40 (160 on the default 4-connection pool) so other commands keep slots free; excess waits queue and check failures periodically. Pass a QueueEvents instance for high-concurrency request/reply over one event stream.

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 minutes
const failed = await queue.getMetrics('failed', 0, -1); // all retained buckets
const trimmed = await queue.trimEvents(1000); // keep newest 1,000 journal entries

getMetrics(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
}
  • start and end are inclusive (0 is the current partial minute, end: -1 reads all retained minutes); empty minutes appear as 0.
  • Retains up to 20,160 points (14 days) per queue and state while meta.count stays 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 (0 on 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.