Background processing lets your app do big jobs without slowing down what users see. It runs heavy tasks quietly behind the scenes.
0
0
Why background processing handles heavy tasks in NestJS
Introduction
Sending many emails after a user signs up
Processing large files uploaded by users
Running reports that take a long time
Handling tasks that don't need instant results
Offloading work to keep the app fast and responsive
Syntax
NestJS
import { Processor, Process } from '@nestjs/bull'; import { Job } from 'bull'; @Processor('queueName') export class MyProcessor { @Process('jobName') async handleJob(job: Job) { // heavy task code here } }
Use @Processor to define a background worker for a queue.
Use @Process to handle specific jobs from that queue.
Examples
This example shows a processor that sends emails in the background.
NestJS
import { Processor, Process } from '@nestjs/bull'; import { Job } from 'bull'; @Processor('email') export class EmailProcessor { @Process('sendEmail') async sendEmail(job: Job) { console.log('Sending email to', job.data.email); } }
This processor handles image resizing tasks without blocking the main app.
NestJS
import { Processor, Process } from '@nestjs/bull'; import { Job } from 'bull'; @Processor('file') export class FileProcessor { @Process('resizeImage') async resizeImage(job: Job) { // code to resize image } }
Sample Program
This NestJS processor runs in the background to send notifications. It logs the user ID and message without slowing down the main app.
NestJS
import { Processor, Process } from '@nestjs/bull'; import { Job } from 'bull'; @Processor('notifications') export class NotificationProcessor { @Process('sendNotification') async sendNotification(job: Job) { console.log(`Notifying user ${job.data.userId} with message: ${job.data.message}`); } }
OutputSuccess
Important Notes
Background tasks improve app speed by running heavy work separately.
Use queues like Bull with NestJS for easy background processing.
Always handle errors inside background jobs to avoid crashes.
Summary
Background processing keeps apps fast by running heavy tasks behind the scenes.
Use NestJS decorators @Processor and @Process to define background jobs.
This helps handle tasks like emails, file processing, and notifications smoothly.