Docs for the next release (prerelease). Install it with npm i @meghjs/cli@next. Latest release docs →

Next release (prerelease) · Latest docs →

Skip to content

Queue ​

A queue runs work in the background: sending mail, building a report, calling a slow API. The request adds a job and returns; a worker runs it.

There are two ways to work with jobs: a queue class, which both produces and consumes jobs, and a worker class, which only consumes a queue someone else fills.

TIP

For email you don't need your own queue: mailer.to(user.email).queue(mail) uses a built-in mail queue. See Mail.

Generate them

npx megh make:queue OrderExport and npx megh make:worker Report --queue reports write a queue or worker to fill in. See Generators.

Transports ​

Jobs live where the transport puts them:

TransportJobs live inNotes
memoryThis processThe default. Jobs are lost on restart
redisRedis, through BullMQEvery feature on this page
rabbitmqRabbitMQ, through messagingNo getJob, getJobs, clean, pause or resume

Everything is bundled with @meghjs/core, so there is nothing to install.

Megh picks a transport in this order:

  1. the transport option on @Queue or @MeghWorker;
  2. setQueueTransport();
  3. the MEGH_QUEUE_TRANSPORT environment variable;
  4. MEGH_MESSAGING_TRANSPORT, so queues follow messaging;
  5. memory.
sh
MEGH_QUEUE_TRANSPORT=redis
MEGH_REDIS_URL=rediss://default:secret@redis.internal:6379

With redis, the connection comes from the redis option, then MEGH_REDIS_URL, then MEGH_MESSAGING_URL when messaging also runs on Redis, then 127.0.0.1:6379.

The rabbitmq transport sends jobs through the messaging bus, so configure messaging for RabbitMQ too (MEGH_MESSAGING_TRANSPORT=rabbitmq and MEGH_MESSAGING_URL, or app.useMessaging()).

Production

With NODE_ENV=production, a queue refuses to start on memory unless you chose it: with transport: 'memory' on the queue, or setQueueTransport(). Jobs in memory vanish on restart and never reach other replicas.

A queue ​

Extend MeghQueue<T> and decorate it with @Queue. T is the shape of the job payload.

ts
import { MeghQueue, Queue, JobHandler, Job } from '@meghjs/core';

export type EmailPayload = {
  to: string;
  subject: string;
};

@Queue({
  name: 'email',
  transport: 'redis',
  redis: { url: process.env.REDIS_URL },
})
export class EmailQueue extends MeghQueue<EmailPayload> {
  constructor() {
    super();
  }

  @JobHandler('welcome')
  async sendWelcome(job: Job<EmailPayload>) {
    console.log(`Sending welcome mail to ${job.data.to}`);
  }

  @JobHandler('reset-password')
  async sendReset(job: Job<EmailPayload>) {
    console.log(`Sending reset mail to ${job.data.to}`);
  }
}

transport and redis are optional. Leave them out to take both from the environment.

WARNING

A @Queue class must declare a constructor that calls super(). Without one, resolving it through dependency injection gives it the wrong queue name. Inject other services through the same constructor.

Each @JobHandler('name') handles jobs added under that name. For jobs added without a name — or with a name no handler matches — define a handler method on the class, or pass handler in the decorator config.

@Queue options:

OptionDescription
nameQueue name. Required
transport'memory', 'redis' or 'rabbitmq'
redisRedis connection: { url?, host?, port?, username?, password?, db?, tls?, prefix? }
syncMemory only: run each job inside add(). For tests
worker{ concurrency? }, or false for a producer-only queue
handlerProcessor for jobs no @JobHandler matches
defaultJobOptionsOptions applied to every job added to this queue

Registering ​

useWorker resolves the class through the container, which is what starts its worker. Workers are closed automatically when the app shuts down.

ts
import { Megh } from '@meghjs/core';
import { EmailQueue } from './queues/email.queue';

const app = Megh.createApplication();

app.useWorker([EmailQueue]);

export default app;

Adding jobs ​

Inject the queue anywhere and call add:

ts
import { AppService } from '@meghjs/core';
import { EmailQueue } from '../queues/email.queue';

@AppService
export class SignupService {
  constructor(private readonly emailQueue: EmailQueue) {}

  async register(email: string) {
    await this.emailQueue.add('welcome', {
      to: email,
      subject: 'Welcome aboard',
    });
  }
}

Other producer methods:

ts
// run 30 seconds from now
await emailQueue.delay('welcome', { to, subject }, 30_000);

// add with job options
await emailQueue.add('welcome', { to, subject }, { attempts: 3, backoff: 1000 });

// inspect and control (memory and redis)
const job = await emailQueue.getJob(jobId);
await emailQueue.pause();
await emailQueue.resume();

Job options ​

JobOptions is the same on every transport:

OptionDescription
delayRun after this many milliseconds
attemptsTotal attempts, including the first. Default 1
backoffWait between attempts: ms, or { type: 'fixed' | 'exponential', delay }
jobIdYour own ID. On Redis, adding a second job with the same ID does nothing
priorityLower runs first. Redis only
removeOnCompleteRemove the job once it completes, or keep the newest N. Redis and memory
removeOnFailRemove the job once it fails, or keep the newest N. Redis and memory

A handler receives a Job<T>: id, name, data, queueName, attemptsMade, timestamp, opts, plus updateProgress() and log(). attemptsMade counts the current attempt, so it is 1 on the first run.

Producer-only queues ​

When another process consumes the jobs, pass worker: false. The queue only adds jobs and never starts a worker:

ts
@Queue({ name: 'report', worker: false })
export class ReportProducer extends MeghQueue<ReportPayload> {
  constructor() {
    super();
  }
}

A worker ​

When the producer lives elsewhere, extend MeghWorkerBase<T> and point @MeghWorker at the queue name. Implement process; the lifecycle hooks are optional.

ts
import { MeghWorker, MeghWorkerBase, Job } from '@meghjs/core';

export type ReportPayload = { reportId: number };

@MeghWorker({
  queue: 'report',
  concurrency: 5,
  transport: 'redis',
  redis: { url: process.env.REDIS_URL },
})
export class ReportWorker extends MeghWorkerBase<ReportPayload> {
  async process(job: Job<ReportPayload>) {
    return { generated: job.data.reportId };
  }

  onCompleted(job: Job<ReportPayload>, result: any) {
    console.log(`Report ${job.data.reportId} done`, result);
  }

  onFailed(job: Job<ReportPayload> | undefined, error: Error) {
    console.error(`Report failed:`, error.message);
  }
}

Register it the same way:

ts
app.useWorker([EmailQueue, ReportWorker]);

Decorating a class with @MeghWorker does not start it. A worker starts when it is registered with app.useWorker([...]) or when you call .start() yourself. isRunning() tells you whether it has started.

Errors thrown by onCompleted, onFailed and onError are caught and logged, so a faulty hook cannot crash the process. Failed jobs are always logged.

RabbitMQ ​

On rabbitmq, each queue is a message type, job:<queue>, with one consumer group, so replicas compete for jobs. attempts and backoff work as on Redis. A job that fails its last attempt is dead-lettered: list and retry it with megh messaging:failed.

RabbitMQ is a message broker, not a job store. getJob, getJobs, clean, pause and resume throw on this transport.

The engine underneath ​

raw() returns the engine's own queue object: BullMQ's Queue on Redis, the in-memory queue, or the AMQP connection on RabbitMQ. Use it for features Megh does not wrap. It is not covered by Megh's compatibility promise.

hasWorker() tells you whether the queue's worker has started, and transport which transport it runs on.

Running without Redis ​

The memory transport needs no broker. Jobs run asynchronously in-process and honour delay. It supports attempts, concurrency, pause and resume, and keeps failed jobs.

With sync: true, add() runs the job before it resolves and ignores delay. That suits tests:

ts
import { setQueueTransport, waitForMemoryQueues, resetMemoryQueues } from '@meghjs/core';

beforeAll(() => setQueueTransport('memory'));
afterEach(() => resetMemoryQueues());

it('sends a welcome mail', async () => {
  await signupService.register('a@example.com');
  await waitForMemoryQueues(); // wait for queued jobs to finish
  expect(mailer.sent).toHaveLength(1);
});

setQueueTransport('memory', { sync: true }) runs every job inline instead. setQueueTransport(undefined) goes back to the environment. Both apply to queues created afterwards.

To check which jobs were added without running them, use Messaging.fake().

Released under the MIT License.