In this guide, I will show you how to install and use BullMQ in a NestJS project. BullMQ is used to handle background jobs like sending emails, processing images, or running heavy tasks without slowing down your app.
working sample: https://github.com/habilm/bullmq-nestjs
Step 1: Install Required Packages
First, install BullMQ and Redis client:
npm install bullmq ioredis
Step 2: Setup Redis
BullMQ needs Redis to work.
You can:
- Install Redis locally
- Or use a cloud Redis service
Example (default local Redis):
host: localhost
port: 6379
Step 3: Create a Queue
Create a new file like queue.ts:
import { Queue } from 'bullmq';
import { Redis } from 'ioredis';
const connection = new Redis({
host: 'localhost',
port: 6379,
});
export const emailQueue = new Queue('email-queue', {
connection,
});
Step 4: Add Job to Queue
You can add jobs from your service:
await emailQueue.add('send-email', {
to: 'test@example.com',
subject: 'Hello',
});
Step 5: Create a Worker
Worker processes the job in background.
Create worker.ts:
import { Worker } from 'bullmq';
import { Redis } from 'ioredis';
const connection = new Redis({
host: 'localhost',
port: 6379,
});
const worker = new Worker(
'email-queue',
async job => {
console.log('Processing job:', job.name);
console.log(job.data);
// Example: send email logic here
},
{ connection },
);
Step 6: Run the Worker
Run worker separately:
node worker.js
Step 7: Use in NestJS Service
Example service:
import { Injectable } from '@nestjs/common';
import { emailQueue } from './queue';
@Injectable()
export class AppService {
async sendEmail() {
await emailQueue.add('send-email', {
to: 'user@gmail.com',
subject: 'Welcome',
});
}
}
Tips
- Always run worker in a separate process
- Use queue for heavy or slow tasks
- You can retry failed jobs using BullMQ options
- Use multiple workers for better performance
Conclusion
Now you have successfully integrated BullMQ with NestJS. This helps your app stay fast by moving heavy tasks to the background.
You can now extend this for:
- Email sending
- Image processing
- Notifications
- Data sync jobs
if you want view all queues and manage in a dashboard use Bull Board