Background jobs in Node.js with BullMQ
By Flavio
Updated
Tagged: Node.js
Build a reliable Node.js background job queue with BullMQ and Redis, including workers, retries, backoff, progress, concurrency, and idempotency.
Some tasks shouldn’t run while a user is sitting there waiting for an HTTP response. Sending an email, resizing an image, generating a PDF, or importing a big CSV can take seconds, and any of them can fail because of a third-party outage you don’t control. Running all of that inside a request handler makes your endpoint slow and fragile.
With a background job queue, your web server records what needs to happen and responds right away, while a separate worker process does the work. In this tutorial we’ll build an email queue using BullMQ and Redis, complete with retries, exponential backoff, progress tracking, concurrency, and the part that saves you in production: making jobs safe to run more than once.
How the queue fits together
The setup has three moving parts:
Your application acts as the producer and pushes jobs onto the queue, Redis holds the job payloads and queue state, and the worker picks up waiting jobs and executes them. BullMQ is a Node.js library that coordinates this queue behavior on top of your own Redis instance, so there’s no separate hosted queue service to sign up for.
Start Redis
Docker is the quickest way to spin up a local Redis instance:
docker run --name jobs-redis \
-p 6379:6379 \
redis:7-alpine
Next, set up a fresh Node.js project and install the dependencies:
mkdir bullmq-email-queue
cd bullmq-email-queue
npm init -y
npm install bullmq express ioredis
Open package.json and add "type": "module" so we can use ES module imports across the project.
Create the queue
Start by putting the Redis connection config in its own file, connection.js:
export const connection = {
host: process.env.REDIS_HOST || '127.0.0.1',
port: Number(process.env.REDIS_PORT || 6379),
}
Keeping these options in a plain module means importing them won’t open a Redis connection or instantiate a queue by side effect.
With that in place, create queue.js to define the queue and its default job behavior:
import { Queue } from 'bullmq'
import { connection } from './connection.js'
export const emailQueue = new Queue('emails', {
connection,
defaultJobOptions: {
attempts: 5,
backoff: {
type: 'exponential',
delay: 1000,
},
removeOnComplete: {
age: 24 * 60 * 60,
count: 1000,
},
removeOnFail: {
age: 7 * 24 * 60 * 60,
},
},
})
emailQueue.on('error', (error) => {
console.error('Queue error', error)
})
The queue name (emails) namespaces all the keys BullMQ writes to Redis, so your producers and workers need to use the same name and Redis connection. Those default options tell BullMQ to retry failed jobs up to five times with increasing delays, cap how many completed jobs stay in history, and keep failed jobs around for seven days. Setting cleanup rules upfront stops old job records from growing forever in Redis.
Add jobs from an API
Now let’s build an HTTP endpoint in server.js that accepts requests and enqueues email jobs:
import express from 'express'
import { emailQueue } from './queue.js'
const app = express()
app.use(express.json())
app.post('/welcome-email', async (request, response) => {
const { userId, email } = request.body
if (!userId || !email) {
return response.status(400).json({
error: 'userId and email are required',
})
}
const encodedUserId = Buffer.from(String(userId)).toString('base64url')
const jobId = `welcome-${encodedUserId}`
let job = await emailQueue.getJob(jobId)
if (!job) {
job = await emailQueue.add(
'send-welcome-email',
{
userId,
email,
},
{
jobId,
}
)
}
const status = await job.getState()
const terminal = status === 'completed' || status === 'failed'
response.status(terminal ? 200 : 202).json({
jobId: job.id,
status,
})
})
const server = app.listen(3000, () => {
console.log('API listening on http://localhost:3000')
})
const shutdown = async () => {
await new Promise((resolve, reject) => {
server.close((error) => {
if (error) {
reject(error)
} else {
resolve()
}
})
})
await emailQueue.close()
}
process.on('SIGTERM', shutdown)
process.on('SIGINT', shutdown)
Start the server:
node server.js
Then send a request to queue up a job:
curl -X POST http://localhost:3000/welcome-email \
-H 'content-type: application/json' \
-d '{"userId":"42","email":"me@example.com"}'
On the first call, you’ll get back 202 Accepted, which tells the caller we’ve queued the work even though it hasn’t finished yet. If you repeat the same request while Redis still holds that job, the endpoint reports its current state instead, returning 200 once the job has completed or failed because it’s no longer waiting in the queue.
Create a worker
Next, create worker.js to pull jobs off the emails queue and process them:
import { Worker } from 'bullmq'
import { connection } from './connection.js'
async function sendWelcomeEmail({ email }) {
console.log(`Sending welcome email to ${email}`)
await new Promise((resolve) => {
setTimeout(resolve, 1000)
})
}
const worker = new Worker(
'emails',
async (job) => {
if (job.name !== 'send-welcome-email') {
throw new Error(`Unknown job: ${job.name}`)
}
await job.updateProgress(10)
await sendWelcomeEmail(job.data)
await job.updateProgress(100)
return {
sentAt: new Date().toISOString(),
}
},
{
connection,
concurrency: 5,
}
)
worker.on('completed', (job, result) => {
console.log(`Job ${job.id} completed`, result)
})
worker.on('failed', (job, error) => {
console.error(`Job ${job?.id} failed`, error.message)
})
worker.on('error', (error) => {
console.error('Worker error', error)
})
const shutdown = async () => {
await worker.close()
process.exit(0)
}
process.on('SIGTERM', shutdown)
process.on('SIGINT', shutdown)
Leave the API server running and start the worker in a second terminal:
node worker.js
You’ll see it pick up and process the waiting job right away. Whenever your worker throws an error, BullMQ marks that attempt as failed and, as long as retries are left, schedules the job to wait for its backoff delay before trying again.
Why retries need backoff
Say your email provider goes down for a minute. If your workers retry immediately, they’ll keep slamming a broken service and burn through all their attempts before it recovers. Exponential backoff spreads those retries out instead:
1 second
2 seconds
4 seconds
8 seconds
When a whole batch of jobs fails together, adding a bit of randomness (jitter) keeps them from all waking up and hammering the provider at the exact same second.
It also pays to separate temporary failures from permanent ones. Network timeouts, rate limits, and temporary service outages are worth retrying because they tend to clear up on their own. Invalid email addresses, malformed job data, and missing configuration won’t fix themselves no matter how many times you run the job. Validate the payload before you enqueue it, and classify errors in your worker whenever the external service gives you enough detail to tell them apart.
Make jobs idempotent
Message queues give you at-least-once processing. A worker can finish calling an external API and then crash before it tells Redis the job is done, which means BullMQ will hand that same job to another worker. Because of that, a job like send welcome email has to be safe to run more than once.
Setting a jobId in the producer stops duplicate jobs from being added while that ID is still retained in Redis, which helps, though you can’t rely on it alone since completed jobs eventually get removed. To make the action truly idempotent, record it in your own database under a unique operation key and pass that same key to the email provider when it supports idempotency keys:
async function sendWelcomeEmail({ userId, email }) {
const operationKey = `welcome-${userId}`
const delivery = await database.emailDelivery.upsert({
where: {
operationKey,
},
create: {
operationKey,
status: 'pending',
},
update: {},
})
if (delivery.status === 'sent') {
return
}
const providerMessageId = await emailProvider.send({
to: email,
template: 'welcome',
idempotencyKey: operationKey,
})
await database.emailDelivery.update({
where: {
operationKey,
},
data: {
status: 'sent',
providerMessageId,
},
})
}
Put a unique constraint on operationKey in your database. Even if two workers happen to read the same pending row at the same time, passing the idempotency key ensures the email provider treats both requests as one send. If your provider doesn’t support idempotency keys, keep in mind there’s still a small window where a worker crashes right after the provider accepts the email and before your database marks it sent. Write every background job expecting that it might run more than once.
Report progress and status
For tasks with a visible outcome, like generating a report export, you’ll often want to let clients check progress. Here’s how to add a status endpoint:
app.get('/jobs/:id', async (request, response) => {
const job = await emailQueue.getJob(request.params.id)
if (!job) {
return response.status(404).json({
error: 'Job not found',
})
}
response.json({
id: job.id,
name: job.name,
state: await job.getState(),
progress: job.progress,
result: job.returnvalue,
failedReason: job.failedReason,
})
})
Avoid exposing raw job data publicly, since it often holds email addresses, file paths, or other private details. Authorize the request first and return only the fields the owner needs.
Listen to queue-wide events
Events emitted on a Worker instance only fire inside that specific worker process. When another service or process needs to watch completions and failures across the whole queue, use QueueEvents:
import { QueueEvents } from 'bullmq'
import { connection } from './connection.js'
const queueEvents = new QueueEvents('emails', {
connection,
})
queueEvents.on('completed', ({ jobId }) => {
console.log(`Job ${jobId} completed`)
})
queueEvents.on('failed', ({ jobId, failedReason }) => {
console.error(`Job ${jobId} failed: ${failedReason}`)
})
queueEvents.on('error', (error) => {
console.error('Queue events error', error)
})
const shutdown = async () => {
await queueEvents.close()
process.exit(0)
}
process.on('SIGTERM', shutdown)
process.on('SIGINT', shutdown)
Under the hood, BullMQ backs QueueEvents with Redis streams rather than standard Redis pub/sub, which gives them different delivery and retention behavior. One quick note if you run into older tutorials: current versions of BullMQ handle delayed jobs and stalled-job recovery without a separate QueueScheduler, so you don’t need to add one.
Concurrency and multiple workers
In our worker config, we set concurrency like this:
concurrency: 5
That lets one Node.js process work on five jobs at once. It helps a lot with I/O-heavy jobs that spend most of their time waiting on an external API, while CPU-heavy JavaScript still shares a single event loop. For CPU-heavy image or document processing, run multiple worker processes or use worker threads instead.
You can also run several copies of worker.js side by side, and BullMQ ensures only one worker reserves a given job at a time. Start with low concurrency and measure how your system responds before bumping it up, keeping an eye on:
- external API rate limits
- Redis load
- database connections
- memory use
- event-loop delay
Turning concurrency up too far can slow the whole system down once your database becomes the bottleneck.
Priorities, delays, and scheduled work
If a job shouldn’t run right away, pass a delay when you add it:
await emailQueue.add(
'send-reminder',
{
userId: '42',
},
{
delay: 60 * 60 * 1000,
}
)
For urgent jobs that should jump ahead in the queue, set a priority value (lower numbers have higher priority):
await emailQueue.add('send-password-reset', data, {
priority: 1,
})
BullMQ also supports Job Schedulers through queue.upsertJobScheduler() for recurring work. Just keep in mind that putting schedules in BullMQ makes Redis part of your scheduling infrastructure, so monitor it and configure backups that match your recovery needs.
Deploy producers and workers separately
Run your web application and your workers as separate processes in production:
web: node server.js
worker: node worker.js
Splitting them up lets you scale each tier independently. Your API might need ten instances while two workers keep up with the queue, or you might spin up twenty temporary workers for a large import without touching the web servers.
When you run Redis and BullMQ in production, a few operational defaults matter a lot:
- use a persistent Redis service
- enable authentication and TLS
- keep Redis off the public internet
- set Redis
maxmemory-policytonoeviction - monitor waiting, active, delayed, and failed counts
- alert on old waiting jobs, not just failed jobs
- shut workers down gracefully during deploys
That noeviction setting is easy to miss if you’re used to treating Redis as a cache. If Redis runs out of memory and starts evicting queue keys, it drops queue state and jobs silently disappear.
The important design rule
Pushing work into a queue gives you a way to retry, inspect, and recover from failures without keeping an HTTP request hanging open, even though the underlying failures still happen. Keep each job’s input data small and validated, stick to a stable job name, bound your retries with backoff, and build an idempotency strategy from the start. Add useful progress or result fields, wire up logs and metrics so you can spot stalled work early, and set a cleanup policy so old records don’t pile up in Redis.
Want me to talk about your product? You can sponsor this site.
Related posts about node: