Run background jobs with a queue

12.6.0

Send slow work such as an export to a worker through a queue so the HTTP request can finish sooner.

On this page

Register a queue and add a job

Install @nestjs/bullmq and bullmq. Configure the Redis connection with BullModule.forRoot and register the named queue once in the module. Inject Queue into the service that adds work. An endpoint accepting work can return 202 and a job ID after enqueue succeeds.

// Inside the module's imports
BullModule.forRoot({ connection: { host: "127.0.0.1", port: 6379 } }),
BullModule.registerQueue({ name: "exports" }),

// Inside an injectable service
constructor(@InjectQueue("exports") private readonly queue: Queue) {}

enqueue(orderId: number) {
  return this.queue.add("order-csv", { orderId }, {
    attempts: 3,
    backoff: { type: "exponential", delay: 1000 },
  });
}

Process a job safely when it retries

Register the consumer in the providers list. WorkerHost uses one process method to handle jobs on that queue. A job can run again after a failure. Use the order ID or job ID as part of a stable output key and design the export service so another run has the same effect. Track failed jobs and queue wait time.

import { Processor, WorkerHost } from "@nestjs/bullmq";
import type { Job } from "bullmq";
import { ExportService } from "./export.service";

@Processor("exports")
export class ExportWorker extends WorkerHost {
  constructor(private readonly exports: ExportService) {
    super();
  }

  async process(job: Job<{ orderId: number }>) {
    if (job.name !== "order-csv") throw new Error("Unknown export job");
    return this.exports.writeOrderCsv(job.data.orderId);
  }
}

Official references