- Engineering
- DevOps
Node.js background jobs BullMQ and Redis Guide
Slow work doesn’t belong in a request. Offload it to a queue. Here’s how I structure reliable background jobs in Node.js with BullMQ and Redis.
Node.js background jobs BullMQ and Redis Guide
Sending an email, crawling a site, generating a report: anything that takes more than a moment should not block an HTTP response. The fix is a job queue for Node.js background jobs BullMQ. The API adds a job and returns right away, and a separate worker picks it up and does the slow part. If you work in Python too, I wrote about the same idea in FastAPI background tasks and retries.
This guide builds a small but production-minded setup in TypeScript: a queue, a worker, safe retries, a monitoring dashboard, and a recurring cron job.
What You Need First
- Node.js 18 or newer
- A running Redis instance (local Docker is fine)
- Packages:
bullmq,ioredis,express, and@bull-board/express
npm install bullmq ioredis express @bull-board/api @bull-board/express
docker run -d --name redis -p 6379:6379 redis:7A Queue and a Worker
Producers add jobs to a named queue. A worker, usually a separate process, pulls jobs off that queue and runs them. Keeping the worker apart from the API means you can scale and restart it on its own. On a single server you can run both under a process manager, as I do in my guide to Self-Hosting Next.js on a VPS with PM2 and Nginx.
First, a shared Redis connection. BullMQ workers need maxRetriesPerRequest set to null, or they will throw on blocking commands.
import IORedis from "ioredis";
export const connection = new IORedis(process.env.REDIS_URL ?? "redis://127.0.0.1:6379", {
maxRetriesPerRequest: null,
});Next, the queue itself. I set retry and cleanup rules once as defaults so every job gets them.
import { Queue } from "bullmq";
import { connection } from "./connection";
export const emailQueue = new Queue("email", {
connection,
defaultJobOptions: {
attempts: 5,
backoff: { type: "exponential", delay: 2000 }, // 2s, 4s, 8s, 16s...
removeOnComplete: { age: 3600, count: 1000 }, // keep 1 hour of history
removeOnFail: { age: 7 * 24 * 3600 }, // keep failures for 7 days
},
});Now the producer. This Express route adds a job and answers with 202 Accepted in a few milliseconds, no matter how slow the email provider is.
import express from "express";
import { emailQueue } from "./queue/email.queue";
const app = express();
app.use(express.json());
app.post("/signup", async (req, res) => {
const { userId, email } = req.body;
// ... create the user in your database here ...
await emailQueue.add(
"welcome-email",
{ userId, email },
{ jobId: `welcome-${userId}` } // same id = no duplicate job
);
res.status(202).json({ status: "queued" });
});
app.listen(3000, () => console.log("API on :3000"));
And the worker, which runs as its own process.
import { Worker } from "bullmq";
import { connection } from "./queue/connection";
import { sendEmail } from "./lib/mailer";
const worker = new Worker(
"email",
async (job) => {
if (job.name === "welcome-email") {
const { email } = job.data;
await sendEmail({ to: email, template: "welcome" });
}
},
{ connection, concurrency: 5 }
);
worker.on("completed", (job) => console.log(`done ${job.id}`));
worker.on("failed", (job, err) => console.error(`failed ${job?.id}: ${err.message}`));Make Jobs Safe to Retry
Jobs fail. Networks blip and third parties rate-limit you. BullMQ will retry with backoff, which means your handler must be idempotent: running it twice must not send two emails or charge a customer twice. Check whether the work is already done before you cause the side effect.
- Idempotency: ask "already done?" before the side effect, and record success after it.
- Backoff: use exponential delays so retries do not hammer a struggling service.
- Dead-letter: after the last attempt, keep the failed job so you can inspect it.
import type { Job } from "bullmq";
import { connection } from "../queue/connection";
import { sendEmail } from "../lib/mailer";
export async function sendWelcome(job: Job) {
const doneKey = `done:welcome:${job.data.userId}`;
// 1. Already finished on an earlier attempt? Skip.
if (await connection.get(doneKey)) return;
// 2. Do the side effect. Pass an idempotency key if your provider supports it.
await sendEmail({
to: job.data.email,
template: "welcome",
idempotencyKey: String(job.id),
});
// 3. Mark it done, and keep the marker for a day.
await connection.set(doneKey, "1", "EX", 86400);
}One note on custom job ids: BullMQ ignores a new job if one with the same id is still stored. Because we clean up completed jobs after an hour, the same id can be added again later. If you need a hard guarantee, keep a unique record in your database as well.
A simple dead-letter setup
BullMQ does not have a built-in dead-letter queue. A failed job simply stays in the failed set once attempts run out. I like to copy those jobs to a separate queue and alert on it.
import { Queue } from "bullmq";
import { connection } from "./queue/connection";
const deadQueue = new Queue("email-dead", { connection });
worker.on("failed", async (job, err) => {
if (!job) return;
const maxAttempts = job.opts.attempts ?? 1;
if (job.attemptsMade >= maxAttempts) {
await deadQueue.add("dead-email", {
original: job.data,
reason: err.message,
failedAt: new Date().toISOString(),
});
// send a Slack or email alert here
}
});Watch What Is Happening
A queue you cannot see is a liability. I put a dashboard called Bull Board behind authentication so I can watch the waiting, active, and failed counts. It is the same mindset as monitoring incoming webhooks when I do Shopify Webhook Verification: Raw Body HMAC in Node.js.
import { createBullBoard } from "@bull-board/api";
import { BullMQAdapter } from "@bull-board/api/bullMQAdapter";
import { ExpressAdapter } from "@bull-board/express";
import { emailQueue } from "./queue/email.queue";
const serverAdapter = new ExpressAdapter();
serverAdapter.setBasePath("/admin/queues");
createBullBoard({
queues: [new BullMQAdapter(emailQueue)],
serverAdapter,
});
// requireAdmin is your own auth middleware. Never expose this publicly.
app.use("/admin/queues", requireAdmin, serverAdapter.getRouter());
// When the failed count climbs, that is your alert. You can also read counts in code and send them to your monitoring tool:
const counts = await emailQueue.getJobCounts("waiting", "active", "failed", "delayed");
console.log(counts); // { waiting: 3, active: 5, failed: 0, delayed: 1 }Recurring Jobs and Cron Workers
For scheduled work like a nightly report, use a job scheduler. It stores the schedule in Redis, so you will not get duplicates when you run several instances. Job schedulers need BullMQ 5.16 or newer.
import { emailQueue } from "./queue/email.queue";
await emailQueue.upsertJobScheduler(
"daily-report",
{ pattern: "0 6 * * *" }, // every day at 06:00
{ name: "daily-report", data: { type: "sales" } }
);
Shut Down Cleanly and Run in Production
On deploy or restart, let the worker finish its current job instead of killing it halfway.
async function shutdown() {
await worker.close(); // waits for active jobs to finish
process.exit(0);
}
process.on("SIGTERM", shutdown);
process.on("SIGINT", shutdown);module.exports = {
apps: [
{ name: "api", script: "dist/server.js", instances: 2, exec_mode: "cluster" },
{ name: "worker", script: "dist/worker.js", instances: 2 },
],
};Common Mistakes
- Running the worker inside the API process. A heavy job will slow your HTTP requests. Keep them apart.
- Skipping idempotency. Retries are guaranteed to happen eventually, so duplicates will too.
- Never cleaning old jobs. Without
removeOnCompleteandremoveOnFail, Redis memory keeps growing. - Putting big payloads in jobs. Store the data in your database and pass only the id.
- Leaving the dashboard open. Bull Board shows job data. Always protect it.
Key Takeaways
A queue gives you a fast API, work that survives restarts, clean retries, and a system you scale by adding more workers. Keep the worker separate, make every job idempotent, retry with exponential backoff, keep failed jobs around, and watch the failed count.
FAQ
What is BullMQ used for in Node.js?
BullMQ is a Redis-based job queue. You use it to run slow or unreliable tasks in the background, such as emails, report generation, image processing, and webhooks, without blocking an API request.
What is the difference between Bull and BullMQ?
BullMQ is the newer rewrite of Bull, written in TypeScript and actively maintained. Use BullMQ for new projects.
Does BullMQ need its own Redis instance?
No, but it needs a Redis that is set to not evict keys. Set maxmemory-policy to noeviction, or Redis may delete your jobs under memory pressure.
How many times will BullMQ retry a failed job?
As many times as you set in the attempts option. The default is one attempt, so set it yourself and add a backoff.
Related posts
Verifying Shopify Session Tokens in FastAPI
Learn how to validate JWT session tokens from Shopify App Bridge inside a Python FastAPI backend.
Read articleModeling DynamoDB Many to Many Relationships with Adjacency Lists
Learn how to structure many-to-many relationships in DynamoDB using single-table design and adjacency lists for fast, dual-direction querying.
Read articleRotating Secrets in AWS Secrets Manager FastAPI Services
Learn how to fetch, cache, and rotate database credentials dynamically in FastAPI using AWS Secrets Manager and SQLAlchemy without application downtime.
Read article