Background jobs handle time-consuming tasks without blocking user requests.
Queue Setup#
1import { Queue, Worker } from 'bullmq';
2import Redis from 'ioredis';
3
4const connection = new Redis(process.env.REDIS_URL);
5
6const emailQueue = new Queue('emails', { connection });
7
8// Add job
9await emailQueue.add('send-welcome', {
10 userId: '123',
11 email: 'user@example.com',
12}, {
13 attempts: 3,
14 backoff: { type: 'exponential', delay: 1000 },
15});Worker Processing#
1const worker = new Worker('emails', async (job) => {
2 const { email, template } = job.data;
3 await sendEmail(email, template);
4 return { sent: true };
5}, { connection, concurrency: 5 });
6
7worker.on('completed', (job) => console.log(`Job ${job.id} done`));
8worker.on('failed', (job, err) => console.error(`Job ${job?.id} failed`, err));Scheduling#
1// Delayed job
2await queue.add('reminder', data, { delay: 86400000 });
3
4// Recurring with cron
5await queue.add('daily-report', {}, {
6 repeat: { pattern: '0 9 * * *', tz: 'America/New_York' },
7});Rate Limiting#
1const limitedQueue = new Queue('api-calls', {
2 connection,
3 defaultJobOptions: {
4 rateLimiter: { max: 100, duration: 60000 },
5 },
6});Use queues for emails, image processing, reports, and any task not requiring immediate response.