# Querying, Control, Progress and Metrics

Read bunqueue jobs, states, and counts, pause, drain, clean, and remove jobs safely, stream progress and logs, wait for results, and query queue metrics.

Canonical: https://bunqueue.dev/guide/queue/manage/

---

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.

**In 30 seconds**

- **Prefer `*Async` methods:** sync helpers (`getJobs`, `pause`, `drain`, `clean`) only reflect immediate broker state in embedded mode; `*Async` variants work identically in embedded and TCP modes.
- **Safe deletion:** `removeAsync()` deletes pending and completed jobs while refusing active or failed ones; `cleanAsync(..., 'active')` is a no-op so in-flight leases cannot leak.
- **Request/reply & metrics:** pass `QueueEvents` to `waitJobUntilFinished()` for high-concurrency waits, and read per-minute buckets with `getMetrics('completed' | 'failed')`.

*[Interactive doc iso diagram: Inspect counts, pause intake, promote delayed jobs, or clean old rows - Full lifecycle control: every inspection and maintenance action works identically from TypeScript, Python, Go, Rust, HTTP, and the CLI - open the HTML page to view it.]*

## 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()`).

```typescript
// 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();
```

> **Note: State semantics**
>
> - **`prioritized`:** jobs with `priority > 0` report `'prioritized'` instead of `'waiting'` (BullMQ v5 convention); both are pullable and prioritized runs first.
> - **`paused`:** while paused, ready jobs count under `paused` instead of `waiting` or `prioritized` until `resume()`. Pause state persists across restarts.
> - **`failed`:** exhausted jobs move to the [Dead Letter Queue](https://bunqueue.dev/guide/dlq/) while staying counted as `failed` and returned by `getJob()` and `getFailedAsync()`.

**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.

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

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

### 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](https://bunqueue.dev/guide/dlq/); 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.

## Progress, Logs and Waiting

Report progress and per-job logs, inspect flow dependencies, or block until a job reaches its terminal outcome.

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

### 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):

```typescript
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](https://bunqueue.dev/guide/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.

## 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](https://bunqueue.dev/guide/monitoring/).

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

```typescript
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](https://bunqueue.dev/guide/rate-limiting/), isolate tenants with [Job Groups & Namespaces](https://bunqueue.dev/guide/queue/groups/), or inspect terminal failures in the [Dead Letter Queue](https://bunqueue.dev/guide/dlq/).
