BullMQ Redis Queue With Retry and Backoff

Enqueue background jobs with BullMQ backed by Redis, configure exponential backoff retries, and process them in a worker with failure handling.

JavascriptNodeResilience

Code

snippet
import { Queue, Worker } from 'bullmq';

const connection = { url: 'redis://127.0.0.1:6379' };

const mailQueue = new Queue('mail', { connection });

await mailQueue.add('send-welcome', { userId: 42 }, {
  attempts: 5,
  backoff: { type: 'exponential', delay: 2000 },
  removeOnComplete: 100,
  removeOnFail: 1000,
});

const worker = new Worker('mail', async (job) => {
  if (job.attemptsMade < 1) throw new Error('smtp temporarily unavailable');
  console.log('delivered mail for', job.data.userId);
}, { connection, concurrency: 4 });

worker.on('failed', (job, err) => {
  console.error('job failed', job.id, err.message);
});