Queue, Worker, and Job

Create jobs with Queue, process them with Worker, and understand the basic Job lifecycle.

🎯 Introduction

By the end of this article, you will be able to submit a job, process it in a separate Worker, and observe its transition from waiting to completed.

Continue using Node.js 22.9.0, BullMQ 5.61.2, Redis 7.4.2, and queue-config.mjs from the previous article.


🧱 The Roles of Queue, Worker, and Job

Queue provides the interface for submitting and querying jobs, Worker picks up and processes jobs, and Job represents an individual job record. Queue and Worker instances must use the same queue name to access the same jobs.

ObjectRoleExample in this article
QueueAdd and query jobsThe course-tasks queue
WorkerCall a processor function to perform the workWrite text to a file
JobStore the name, ID, and data for one jobA single file-write request

This separation lets a Node.js web service submit jobs quickly while another long-running process handles them. Queue manages jobs; it does not create a processor function for you.


🧰 The Job Lifecycle

A Job typically starts by waiting for a Worker. Once picked up, it becomes active. It completes when the processor function returns normally; if the function throws an error, failure handling begins. Later articles cover delays and retries.

Job data is serialized and stored in Redis, so pass JSON-compatible values such as strings, numbers, and plain objects. Do not pass functions, file handles, or connection pools.


🛠 Create a Processor Function

Create write-text.mjs to keep the processing logic separate from the Worker's connection and event configuration:

write-text.mjs
import { mkdir, writeFile } from 'node:fs/promises';

export async function writeText(job) {
    if (job.name !== 'write-text' || typeof job.data.text !== 'string') {
        throw new Error('Invalid job name or text data');
    }
    await mkdir('./output', { recursive: true });
    const filePath = `./output/${encodeURIComponent(job.id)}.txt`;
    await writeFile(filePath, job.data.text, 'utf8');
    return { filePath };
}

The Worker calls writeText(job). The returned object becomes the Job's result; throwing an error marks processing as failed. Using the job ID in the filename gives each job a separate file.


🛠 Process Jobs with a Worker

Create worker.mjs to listen to the same queue and call the processor above:

worker.mjs
import { Worker } from 'bullmq';
import { connection, queueName } from './queue-config.mjs';
import { writeText } from './write-text.mjs';

const worker = new Worker(queueName, writeText, {
    connection: { ...connection, maxRetriesPerRequest: null },
});
worker.on('completed', (job, result) => {
    console.log('Job completed:', job.id, result.filePath);
});
worker.on('failed', (job, error) => {
    console.error('Job failed:', job?.id, error.message);
});
worker.on('error', error => console.error('Worker connection error:', error.message));
process.once('SIGINT', async () => { await worker.close(); });

The Worker needs to keep waiting for Redis to recover, so its connection options allow commands to retry indefinitely. This Worker process receives completed and failed events. The error event indicates a connection or runtime error in the Worker itself. On shutdown, close() waits for active jobs to finish.

Start the Worker first:

node worker.mjs

Leave this terminal running, then submit a job from another terminal:

node add-job.mjs

The Worker should print the job ID and generated file path. Open the file in the output directory to see Hello BullMQ.

If you submit a job before starting the Worker, the Job remains waiting until the Worker starts. Producers and Workers can run in different processes or even on different machines, provided they connect to the same Redis instance and queue.


🧰 Closing a Queue and Retaining Jobs

Call close() before the producer script exits to release its connection. Closing a Queue does not delete the queue or its jobs. Job records are retained according to cleanup settings, which are covered in the reliability article.

A Worker uses close() to wait for jobs it has picked up to finish. If its process is forcibly terminated, active jobs may be picked up again later, so processing must tolerate repeated execution.


❓ Knowledge Check

Q1: Must Queue and Worker be in the same file?

No. Applications that submit jobs and Workers that process them commonly run separately.

Q2: Does a Worker exit when there are no jobs?

No. It keeps running and waits for new jobs until close() is called or the process ends.

Q3: Where is a Job's return value stored?

The processor function's return value is stored as the Job's result. Later articles show how to query it.


🧪 Exercise

Stop the Worker, submit two jobs, then restart it and inspect the contents of the files it generates.

// Write your code here

🎉 You now understand the roles of Queue, Worker, and Job!