Summary: To keep a NestJS API fast when email or push providers are slow or down, push each notification into a BullMQ queue and let a worker send it in the background. Give jobs retries with a backoff, move jobs that run out of retries into a dead letter queue you can inspect and replay, and pass an idempotency key to the provider so a retried job never sends the same email twice.
A user pays for an order, and your email provider happens to be down at that moment. Should the order fail because the invoice email couldn't go out? It shouldn't. The invoice can be sent a few minutes later, but if your API waits on the email service before it responds, the user is stuck waiting for something that has nothing to do with their payment.
Almost every application sends notifications: push, email or SMS. For push, there's no way around external services; iOS needs Apple Push Notification Service (APNs) and Android needs Firebase Cloud Messaging (FCM). For email, you could technically run your own SMTP server, but teams usually pick a provider like Resend for reliability and ease of use.
External services bring network latency, rate limits and downtime with them. When notifications are sent synchronously, your app's response time is at the mercy of those services. The fix is to decouple the two. In this post, we'll walk through how we designed an asynchronous notification pipeline with BullMQ and Redis in NestJS, including what happens to jobs that keep failing, how to avoid sending the same email twice, and what to do with jobs that block the event loop.
Why Send Notifications Through a Queue
Instead of calling the email provider inside the request, the API adds a job to a queue with everything the email needs, then responds. A worker sends the email separately, so a provider outage delays the email, not the order.
BullMQ gives us an easy API to add jobs to a queue and to pick them up for processing. It stores job data in Redis by default, and recent versions also offer an optional PostgreSQL backend for teams that would rather not run a separate Redis instance, and store jobs in PostgreSQL.
Everything to the right of the queue happens after the user already has their response.
Queues, Jobs and Workers in BullMQ
Think of a coffee shop where the queue holds every order waiting to be made. In BullMQ, a queue holds jobs waiting to be processed, and each job must carry everything needed to complete it. To send an email, that means the address, subject and body.
import { Queue } from 'bullmq';
// Initialise a queue.
const queue = new Queue('email');
// Add a job to the queue.
await queue.add('email', {
to: 'hello@example.com',
subject: 'Just checking',
body: 'How is it going?',
});Workers are the baristas. They take jobs from the queue and do the work, whether that's sending an email or a push notification. When a job finishes, it moves to the completed state. If the worker throws an error, the job is retried, and once all retry attempts are used up it moves to the failed state. The work itself happens in the worker's async process function.
import { Worker, Job } from 'bullmq';
const worker = new Worker('email', async (job: Job) => {
// Process the job and then return some value.
return 'value';
});How to Set Up BullMQ in NestJS
Start by installing the NestJS wrapper along with BullMQ itself.
npm i @nestjs/bullmq bullmqThen register the Redis connection, the default job options and the queue in your module.
import { Module } from '@nestjs/common';
import { BullModule } from '@nestjs/bullmq';
@Module({
imports: [
BullModule.forRoot({
connection: {
url: process.env.REDIS_URL,
},
defaultJobOptions: {
attempts: 3,
backoff: { type: 'exponential', delay: 5000 },
removeOnComplete: true,
removeOnFail: 1000, // Without this, BullMQ keeps every failed job.
},
}),
BullModule.registerQueue({
name: 'email',
}),
],
})
export class EmailModule {}Here's what each option does:
attemptsis the total number of tries a job gets before it is marked as failed.backoffsets the wait between retries. With exponential backoff, the wait is 2^(attempts made − 1) × delay, so it doubles each time: 5 seconds before the first retry, then 10 seconds.removeOnCompleteremoves a job from Redis once it completes.removeOnFailkeeps only the most recent 1,000 failed jobs.
A common mistake is using delay here instead of backoff. In BullMQ, delay holds a job back before its first run; it has nothing to do with retries. Without a backoff, failed jobs are retried immediately.
Next, we need a producer. In BullMQ, a producer is any code that adds jobs to a queue, while workers are the ones that process them. Here, the producer is a service your API calls instead of the email provider.
import { Injectable } from '@nestjs/common';
import { InjectQueue } from '@nestjs/bullmq';
import type { Queue } from 'bullmq';
export type EmailPayload = { to: string; subject: string; body: string };
@Injectable()
export class EmailService {
constructor(@InjectQueue('email') private emailQueue: Queue) {}
async sendEmail(to: string, subject: string, body: string) {
await this.emailQueue.add('send-email', { to, subject, body });
return { success: true };
}
}The consumer is the worker that picks up those jobs and sends the email.
import { Processor, WorkerHost } from '@nestjs/bullmq';
import type { Job } from 'bullmq';
import { EmailPayload } from './email.service';
@Processor('email')
export class EmailConsumer extends WorkerHost {
async process(
job: Job<EmailPayload, any, 'send-email'>,
): Promise<{ success: boolean }> {
const { to, subject, body } = job.data;
// Call your email provider here.
return { success: true };
}
}Finally, the controller only queues the email and returns right away.
import { Body, Controller, Post } from '@nestjs/common';
@Controller('email')
export class EmailController {
constructor(private readonly emailService: EmailService) {}
@Post('send-email')
async sendEmail(@Body() dto: SendEmailDto): Promise<{ success: boolean }> {
return this.emailService.sendEmail(dto.to, dto.subject, dto.body);
}
}Tracking Jobs with BullMQ Worker and Queue Events
BullMQ emits events on both workers and queues, so you can follow a job as its state changes. At the worker level, use the @OnWorkerEvent(event) decorator inside the processor class. These events are useful for logging when a job starts, completes or fails, and for reporting its progress.
import { Processor, WorkerHost, OnWorkerEvent } from '@nestjs/bullmq';
import { Job } from 'bullmq';
import { Logger } from '@nestjs/common';
import { EmailPayload } from './email.service';
@Processor('email')
export class EmailConsumer extends WorkerHost {
private readonly logger = new Logger(EmailConsumer.name);
async process(
job: Job<EmailPayload, any, 'send-email'>,
): Promise<{ success: boolean }> {
// Same email-sending logic as in the consumer above.
return { success: true };
}
@OnWorkerEvent('active')
onActive(job: Job) {
this.logger.log(`Job ${job.id} has started`);
}
@OnWorkerEvent('completed')
onCompleted(job: Job, result: any) {
this.logger.log(`Job ${job.id} completed: ${JSON.stringify(result)}`);
}
@OnWorkerEvent('failed')
onFailed(job: Job, e: Error) {
this.logger.error(`Job ${job.id} failed with error: ${e.message}`);
}
// Report progress from inside process() with: await job.updateProgress(percentage);
@OnWorkerEvent('progress')
onProgress(job: Job, progress: number | object) {
this.logger.log(`Job ${job.id} progress: ${JSON.stringify(progress)}%`);
}
}Queue-level events track the queue as a whole. Use the @OnQueueEvent(event) decorator to react when a new job starts waiting, when the queue is drained (empty), and when it is paused or resumed.
import { QueueEventsHost, QueueEventsListener, OnQueueEvent } from '@nestjs/bullmq';
import { Logger } from '@nestjs/common';
@QueueEventsListener('email')
export class EmailQueueEvents extends QueueEventsHost {
private readonly logger = new Logger(EmailQueueEvents.name);
@OnQueueEvent('waiting')
onQueueWaiting(job: { jobId: string; prev?: string }) {
this.logger.log(`Job ${job.jobId} is waiting in the queue`);
}
@OnQueueEvent('drained')
onQueueDrained() {
this.logger.warn('Queue is empty, all jobs have been processed');
}
@OnQueueEvent('paused')
onQueuePaused() {
this.logger.log('The email queue has been paused');
}
}NestJS wires up @OnWorkerEvent handlers automatically because the class already has @Processor(). Queue event classes are different: add them to your module's providers array (providers: [EmailConsumer, EmailQueueEvents]) so NestJS creates them and starts listening.
Pausing a BullMQ Queue When a Provider Goes Down
Queues come with a management API, including queue.pause() and queue.resume(). A paused queue doesn't hand out new jobs until it's resumed, while jobs already in progress keep running until they finish.
Pausing doesn't stop jobs from coming in. Your API can still call queue.add(); the worker just won't pick up anything new, and the jobs wait in Redis until the queue is resumed.
This is handy for reliability and maintenance. If a third-party API is down, there's no point burning through retry attempts against it. Pause the queue, let pending jobs pile up safely, and resume once the provider is back. The same idea works for server load: when server resource usage is high, an automated health-check script can pause the queue while the existing backlog clears, protecting the infrastructure from crashing.
Handling Failed Jobs with a Dead Letter Queue

With the configuration above, BullMQ tries each job three times and keeps only the last 1,000 failed jobs. If something goes wrong and 5,000 jobs fail, 4,000 of them disappear without anyone noticing. You need a way to deal with them.
Retrying failed jobs from the main queue
If the queue isn't very busy, you can start simple. Use the age property in removeOnFail so failed jobs stay around for a few days, then expose an API to list failed jobs and retry the ones you choose. This lives in its own service, separate from the EmailService that adds jobs.
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectQueue } from '@nestjs/bullmq';
import { Queue } from 'bullmq';
@Injectable()
export class EmailFailedJobsService {
constructor(@InjectQueue('email') private readonly emailQueue: Queue) {}
async getFailedJobs(start = 0, end = 50) {
const jobs = await this.emailQueue.getFailed(start, end);
return jobs.map((job) => ({
id: job.id,
data: job.data,
failedReason: job.failedReason,
attemptsMade: job.attemptsMade,
finishedOn: job.finishedOn,
}));
}
async retryFailedJob(jobId: string) {
const job = await this.emailQueue.getJob(jobId);
if (!job) throw new NotFoundException(`Job ${jobId} not found`);
// resetAttemptsMade sets the attempt count back to 0. Without it, a job that
// already used 3 of 3 attempts fails again immediately on retry.
await job.retry('failed', { resetAttemptsMade: true });
return { retriedJobId: jobId };
}
}Moving terminal failures into a dead letter queue
Keeping failed jobs in the main queue works early on, but it stops scaling. If you process more than 10,000 jobs a day, you don't want up to 10,000 failed jobs sitting in the main queue. Queues work best when completed and failed jobs are cleared aggressively, and Redis storage gets expensive quickly.
When you run several queues, have strict memory limits, or want custom workflows such as alerts, move failed jobs into a dedicated queue: a dead letter queue (DLQ). With multiple queues (email, SMS, webhooks, payouts, push), sending every terminal failure into one shared queue such as email-dlq means you build one inspection API and one cron job, instead of polling getFailed() on every queue.
To set this up, register a new queue for failed jobs, then listen for the worker's failed event. When a job has used all its attempts, copy it into the DLQ and remove it from the main queue.
import { Processor, WorkerHost, OnWorkerEvent, InjectQueue } from '@nestjs/bullmq';
import { Job, Queue } from 'bullmq';
import { EmailPayload } from './email.service';
@Processor('email')
export class EmailConsumer extends WorkerHost {
constructor(@InjectQueue('email-dlq') private readonly dlqQueue: Queue) {
super();
}
// ... process
@OnWorkerEvent('failed')
async onFailed(job: Job<EmailPayload> | undefined, error: Error) {
if (!job) return;
const maxAttempts = job.opts.attempts ?? 1;
if (job.attemptsMade >= maxAttempts) {
await this.dlqQueue.add('dead-email', {
originalJobId: job.id,
originalJobName: job.name,
payload: job.data,
failedReason: error.message,
failedAt: new Date().toISOString(),
});
await job.remove(); // Clean up from the main queue.
}
}
}Replaying jobs from the dead letter queue
The email-dlq queue has no worker attached, so every dead job sits safely in the waiting state until you decide what to do with it. There are two ways to recover these jobs:
- With manual replay, someone reviews why the job failed, fixes the cause if needed, and pushes the job back into the main queue.
- With cron replay, a scheduled
@Cron()job moves DLQ items back automatically.
If you automate it, never replay blindly. Filter on the stored failedReason so the cron job only replays transient network errors (ETIMEDOUT, ECONNRESET, 503) and leaves 4xx and validation errors for a person to inspect. Otherwise a job that can never succeed bounces between the main queue and the DLQ forever.
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectQueue } from '@nestjs/bullmq';
import { Queue } from 'bullmq';
@Injectable()
export class EmailDlqService {
constructor(
@InjectQueue('email-dlq') private readonly dlqQueue: Queue,
@InjectQueue('email') private readonly mainQueue: Queue,
) {}
async getDeadJobs(start = 0, end = 50) {
const jobs = await this.dlqQueue.getJobs(['waiting'], start, end);
return jobs.map((job) => ({ dlqId: job.id, ...job.data }));
}
async replayDeadJob(dlqJobId: string) {
const dlqJob = await this.dlqQueue.getJob(dlqJobId);
if (!dlqJob) throw new NotFoundException(`DLQ job ${dlqJobId} not found`);
await this.mainQueue.add(dlqJob.data.originalJobName, dlqJob.data.payload);
await dlqJob.remove();
return { replayedId: dlqJobId };
}
// Can be triggered manually or via @Cron.
async replayTransientFailures(batchSize = 50) {
const jobs = await this.dlqQueue.getJobs(['waiting'], 0, batchSize);
let replayedCount = 0;
for (const job of jobs) {
const reason: string = job.data.failedReason ?? '';
const isTransient = ['ETIMEDOUT', 'ECONNRESET', '503'].some((code) =>
reason.includes(code),
);
if (isTransient) {
await this.replayDeadJob(job.id!);
replayedCount++;
}
}
return { replayedCount };
}
}To expose this as an API, call getDeadJobs() and replayDeadJob() from a controller route, the same way the EmailController calls EmailService earlier in this post.
Scaling BullMQ Workers with Concurrency and More Instances
As your app grows, so does the number of jobs. By default, a BullMQ worker processes one job at a time, and handling jobs one by one quickly builds a backlog.
If your jobs are mostly I/O-bound, like calling an API or querying a database, Node.js can run many of them at once on a single thread. Raise the worker's concurrency:
import { Processor, WorkerHost } from '@nestjs/bullmq';
import { Job } from 'bullmq';
import { EmailPayload } from './email.service';
// Process up to 50 email jobs at the same time on this worker instance.
@Processor({ name: 'email', concurrency: 50 })
export class EmailConsumer extends WorkerHost {
async process(job: Job<EmailPayload>): Promise<void> {
// emailService is your email provider client, injected through the constructor.
await this.emailService.send(job.data);
}
}Keep high concurrency for async, I/O-bound work only. CPU-heavy jobs need a different approach, covered in the section on sandboxed processors.
The second option is horizontal scaling. When one machine hits its memory or network limits, run more instances of the NestJS app (or a dedicated worker service) pointing at the same Redis. Since BullMQ uses Redis as the central broker and lock manager, this needs no code changes. Redis's atomic operations make sure each job goes to only one worker at a time, though if a worker loses its lock, the job can run again somewhere else. That last part matters for the next section.
How to Prevent Duplicate Emails When BullMQ Retries a Job
Here's the scenario to watch for. A worker picks up an email job, asks the email provider to send it, and crashes before the provider's response comes back. The email may well have gone out, but BullMQ never heard that the job finished. The job is marked as stalled, and by default BullMQ puts stalled jobs back in the queue to run again. The user can end up with the same email twice.
The fix is to make the send idempotent, meaning running it twice has the same effect as running it once. Pass a unique idempotency key with each request to the email provider, built from something that identifies that one email, such as the order ID. If the provider sees a second request with the same key, it treats it as a retry, skips the duplicate send and returns success, so the worker can mark the job as complete.
Resend supports this through an Idempotency-Key header, and its docs say it checks for the same key over the past 24 hours. In the Node SDK, it's an option on the send call:
await resend.emails.send(
{ from, to, subject, html },
{ idempotencyKey: `order-confirmation/${orderId}` },
);If a provider doesn't support idempotency keys, record the send attempt in your database before calling the API and skip the send on retry when a record already exists. That stops duplicates, but there's a trade-off: if the worker crashes right after writing the record and before the API call, the email never goes out. You're choosing at-most-once delivery over at-least-once.
Running CPU-Heavy Jobs with BullMQ Sandboxed Processors
Node.js runs on a single-threaded event loop. It handles async I/O very well but struggles with CPU-intensive work. If a worker picks up a job that needs heavy computation, like generating a large PDF, processing images or crunching a big dataset, it blocks that one thread.
When the event loop is blocked, two things go wrong. If the worker runs inside the API process, the whole app freezes and stops serving HTTP requests. And the worker can't send its regular heartbeat to Redis, which is how it keeps its lock on the job.
Once the heartbeats stop, other healthy workers see the expired lock, mark the job as stalled and put it back in the queue. If it stalls again, by default it moves to the failed state, where it's either lost or kept depending on your config. Raise maxStalledCount and it gets worse: the job keeps returning to the queue, and one heavy job repeatedly freezes every worker that touches it.
For long-running, CPU-bound tasks, BullMQ offers sandboxed processors. Instead of giving the worker a callback, you give it the path to a script file:
import { BullModule } from '@nestjs/bullmq';
import { join } from 'path';
BullModule.registerQueue({
name: 'heavy-jobs-queue',
processors: [join(__dirname, 'reportProcessor.js')],
});Under the hood, BullMQ uses Node's child_process.fork() to start a separate Node.js process that runs that file. The heavy computation happens in the child process, so the main event loop stays free to serve API requests and keep the worker's heartbeats going.
If you're building something similar or have questions about this setup, connect with me on LinkedIn.
FAQ
How do I use BullMQ with NestJS?
Install @nestjs/bullmq and bullmq, register the Redis connection with BullModule.forRoot() and each queue with BullModule.registerQueue(). Inject the queue into a service with @InjectQueue() to add jobs, and create a class decorated with @Processor() that extends WorkerHost to process them.
What is the difference between delay and backoff in BullMQ?
delay holds a job back before its first run. backoff controls the wait between retries after a job fails, either fixed or exponential. If you set attempts without a backoff, BullMQ retries failed jobs immediately.
Does BullMQ have a dead letter queue?
BullMQ keeps jobs that run out of attempts in the queue's failed set, and removeOnFail decides how many are kept. A dead letter queue is a separate queue you create yourself: listen for the worker's failed event, copy jobs that used all their attempts into it, and replay them manually or on a schedule.
Can BullMQ process the same job twice?
Yes. If a worker crashes or loses its lock on a job, BullMQ marks the job as stalled and runs it again, even if the work was partly or fully done. For notifications, pass an idempotency key to the provider, or record each send in your database, so a rerun doesn't send a duplicate.

Prakash Kumar
SDE1
Prakash is a frontend-focused full-stack developer working with React, Next.js, TypeScript, and NestJS. He prioritises thoughtful architecture, maintainable code, and reliable frontend and backend systems.

