BullMQ Redis Queue With Retry
Configure a BullMQ job queue on Redis with retry backoff concurrency and dead letter handling.
Code
import{Queue,Worker}from'bullmq';import Redis from'ioredis';export function createQueue(name,redisUrl,{concurrency=5,maxRetries=3,backoff={type:'exponential',delay:1000}}={}){const connection=new Redis(redisUrl);const queue=new Queue(name,{connection});const worker=new Worker(name,async(job)=>{return await processJob(job);},{connection,concurrency});worker.on('failed',(job,err)=>{if(job.attemptsMade>=maxRetries)console.error('dead letter:',job.id,err.message);});async function add(data,opts={}){return queue.add(name,data,{attempts:maxRetries,backoff,...opts});}return{queue,worker,add,close:()=>Promise.all([queue.close(),worker.close()])};}async function processJob(job){return job.data;}How it works
Structurally, expect the functions createQueue, add and processJob and nothing else.
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. The snippet’s external surface is Queue, Worker, all of it via bullmq.
The result comes back as an object carrying queue, worker, add.
Points of care
- Requires
bullmqandioredisas packages; the snippet will not run without them.
Putting the pieces to work
The primary signature is export function createQueue(name,redisUrl,{concurrency=5,maxRetries=3,backoff={type:'exponential',delay:100…
The demo output is labeled (dead letter:), so every printed line maps back to its originating operation.
Import createQueue from the file and call it — the rest of the code is implementation detail.
The call returns queue, worker, add — destructure what you need at the call site.
Interactive Tools for This Topic
FAQ
- Do I need to install anything before running this?
- Yes: `bullmq` and `ioredis` must be present in the project or the import fails at load time.
- What does `createQueue` return?
- An object carrying `queue`, `worker`, `add`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.