Job States, Progress, and Events

Query BullMQ job states and results, report progress, and listen for Worker and queue events.

🎯 Introduction

By the end of this article, you will be able to query a job's state and result by ID, report progress from a Worker, and listen for completion and failure events.

Continue using BullMQ 5.61.2, the Redis configuration, and queue-config.mjs from the previous two articles.


🧱 Query Job States and Results

A Job's state indicates whether it is waiting, active, or finished. Once the submitting program saves the job ID, it can query the Job again without relying on Worker console logs.

Create inspect-job.mjs and pass the job ID as a command-line argument:

inspect-job.mjs
import { Queue } from 'bullmq';
import { connection, queueName } from './queue-config.mjs';

const jobId = process.argv[2];
if (!jobId) throw new Error('Please provide a job ID');
const queue = new Queue(queueName, {
    connection: { ...connection, maxRetriesPerRequest: 1 },
});
queue.on('error', error => console.error(error.message));
try {
    const job = await queue.getJob(jobId);
    if (!job) {
        console.log('Job does not exist or has been removed');
    } else {
        console.log('State:', await job.getState());
        console.log('Result:', job.returnvalue);
        console.log('Failure reason:', job.failedReason);
    }
} finally {
    await queue.close();
}

Query using the ID printed when you submitted a job in the first article:

node inspect-job.mjs JOB_ID

Common states include waiting, active, completed, and failed. Once a job is removed, queries report that it does not exist. A missing job must not be interpreted as a successful one.


📊 Report and Read Job Progress

Job progress is a value the processor function writes to the Job to describe its current progress. Long-running jobs often use it to report completed stages to callers. The Worker updates progress, and other programs can read it through the Job.

Create progress-worker.mjs:

progress-worker.mjs
import { Worker } from 'bullmq';
import { setTimeout as delay } from 'node:timers/promises';
import { connection, queueName } from './queue-config.mjs';

const worker = new Worker(queueName, async job => {
    for (const progress of [25, 50, 75, 100]) {
        await delay(500);
        await job.updateProgress(progress);
    }
    return { message: 'Processing complete' };
}, { connection: { ...connection, maxRetriesPerRequest: null } });
worker.on('completed', job => console.log('Completed:', job.id));
worker.on('error', error => console.error(error.message));
process.once('SIGINT', async () => { await worker.close(); });

updateProgress() accepts a number or an object. This example uses integer percentages. Start this Worker, then submit a job to the same queue. The Worker updates progress every half second and returns a result when finished.

Your program defines what progress means; it is not automatically converted into time remaining. Percentages are meaningful only when the job's steps can actually be estimated.


📣 Local Worker Events

Worker events are received by the process that created that Worker. They are useful for logging job completions, failures, and runtime errors locally.

Common events include completed, failed, and error. The first two describe processing outcomes. The error event usually indicates a runtime or connection error in the Worker itself. Make this distinction clear in logs.

Register listeners after creating the Worker:

worker.on('completed', (job, result) => {
    console.log('Job completed:', job.id, result);
});
worker.on('failed', (job, error) => {
    console.error('Job failed:', job?.id, error.message);
});
worker.on('error', error => console.error('Worker error:', error.message));

These listeners only observe events received by this Worker. They are not suitable for an independent web service that needs to observe changes across the entire queue.


🌐 Queue Events with QueueEvents

QueueEvents receives job events at the queue level and can listen from a different process than the Worker. It suits web services that need completion notifications or independent monitoring processes that record queue changes.

Create queue-events.mjs:

queue-events.mjs
import { QueueEvents } from 'bullmq';
import { connection, queueName } from './queue-config.mjs';

const events = new QueueEvents(queueName, { connection });
events.on('completed', ({ jobId, returnvalue }) => {
    console.log('Queue job completed:', jobId, returnvalue);
});
events.on('failed', ({ jobId, failedReason }) => {
    console.error('Queue job failed:', jobId, failedReason);
});
events.on('error', error => console.error('Event listener error:', error.message));
await events.waitUntilReady();
console.log('Listening for queue events');
process.once('SIGINT', async () => { await events.close(); });

QueueEvents uses a Redis Stream to collect queue events. Events that occurred before the listener started are not automatically replayed as new events. Query by job ID when you need a job's current result.

Start the listener script first, then run add-job.mjs in another terminal. The listener terminal will show the completed job ID and result. See the BullMQ Events documentation for details.


🧹 Stop Listening and Release Resources

Event listeners keep the process running. Call close() when exiting to stop listening and release the connection. A Worker uses its own close() method. These are separate objects, each responsible for its own connection resources.


❓ Knowledge Check

Q1: If no completed event fires, does that prove the job failed?

No. The listener may have started too late, the process may have disconnected, or the job record may already have been removed. Querying by job ID is better for checking an individual job.

Q2: Does progress of 80 mean only 20% of the time remains?

Not necessarily. Progress is a value reported by the processor function, not a time estimate.

Q3: How does QueueEvents differ from a Worker's completed listener?

Worker events are received by the local Worker. QueueEvents can listen for queue events from another process.


🧪 Exercise

Update progress after each processing step, then compare the information printed by local Worker events and QueueEvents.

// Write your code here

🎉 You can now query jobs and observe their progress!