Getting started
This page builds one queue end to end: a mail queue with two typed jobs, a service that enqueues one, a worker that processes both, an hourly sweep, and a shutdown that waits for running jobs. Every sample with a file name on this site is compiled against the package’s sources when the site builds, so it matches the current API.
-
Install the package and its two runtime peers.
Terminal window bun add @noctcore/jobs bullmq ioredis# or: pnpm add / npm installPeers:
@nestjs/commonand@nestjs/core11 or 12,bullmq6.3 or later (below 7),ioredis5 or 6. Node 22 or later. Redis must run withmaxmemory-policy noeviction, as BullMQ requires. -
Define the queue, its policy and its typed jobs, in a file both producers and workers import. The policy fields are all required; see Queues and policies.
mail.queue.ts // mail.queue.tsimport { 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, jitteredkeep: { completed: '1d', failed: '14d' },concurrency: 10,pace: { max: 50, per: '1s' }, // all replicas}); -
Register the module once, and the queues where they are used.
AppConfigstands for your own configuration service.app.module.ts // app.module.tsimport { Module } from '@nestjs/common';import { JobsModule } from '@noctcore/jobs';import { mail } from './mail.queue';import { MailWorker } from './mail.worker';import { MaintenanceSweeps } from './maintenance.sweeps';import { SignupService } from './signup.service';import { AppConfig, Mailer, TokenStore } from './support';@Module({imports: [JobsModule.forRootAsync({inject: [AppConfig],useFactory: (config: AppConfig) => ({ redisUrl: config.get('REDIS_URL') }),}),JobsModule.forFeature([mail]),],providers: [AppConfig, Mailer, TokenStore, SignupService, MailWorker, MaintenanceSweeps],})export class AppModule {} -
Enqueue, choosing a dedupe every time. Here a second welcome mail for the same user within a day is dropped. See Dedupe for the four kinds.
signup.service.ts // signup.service.tsimport { Injectable } from '@nestjs/common';import { InjectQueue, JobQueue, dedupe } from '@noctcore/jobs';import { mail, type MailJobs } from './mail.queue';@Injectable()export class SignupService {constructor(@InjectQueue(mail) private readonly mail: JobQueue<MailJobs>) {}async onSignedUp(userId: string): Promise<void> {await this.mail.add('welcome', { userId }, { dedupe: dedupe.window(['welcome', userId], '1d') });}}add()resolves to{ id }. When the dedupe dropped the call, the id is that of the job already holding the key. While Redis is unreachable it rejects withEnqueueUnavailableErrorwithin 3 seconds, so your request handler decides what to do instead of hanging. -
Process in a worker class, one per queue.
job.namenarrowsjob.data.mail.worker.ts // mail.worker.tsimport { JobHost, Worker, type JobOf } from '@noctcore/jobs';import { mail, type MailJobs } from './mail.queue';import { Mailer } from './support';@Worker(mail)export class MailWorker extends JobHost<typeof mail> {constructor(private readonly mailer: Mailer) {super();}async handle(job: JobOf<MailJobs>): Promise<void> {switch (job.name) {case 'welcome':return this.mailer.sendWelcome(job.data.userId); // job.data is typed per namecase 'receipt':return this.mailer.sendReceipt(job.data.orderId);}}override onFinalFailure(job: JobOf<MailJobs>, error: unknown): void {this.logger.error({ message: 'Mail gave up', job: job.name, id: job.id, error });}} -
Run something on a schedule with
@Sweep. Each tick runs once across every replica.maintenance.sweeps.ts // maintenance.sweeps.tsimport { Injectable } from '@nestjs/common';import { Sweep, type SweepContext } from '@noctcore/jobs';import { TokenStore } from './support';@Injectable()export class MaintenanceSweeps {constructor(private readonly tokens: TokenStore) {}@Sweep('expired-tokens', { cron: '15 * * * *', tz: 'UTC' })async purgeExpiredTokens(ctx: SweepContext): Promise<void> {await this.tokens.deleteExpiredBefore(ctx.scheduledAt);}@Sweep('heartbeat', { every: '1m' })async heartbeat(): Promise<void> {// A sweep that does nothing still proves the scheduler is alive:// alert on jobs_sweep_last_success_timestamp_seconds going stale.}} -
Stop cleanly.
installGracefulShutdowndrains the workers before the app closes.main.ts // main.tsimport 'reflect-metadata';import { NestFactory } from '@nestjs/core';import { installGracefulShutdown } from '@noctcore/jobs';import { AppModule } from './app.module';import { flushTelemetry } from './telemetry';const app = await NestFactory.createApplicationContext(AppModule);// Instead of app.enableShutdownHooks(), never together with it.installGracefulShutdown(app, { flush: flushTelemetry });
Run it locally
Section titled “Run it locally”BullMQ needs a Redis with noeviction:
docker run --rm -p 6379:6379 redis:7 redis-server --maxmemory-policy noevictionREDIS_URL=redis://localhost:6379 node dist/main.js- Queues and policies: what each policy field does and what does not compile.
- Workers and JobHost: final failures, fatal errors and pausing a queue.
- Migrating from @nestjs/bullmq, one queue at a time.