Skip to content

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.

  1. Install the package and its two runtime peers.

    Terminal window
    bun add @noctcore/jobs bullmq ioredis
    # or: pnpm add / npm install

    Peers: @nestjs/common and @nestjs/core 11 or 12, bullmq 6.3 or later (below 7), ioredis 5 or 6. Node 22 or later. Redis must run with maxmemory-policy noeviction, as BullMQ requires.

  2. 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.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
    });
  3. Register the module once, and the queues where they are used. AppConfig stands for your own configuration service.

    app.module.ts
    // app.module.ts
    import { 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 {}
  4. 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.ts
    import { 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 with EnqueueUnavailableError within 3 seconds, so your request handler decides what to do instead of hanging.

  5. Process in a worker class, one per queue. job.name narrows job.data.

    mail.worker.ts
    // mail.worker.ts
    import { 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 name
    case '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 });
    }
    }
  6. Run something on a schedule with @Sweep. Each tick runs once across every replica.

    maintenance.sweeps.ts
    // maintenance.sweeps.ts
    import { 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.
    }
    }
  7. Stop cleanly. installGracefulShutdown drains the workers before the app closes.

    main.ts
    // main.ts
    import '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 });

BullMQ needs a Redis with noeviction:

Terminal window
docker run --rm -p 6379:6379 redis:7 redis-server --maxmemory-policy noeviction
REDIS_URL=redis://localhost:6379 node dist/main.js