Skip to content
All articles
8 min read

NestJS + BullMQ: Background Jobs That Don't Block Your API

Move slow work out of the request cycle. A practical guide to BullMQ queues in NestJS: producers, workers, retries, rate limits, and monitoring, with production-ready code.

Gusti Randa

Flutter & Full-Stack Developer

The Problem: Slow Work Inside the Request

Every NestJS API eventually grows a handler that does too much. Sending a welcome email, generating a PDF invoice, resizing an uploaded image, calling a slow third-party API. The request waits for all of it, the user stares at a spinner, and under load your server runs out of connections doing work nobody asked to wait for.

The fix is boring and reliable: move the slow work into a background job queue. The request enqueues a job and returns immediately. A worker picks the job up, does the work, retries on failure, and reports the result. Your API stays fast even when the work itself is slow.

This guide uses BullMQ, the Redis-backed queue library that has become the standard choice for Node.js. It covers the full production pattern: producer, worker, retries, rate limiting, and monitoring.

Why BullMQ

There are lighter options. You can spawn a setTimeout, run a cron job, or push work into a database table and poll it. All of them work until they do not. A process restart loses in-memory work. Polling a table adds latency and load. Cron cannot rate-limit per customer or retry with backoff.

BullMQ gives you, out of the box:

  • Persistent jobs in Redis, so a restart loses nothing
  • Automatic retries with exponential backoff
  • Delayed and scheduled jobs
  • Rate limiting per queue
  • Concurrency control per worker
  • Job events and a dashboard (Bull Board) for visibility

If your app already uses Redis for caching or sessions, adding BullMQ costs almost nothing.

Setup

Install the packages and the NestJS wrapper:

npm install @nestjs/bullmq bullmq
npm install -D @types/bullmq

Register the queue module with your Redis connection:

import { Module } from '@nestjs/common';
import { BullModule } from '@nestjs/bullmq';

@Module({
  imports: [
    BullModule.forRoot({
      connection: {
        host: process.env.REDIS_HOST ?? 'localhost',
        port: Number(process.env.REDIS_PORT ?? 6379),
        maxRetriesPerRequest: null,
      },
    }),
    BullModule.registerQueue({ name: 'emails' }),
    BullModule.registerQueue({ name: 'reports' }),
  ],
})
export class QueueModule {}

One detail that bites everyone once: maxRetriesPerRequest must be null. BullMQ uses blocking Redis connections, and the default ioredis retry behavior breaks them. Set it and forget it.

The Producer: Enqueue and Return Fast

A producer is any service that adds jobs to a queue. Keep it thin. The handler validates input, enqueues the job, and returns a 202 Accepted with a job id the client can poll if it needs the result.

import { Injectable } from '@nestjs/common';
import { InjectQueue } from '@nestjs/bullmq';
import { Queue } from 'bullmq';

@Injectable()
export class InvoiceService {
  constructor(@InjectQueue('reports') private reportsQueue: Queue) {}

  async requestInvoice(orderId: string) {
    const job = await this.reportsQueue.add(
      'generate-invoice-pdf',
      { orderId },
      {
        attempts: 3,
        backoff: { type: 'exponential', delay: 5000 },
        removeOnComplete: { count: 1000 },
        removeOnFail: { count: 5000 },
      },
    );

    return { jobId: job.id, status: 'queued' };
  }
}

Three decisions in this snippet matter in production. attempts: 3 with exponential backoff means a transient failure, like a PDF service blip, retries after 5, 10, then 20 seconds instead of hammering a broken dependency. removeOnComplete and removeOnFail cap how many finished jobs Redis keeps, so your queue history does not grow forever.

The Worker: Where the Work Happens

A worker is a separate class that BullMQ calls for each job. The @Processor decorator binds it to a queue, and each @Process method handles one job type.

import { Processor, WorkerHost, OnWorkerEvent } from '@nestjs/bullmq';
import { Job } from 'bullmq';
import { Logger } from '@nestjs/common';

@Processor('reports', { concurrency: 5 })
export class ReportsWorker extends WorkerHost {
  private readonly logger = new Logger(ReportsWorker.name);

  async process(job: Job<{ orderId: string }>) {
    this.logger.log(`Generating invoice for order ${job.data.orderId}`);

    const pdf = await this.pdfService.render(job.data.orderId);
    const url = await this.storageService.upload(pdf);

    await this.ordersService.markInvoiceReady(job.data.orderId, url);
    return { url };
  }

  @OnWorkerEvent('failed')
  onFailed(job: Job, error: Error) {
    this.logger.error(
      `Job ${job.id} failed after ${job.attemptsMade} attempts: ${error.message}`,
    );
  }
}

Concurrency of 5 means this worker processes five jobs at once. Tune it to the bottleneck: CPU-bound work wants a low number, I/O-bound work can go higher. If you run multiple app instances, each instance runs its own workers, and BullMQ distributes jobs across them automatically.

Structuring Jobs: Small, Idempotent, Serializable

Three rules keep a queue healthy over months of production use.

Keep jobs small. A job payload should be an id, not a blob. Pass { orderId } and let the worker fetch the current data. If the order changes between enqueue and processing, the worker uses fresh data instead of a stale snapshot.

Make jobs idempotent. A job may run twice. A worker can crash after sending the email but before marking the job complete, and BullMQ will retry it. Design every handler so a second run is harmless: check whether the invoice already exists before generating it, use a unique key when inserting records, or send the email with an idempotency key.

Keep payloads JSON-serializable. BullMQ stores jobs as JSON in Redis. No class instances, no Dates, no Buffers, no functions. Serialize to plain data at the producer and reconstruct at the worker.

Rate Limiting and Priority

Some work must not run at full speed. A queue that calls a third-party API with a 10-requests-per-second limit will get your key banned without a limiter. BullMQ supports this natively:

BullModule.registerQueue({
  name: 'emails',
  defaultJobOptions: {
    attempts: 5,
    backoff: { type: 'exponential', delay: 10000 },
  },
  limiter: { max: 10, duration: 1000 },
});

This caps the queue at 10 jobs per second. You can also set per-job priority when adding a job, so a password-reset email jumps ahead of a weekly digest:

await this.emailsQueue.add(
  'send-email',
  { to: user.email, template: 'reset-password' },
  { priority: 1 },
);

Lower numbers run first. Use priority sparingly. A queue full of priority-1 jobs is just a queue again.

Delayed and Recurring Jobs

Not every job should run now. BullMQ supports delays and repeatable jobs without a separate scheduler:

// Remind the user in 24 hours if they never completed checkout
await this.emailsQueue.add(
  'abandoned-cart-reminder',
  { cartId },
  { delay: 24 * 60 * 60 * 1000 },
);

// Generate the weekly report every Monday at 08:00
await this.reportsQueue.add(
  'weekly-summary',
  {},
  { repeat: { pattern: '0 8 * * 1' } },
);

Delayed jobs are useful for grace periods: send the reminder only if the user still has not finished, and have the worker check the current state before acting.

Monitoring: Never Run a Queue Blind

A queue you cannot see is a queue that fails silently. At minimum, log the failed and stalled events and alert on them. A stalled job means a worker died mid-processing, which usually points to a crash or an out-of-memory kill.

For day-to-day visibility, add Bull Board, a small dashboard that shows waiting, active, delayed, failed, and completed jobs per queue:

import { createBullBoard } from '@bull-board/api';
import { BullMQAdapter } from '@bull-board/api/bullMQAdapter';
import { ExpressAdapter } from '@bull-board/express';

const serverAdapter = new ExpressAdapter();
serverAdapter.setBasePath('/admin/queues');

createBullBoard({
  queues: [new BullMQAdapter(emailsQueue), new BullMQAdapter(reportsQueue)],
  serverAdapter,
});

Mount it behind your admin authentication. It is read-mostly, but it can retry and delete jobs, so never expose it publicly.

Scaling and Failure Modes

A few things to plan for before traffic grows:

  • Separate your workers from your API. When the queue is busy, workers compete with request handlers for CPU. Run workers in their own process or container so a PDF backlog never slows down login.
  • Redis is a single point of failure. If Redis goes down, producers cannot enqueue and workers stop. Use a managed Redis with persistence and a replica, and make your producer handle enqueue errors gracefully, returning 503 instead of crashing the request.
  • Watch the dead-letter pile. Jobs that exhaust their retries land in the failed set. Review them regularly. A job failing forever is usually a bug in the worker or bad data, not a queue problem.
  • Mind memory. A worker that loads a huge file into memory per job will eventually get killed. Stream large files, process in chunks, and set a sane concurrency.

When Not to Use a Queue

Queues add a moving part. Skip them when the work is fast and the caller genuinely needs the result: validating input, reading from the database, or rendering a page. A queue is for work that is slow, can happen later, or must survive a restart. If none of those apply, a direct function call is simpler and easier to debug.

The Pattern, Summarized

The request validates and enqueues. The worker does the slow work with retries. Payloads stay small and idempotent. Rate limits protect external services. Bull Board shows you what is happening. That is the whole pattern, and it scales from a side project to a production API serving thousands of requests per minute without changing shape.

Start with one queue and one job type. The moment your first email sends from a worker instead of blocking a request, you will wonder why you waited.

  • #NestJS
  • #TypeScript
  • #Backend
  • #BullMQ
  • #Queues