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

javascriptsnippet
21 lines
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);
});

Inside the snippet

The async parts await their results, which keeps ordering predictable. From bullmq it pulls Queue, Worker — the imports name exactly which library surface the snippet touches. Failure is loud: Error aborts the current operation instead of degrading it.

Module-level bindings hold the data — connection, mailQueue, worker — with no function scope in between.

The top-level object literal pins url as plain values — no derivation, no imports behind them.

Emits through the .error level methods with structured payloads, so downstream transports can route by level and field.

What to watch for

  • Plan for an install step: bullmq is a real dependency, resolved by the package manager.
  • The guard job.attemptsMade < 1 short-circuits the flow with an early throw when its condition holds.

Putting it to use

Running the file prints labeled results such as delivered mail for, job failed — each operation’s effect is visible in the output.

Core lines

if (job.attemptsMade < 1) throw new Error('smtp temporarily unavailable');
await mailQueue.add('send-welcome', { userId: 42 }, {
  attempts: 5,
  backoff: { type: 'exponential', delay: 2000 },
  removeOnComplete: 100,
  removeOnFail: 1000,
});
worker.on('failed', (job, err) => {
  console.error('job failed', job.id, err.message);
});

Interactive Tools for This Topic

FAQ

Is there a failure path for bad input?
The code refuses to continue: `Error` is thrown while the state is still recoverable.
What does this need from the package registry?
These are real dependencies: `bullmq`. Without it the snippet will not load.