Background Jobs in Node.js With BullMQ
Sending emails, generating PDFs, resizing images, calling slow APIs, running AI summaries — these shouldn't happen inside the HTTP request. Put them in a queue and process them in the background.
BullMQ Basics
// queue.js
import { Queue } from 'bullmq';
export const emailQueue = new Queue('email', { connection: { url: process.env.REDIS_URL } });
// in your route
await emailQueue.add('welcome', { userId: user.id }, {
attempts: 5,
backoff: { type: 'exponential', delay: 2000 },
});
res.status(202).json({ status: 'queued' });
Worker
import { Worker } from 'bullmq';
new Worker('email', async (job) => {
const user = await db.users.findById(job.data.userId);
await sendWelcomeEmail(user);
}, { connection: { url: process.env.REDIS_URL }, concurrency: 10 });
Run workers as separate processes from your API so they scale independently.
Features
- Retries with backoff for transient failures
- Delayed jobs — send a reminder in 24 hours
- Repeatable jobs — cron-style schedules
- Priorities
- Rate limiting — respect third-party API limits
- Flows — parent/child job dependencies
Idempotency
Jobs can run more than once (retries, crashes). Make handlers safe to repeat — e.g. check whether the email was already sent.
Monitoring
- Track failed jobs and queue length
- Use a dashboard (Bull Board or similar)
- Alert when queues back up
Queues make your API fast and your system resilient. Anything slow or unreliable belongs in the background.