Job Retries and Error Handling
🎯 Introduction
By the end of this article, you will be able to configure a finite number of retries, distinguish retryable errors from errors that should not be retried, and configure cleanup for completed and failed jobs.
Reuse the configuration and processor function from the BullMQ quick start. This course uses BullMQ 5.61.2.
🧱 Job Failures and Error Types
When a processor function throws an error, BullMQ records that attempt as failed. If retries are configured, the Job may become eligible to run again later. The error reason is saved in the Job record.
Retry failures that may be temporary, such as an external service timeout. Validation errors and missing required data usually do not improve with repeated execution. A retry schedules another attempt; it does not fix input data.
BullMQ requires thrown failures to be Error objects so it can reliably record error information. Do not catch an error, log it, and return normally, or the queue will treat the job as successful.
🔁 Attempts and Backoff
attempts sets the maximum number of executions for a Job, including the initial attempt; backoff determines how long to wait before retrying after a failure. The wait can be fixed or increase gradually to avoid repeatedly calling a failing dependency immediately.
Create retry-worker.mjs to deliberately fail on the first attempt and process normally on the second:
import { Worker } from 'bullmq';
import { connection, queueName } from './queue-config.mjs';
import { writeText } from './write-text.mjs';
async function processJob(job) {
console.log('Attempt:', job.attemptsMade + 1);
if (job.attemptsMade === 0) throw new Error('Simulated temporary failure');
return writeText(job);
}
const worker = new Worker(queueName, processJob, {
connection: { ...connection, maxRetriesPerRequest: null },
});
worker.on('failed', (job, error) => console.error('Attempt failed:', job?.id, error.message));
worker.on('completed', job => console.log('Job completed:', job.id));
worker.on('error', error => console.error(error.message));
process.once('SIGINT', async () => { await worker.close(); });
Submit a job with retry options in add-retry.mjs:
import { Queue } from 'bullmq';
import { connection, queueName } from './queue-config.mjs';
const queue = new Queue(queueName, {
connection: { ...connection, maxRetriesPerRequest: 1 },
});
queue.on('error', error => console.error(error.message));
try {
const job = await queue.add('write-text', { text: 'Generated after retry' }, {
attempts: 3,
backoff: { type: 'exponential', delay: 1000 },
});
console.log('Job ID:', job.id);
} finally {
await queue.close();
}
Start the Worker, then run the submission script. The Worker first logs the simulated failure, then logs completion after retrying. exponential increases the wait as failures accumulate. attempts: 3 allows at most three executions in total.
🧱 Handle Unrecoverable Errors
An unrecoverable error prevents a job from succeeding with the same input, regardless of how many times it is retried. BullMQ's UnrecoverableError stops retries for the current Job and moves it to the failed state.
For example, a missing file ID is an input problem that the processor can reject during validation:
import { UnrecoverableError } from 'bullmq';
if (typeof job.data.fileId !== 'string') {
throw new UnrecoverableError('Missing file ID');
}
Place this check at the start of the processor function. Do not use an unrecoverable error for temporary network failures, or the job will not retry as configured.
🪤 Worker Interruptions and Job Recovery
If a Worker is interrupted, jobs that have not been confirmed as completed may be picked up again after their locks expire. This prevents jobs from staying active forever after a process exits, but also means business operations may run more than once.
Call worker.close() during a normal shutdown to let current processing finish. Power loss, forced process termination, or network disconnection can still interrupt work, so design processor functions to avoid additional side effects when executed again.
Connection errors and processor errors are different failures: the former affect a Worker's ability to pick up work, while the latter describe the outcome of a Job attempt. Listen for Worker error and Job failed events as needed. Redis reconnection is not a job retry strategy.
🧹 Clean Up Completed and Failed Jobs
Cleanup rules limit how many historical jobs Redis retains and for how long. They remove job records without undoing completed business operations or automatically deleting generated files.
Add these options to queue.add():
removeOnComplete: { age: 3600, count: 100 },
removeOnFail: { age: 86400, count: 1000 },
age is measured in seconds, and count is the maximum number of retained records. Completed records are retained for up to one hour or 100 jobs; failed records for up to one day or 1,000 jobs. Whichever limit is reached first triggers cleanup. Cleanup is lazy, so do not treat it as a precise timer.
For long-term auditing, save the required job IDs, results, and errors separately in your application database or logging system, then choose how long to retain queue history. See BullMQ automatic job removal.
❓ Knowledge Check
Q1: Does every failed event mean the job will never be retried?
Not necessarily. It may indicate a failed attempt. The Job will run again if attempts remain.
Q2: Does three attempts mean three retries after the initial execution?
No. attempts: 3 allows at most three executions, including the initial attempt.
Q3: Does removing a successful Job delete the file it generated?
No. Cleanup removes the Job record from Redis. The application must manage files separately.
🧪 Exercise
Make the processor throw a regular error on every attempt and observe three failures. Then switch to UnrecoverableError and compare whether retries continue.
// Write your code here
🎉 You now understand retries and job history management!
