Background jobs and queues
Overview
Some work doesn’t belong in the request–response cycle:
- Slow: generating a PDF certificate, resizing images, transcoding video, importing a 50,000-row CSV.
- Unreliable: sending email, calling a payment provider’s webhook, posting to a third-party API that sometimes times out.
- Not urgent: updating search indexes, recalculating statistics, cleaning up old data.
If a sign-up request waits for the welcome email to send, the user waits too — and if the mail service is down, the sign-up fails for a reason the user doesn’t care about. Better: record the work as a job, respond immediately, and let a separate worker do it.
Why not just setTimeout or a promise you don’t await?
app.post('/signup', async (req, res) => {
const user = await authService.register(req.validated.body);
sendWelcomeEmail(user).catch(console.error); // ✗ fire and forget
res.status(201).json(user);
});This responds quickly, but:
- If the process restarts (a deployment, a crash), in-progress work is lost.
- There are no retries when the mail service hiccups.
- Heavy work still runs on the same event loop that serves requests.
- You can’t see what’s pending or what failed.
A job queue solves all four.
BullMQ
BullMQ is the most popular job queue for Node.js. It stores jobs in Redis, so they survive restarts and are shared by all your processes.
npm install bullmqProducing jobs
// src/queues.js
import { Queue } from 'bullmq';
const connection = { url: process.env.REDIS_URL };
export const emailQueue = new Queue('emails', { connection });app.post('/signup', validate({ body: registerSchema }), async (req, res) => {
const user = await authService.register(req.validated.body);
await emailQueue.add(
'welcome', // job name
{ userId: user.id }, // job data — keep it small and JSON-friendly
{
attempts: 5, // try up to 5 times
backoff: { type: 'exponential', delay: 2000 }, // 2 s, 4 s, 8 s, 16 s…
removeOnComplete: 1000, // keep the last 1000 successes
removeOnFail: 5000, // keep failures to inspect
},
);
res.status(201).json(user);
});Put IDs in job data rather than whole objects. The worker can load fresh data when it runs — which might be minutes later.
Processing jobs
Workers usually run as a separate process (or container), so heavy jobs never slow down your API:
// src/worker.js
import { Worker } from 'bullmq';
import { usersRepo } from './users/users.repository.js';
import { mailer } from './mailer.js';
const connection = { url: process.env.REDIS_URL };
const worker = new Worker(
'emails',
async (job) => {
switch (job.name) {
case 'welcome': {
const user = await usersRepo.findById(job.data.userId);
if (!user) return; // deleted since — nothing to do
await mailer.send({ to: user.email, template: 'welcome', data: { name: user.name } });
break;
}
default:
throw new Error(`Unknown job ${job.name}`);
}
},
{ connection, concurrency: 5 }, // up to 5 jobs at once in this process
);
worker.on('failed', (job, err) => {
console.error(`Job ${job?.id} (${job?.name}) failed on attempt ${job?.attemptsMade}:`, err.message);
});{ "scripts": { "start": "node src/server.js", "worker": "node src/worker.js" } }If the job function throws, BullMQ retries it according to attempts and backoff. After the last attempt it’s moved to the failed set, where you can inspect it, fix the cause, and retry it — dashboards such as Bull Board show all of this in a browser.
Idempotent jobs
Retries mean a job may run more than once — for example, if the email was sent but the worker crashed before recording success. Design jobs so that running twice is harmless:
- Record what was done (
welcome_email_sent_at) and skip if it’s already set. - Pass idempotency keys to external APIs (payment providers support them).
- Prefer “set to X” over “add 1”.
You can also give a job a fixed jobId (for example welcome-${userId}) so adding the same job twice doesn’t create a duplicate.
Delayed and repeating jobs
// Remind the learner in 3 days
await emailQueue.add('nudge', { userId }, { delay: 3 * 24 * 60 * 60 * 1000 });
// Every night at 02:00 — a scheduled job (cron syntax)
await reportsQueue.upsertJobScheduler('nightly-stats', { pattern: '0 2 * * *' }, { name: 'stats' });Running scheduled work through the queue (instead of setInterval in your API) means it runs once, even when you have ten API instances.
Other patterns
- Smoothing spikes: a flood of 10,000 uploads becomes a queue that workers drain at a steady pace, instead of overwhelming your server.
- Rate-limited workers: BullMQ can limit how many jobs per second hit a fussy external API.
- Progress:
job.updateProgress(40)lets you show progress bars for long jobs. - Graceful shutdown: on
SIGTERM, callawait worker.close()— it stops taking new jobs and waits for the current ones to finish.
Other tools
If you’d rather not run Redis, pg-boss and Graphile Worker use PostgreSQL as the queue. Cloud platforms offer managed queues (Amazon SQS, Google Cloud Tasks) and scheduled functions. The concepts — producers, workers, retries, idempotency — are identical.
Rule of thumb: if a user doesn’t need the result to see the next screen, or if it talks to a service you don’t control, it probably belongs in a job.
A welcome-email job
Create a BullMQ queue emails. After sign-up, add a welcome job with the user's email and name, retried up to 5 times with exponential backoff starting at 2 seconds. Write a worker that sends the email (simulate with a function that fails randomly) and logs completed and failed jobs.
import { Queue, Worker } from 'bullmq';
const connection = { host: 'localhost', port: 6379 };
// your code hereimport { Queue, Worker } from 'bullmq';
const connection = { host: 'localhost', port: 6379 };
export const emailQueue = new Queue('emails', { connection });
// in the sign-up handler, after saving the user:
await emailQueue.add(
'welcome',
{ to: user.email, name: user.name },
{ attempts: 5, backoff: { type: 'exponential', delay: 2000 }, removeOnComplete: 1000, removeOnFail: 5000 },
);
// worker.js — run as a separate process
async function sendEmail({ to, name }) {
if (Math.random() < 0.3) throw new Error('Mail service unavailable');
console.log(`Welcome email sent to ${name} <${to}>`);
}
const worker = new Worker('emails', async (job) => {
if (job.name === 'welcome') await sendEmail(job.data);
}, { connection, concurrency: 5 });
worker.on('completed', (job) => console.log(`✓ ${job.name} ${job.id}`));
worker.on('failed', (job, err) => console.error(`✗ ${job?.name} ${job?.id} (attempt ${job?.attemptsMade}):`, err.message));Summary
- Don’t make users wait for slow or unreliable work — queue it and respond straight away.
- A queue (e.g. BullMQ on Redis) stores jobs durably; separate worker processes run them.
- Configure retries with exponential backoff, and keep failed jobs for inspection.
- Make jobs idempotent: a retried job must not send two emails or charge twice.
- Queues also schedule repeating work and smooth out traffic spikes.