Queue events and monitoring help you watch what happens inside your task queues. This lets you know if tasks are waiting, running, or done, so you can fix problems fast.
Queue events and monitoring in NestJS
import { Processor, Process, OnQueueEvent } from '@nestjs/bull'; import { Job } from 'bullmq'; @Processor('myQueue') export class MyQueueProcessor { @Process() async handleJob(job: Job) { // job processing code here } @OnQueueEvent('completed') onJobCompleted(event: any) { console.log('Job completed:', event.jobId); } @OnQueueEvent('failed') onJobFailed(event: any) { console.log('Job failed:', event.jobId, 'Reason:', event.failedReason); } }
Use @Processor('queueName') to define which queue to listen to.
@OnQueueEvent('eventName') listens to specific queue events like 'completed', 'failed', 'waiting', etc.
import { Processor, Process, OnQueueEvent } from '@nestjs/bull'; import { Job } from 'bullmq'; @Processor('emailQueue') export class EmailProcessor { @Process() async sendEmail(job: Job) { // send email logic } @OnQueueEvent('completed') onCompleted(event: any) { console.log(`Email job ${event.jobId} completed`); } }
import { Processor, Process, OnQueueEvent } from '@nestjs/bull'; import { Job } from 'bullmq'; @Processor('taskQueue') export class TaskProcessor { @Process() async runTask(job: Job) { // task logic } @OnQueueEvent('failed') onFailed(event: any) { console.error(`Task job ${event.jobId} failed: ${event.failedReason}`); } }
import { Processor, Process, OnQueueEvent } from '@nestjs/bull'; import { Job } from 'bullmq'; @Processor('emptyQueue') export class EmptyQueueProcessor { @Process() async processJob(job: Job) { // This queue might be empty sometimes } @OnQueueEvent('waiting') onWaiting(event: any) { console.log(`Job ${event.jobId} is waiting in the queue`); } }
This processor handles notification jobs. It logs when a job starts, and listens for completion or failure events to log the results.
import { Processor, Process, OnQueueEvent } from '@nestjs/bull'; import { Job } from 'bullmq'; @Processor('notificationQueue') export class NotificationProcessor { @Process() async sendNotification(job: Job) { console.log(`Processing notification job ${job.id}`); // Simulate success or failure if (job.data.fail) { throw new Error('Notification failed'); } return 'Notification sent'; } @OnQueueEvent('completed') onCompleted(event: any) { console.log(`Job ${event.jobId} completed successfully.`); } @OnQueueEvent('failed') onFailed(event: any) { console.log(`Job ${event.jobId} failed with reason: ${event.failedReason}`); } }
Queue events like 'completed' and 'failed' help you track job status in real time.
Listening to events does not block job processing; it runs alongside your job handler.
Common mistake: forgetting to handle errors inside the job, which can cause silent failures.
Queue events let you watch what happens to jobs in your queues.
Use @OnQueueEvent decorators to listen for events like 'completed' and 'failed'.
Monitoring queues helps you fix problems and improve your app's background work.
Practice
@OnQueueEvent decorators in NestJS queues?Solution
Step 1: Understand the role of
This decorator is used to listen for events emitted by the queue, such as when a job completes or fails.@OnQueueEventStep 2: Identify what
It does not create queues, configure concurrency, or delete jobs manually; it only listens to events.@OnQueueEventdoes not doFinal Answer:
To listen and react to specific queue events like job completion or failure -> Option BQuick Check:
@OnQueueEventlistens to events [OK]
@OnQueueEvent listens to queue events only [OK]- Thinking it creates or deletes queues
- Confusing event listening with queue configuration
- Assuming it manages job concurrency
@OnQueueEvent?Solution
Step 1: Recall the exact event name for job completion
The official event name emitted by NestJS queues for job completion is 'completed'.Step 2: Match the syntax with the correct event name
The syntax must use@OnQueueEvent('completed')to listen properly.Final Answer:
@OnQueueEvent('completed')\nhandleCompleted(job: Job) {\n // handle job completion\n} -> Option CQuick Check:
Event name is 'completed' exactly [OK]
@OnQueueEvent [OK]- Using incorrect event names like 'complete' or 'done'
- Misspelling the decorator syntax
- Not passing the event name as a string
@OnQueueEvent('failed')
handleFailed(job: Job, error: Error) {
console.log(`Job ${job.id} failed with error: ${error.message}`);
}Solution
Step 1: Analyze the event and handler parameters
The handler listens to the 'failed' event and receives the job and error objects.Step 2: Understand the console.log output
The log prints the job's id and the error's message in the format: "Job failed with error: ".Final Answer:
Job <job_id> failed with error: <error_message> -> Option AQuick Check:
Failed event logs job id and error message [OK]
- Ignoring job id in the log message
- Confusing 'failed' with 'completed' event
- Logging incomplete error information
@OnQueueEvent('completed')
handleCompleted() {
console.log('Job done');
} What is the likely problem?Solution
Step 1: Check the event handler signature
Event handlers for 'completed' receive the job object as a parameter, but this method has none.Step 2: Understand why missing parameters cause no trigger
Without the expected parameter, NestJS cannot properly call the handler, so it never triggers.Final Answer:
The handler is missing the job parameter to receive event data -> Option DQuick Check:
Event handlers need correct parameters [OK]
- Omitting parameters in event handlers
- Changing event names incorrectly
- Thinking handlers must be called manually
Solution
Step 1: Identify correct event names for job lifecycle
In NestJS queues, 'waiting' is emitted when a job is added, 'completed' when done, and 'failed' on failure.Step 2: Verify the other options' event names
Other options use incorrect or non-existent event names like 'added', 'done', 'error', 'start', 'finish', 'fail', 'enqueue', 'success', 'failure'.Final Answer:
Use @OnQueueEvent('waiting'), @OnQueueEvent('completed'), and @OnQueueEvent('failed') -> Option AQuick Check:
Correct event names: waiting, completed, failed [OK]
- Using wrong event names not recognized by NestJS
- Missing the 'waiting' event for job addition
- Confusing 'failed' with 'fail' or 'error'
Ready to prove it?
Pass the test and this pattern moves unknown
