In NestJS, why is it beneficial to handle heavy tasks using background processing?
Think about how the app behaves when it has to do many things at once.
Background processing lets the main app handle user requests quickly by moving heavy tasks to separate workers. This keeps the app responsive.
Consider a NestJS app that processes a large file upload directly on the main thread. What is the likely effect on the app's behavior?
Think about what happens when one big job blocks everything else.
Running heavy tasks on the main thread blocks other operations, causing the app to freeze until the task completes.
Which code snippet correctly defines a background job processor using the Bull module in NestJS?
import { Processor, Process } from '@nestjs/bull'; import { Job } from 'bull'; @Processor('email') export class EmailProcessor { @Process('send') async handleSendEmail(job: Job) { // send email logic } }
Look for decorators that connect the class and method to the queue and job.
The @Processor decorator marks the class as a queue processor. The @Process decorator marks methods to handle specific jobs.
Given this NestJS Bull processor code, why might the background job never execute?
import { Processor, Process } from '@nestjs/bull'; import { Job } from 'bull'; @Processor('notifications') export class NotificationProcessor { async handleNotification(job: Job) { console.log('Processing notification'); } }
Check if the method is properly marked to handle jobs.
Without the @Process decorator, the method is not linked to any job and will not be called by Bull.
Consider this NestJS controller code that adds a heavy task to a Bull queue. What will the client receive immediately after calling the endpoint?
import { Controller, Post } from '@nestjs/common'; import { InjectQueue } from '@nestjs/bull'; import { Queue } from 'bull'; @Controller('tasks') export class TasksController { constructor(@InjectQueue('heavy') private heavyQueue: Queue) {} @Post('start') async startHeavyTask() { await this.heavyQueue.add('process', { data: 'big job' }); return { status: 'Task queued' }; } }
Think about what happens when you add a job to a queue instead of running it directly.
Adding a job to the queue is fast and returns immediately. The heavy task runs separately, so the client gets a quick confirmation.