Skip to content

Background jobs for NestJS

Jobs without the traps.

A thin layer over BullMQ 6 for NestJS. Typed queues, a dedupe on every enqueue, jittered and bounded retries, sweeps that run once per tick, and a shutdown that waits for running jobs.

bun add @noctcore/jobs bullmq ioredis

0.x on npm. NestJS 11 or 12, BullMQ 6, Node 22 or later.

Two paths. One job from add() to completed: the producer refuses at once while Redis is down so a request never hangs, the hashed dedupe key drops a repeat, the queue policy's jittered backoff spaces retries so a failed attempt goes back through it instead of a retry storm, and a JobHost worker runs the job. One sweep on two replicas: both upsert the same scheduler, Redis holds one, and each tick runs once.

One file, both sides.

A queue is defined once, with its policy and its jobs, in a file that producers and workers both import. Every field BullMQ would leave to a default is required here.

  1. attempts is a literal from 2 to 20, or 'once'.
  2. A retry needs expo() or fixed(), jittered by default.
  3. keep bounds completed and failed jobs, always with an age.
mail.queue.ts
// mail.queue.ts
import { defineQueue, expo } from '@noctcore/jobs';
export type MailJobs = {
welcome: { userId: string };
receipt: { orderId: string };
};
export const mail = defineQueue<MailJobs>('mail', {
attempts: 5,
backoff: expo('2s'), // 2s, 4s, 8s, 16s, jittered
keep: { completed: '1d', failed: '14d' },
concurrency: 10,
pace: { max: 50, per: '1s' }, // all replicas
});

What it refuses to do

No silent default
Attempts, backoff, retention, concurrency and a dedupe on every add() are choices you write down. A single attempt is spelled 'once'; no dedupe is spelleddedupe.none().
No caller jobId
BullMQ assigns every id. A dedupe goes through its own Redis key, hashed with SHA-256, so it never depends on how long a job is kept.
No hanging enqueue
Producers and workers get opposite Redis policies on separate connections. Anadd() either lands or fails within its bound.
No zoneless cron
A sweep's cron needs its tz, and a renamed sweep is removed from Redis at boot.
No vendor SDK
Metrics, tracing and error reporting are three small interfaces. The adapters take the prom-client, OpenTelemetry or Sentry module you already have.

Six things to learn

  • defineQueueA queue, its typed jobs and its policy, in one file both sides import.
  • JobsModuleforRoot or forRootAsync once, forFeature where the queues are used.
  • queue.addTyped by the queue, with a required dedupe, bounded by the producer timeout.
  • @Worker + JobHostOne worker class per queue: handle, onFinalFailure, classify, pauseQueue.
  • @SweepA method on a schedule, once per tick across every replica.
  • installGracefulShutdownDrains workers before the app closes, then flushes telemetry.