Some work is too slow for a web request: sending 500 emails, making a PDF, resizing images, calling a slow API. If the user waits for it, the page feels broken and a timeout can kill the work half way. The answer is a job queue. The request puts a small description of the work on a list and replies at once. A separate worker takes the jobs one by one. This lesson shows the idea with a small queue that you can run, and then the production tool, BullMQ.
The idea in four words
- Producer: your route. It calls
queue.add(data)and returns immediately, usually with status 202 Accepted. - Queue: a waiting list. In production it lives in Redis, so it survives a restart.
- Worker: code that takes a job and does the slow work.
- Retries and dead letters: if a job fails, try again after a delay. After the last attempt, move it to a failed list that a person can look at, instead of losing it.
// A tiny in-memory job queue to teach the ideas: producers add jobs, a worker takes them one by one,
// failed jobs are retried with a delay, and the web request does not wait for the slow work.
export function createQueue({ handler, maxAttempts = 3, retryDelayMs = 10 }) {
const waiting = [];
const results = { done: 0, failed: [] };
let running = false;
async function run() {
if (running) return;
running = true;
while (waiting.length) {
const job = waiting.shift();
try {
await handler(job.data);
results.done += 1;
} catch (error) {
job.attempts += 1;
if (job.attempts >= maxAttempts) results.failed.push({ data: job.data, error: error.message }); // "dead letter"
else { await new Promise((r) => setTimeout(r, retryDelayMs * job.attempts)); waiting.push(job); }
}
}
running = false;
}
return {
results,
add(data) { waiting.push({ data, attempts: 0 }); queueMicrotask(run); }, // returns at once
async idle() { while (running || waiting.length) await new Promise((r) => setTimeout(r, 5)); },
};
}
// A cron-style schedule in plain Node: run something every N ms and stop cleanly.
export function every(ms, task) {
const timer = setInterval(task, ms);
timer.unref(); // does not keep the process alive by itself
return () => clearInterval(timer);
}
createQueue takes a handler. add pushes a job and returns at once. The loop inside run takes jobs one at a time. When the handler throws, the job's attempt count goes up, it waits a little longer each time, and goes back on the list. After maxAttempts it is saved in results.failed with the error message. That behaviour, retry with growing delay and then a failed list, is exactly what real queue systems offer.
- Make a folder and open it in a terminal. Run
npm init -y, then openpackage.jsonand add"type": "module"so thatimportworks. - Save the code as
jobs.js. The test uses only Node.
import test from 'node:test';
import assert from 'node:assert/strict';
import { createQueue, every } from './jb36-jobs.js';
test('jobs run, retry and end in the failed list', async () => {
const seen = [];
const attempts = new Map();
const queue = createQueue({
maxAttempts: 3,
handler: async (data) => {
seen.push(data.name);
const count = (attempts.get(data.name) ?? 0) + 1;
attempts.set(data.name, count);
if (data.name === 'flaky' && count < 3) throw new Error('temporary');
if (data.name === 'broken') throw new Error('always fails');
},
});
queue.add({ name: 'ok' });
queue.add({ name: 'flaky' });
queue.add({ name: 'broken' });
await queue.idle();
assert.equal(queue.results.done, 2); // ok + flaky (on its 3rd try)
assert.equal(attempts.get('broken'), 3);
assert.deepEqual(queue.results.failed.map((f) => f.data.name), ['broken']);
});
test('every() repeats and stops', async () => {
let ticks = 0;
const stop = every(10, () => { ticks += 1; });
await new Promise((r) => setTimeout(r, 55));
stop();
const after = ticks;
await new Promise((r) => setTimeout(r, 30));
assert.ok(after >= 3);
assert.equal(ticks, after);
});
ok 1 - jobs run, retry and end in the failed list
ok 2 - every() repeats and stops
Scheduled work
Some jobs are not triggered by a user but by the clock: send a daily report, delete expired tokens, back up the database. The simplest way in Node is setInterval, which the every helper wraps. Call unref() on the timer so that it does not keep the process alive on its own, and always return a stop function so that tests and shutdown can clean up. For schedules such as "every day at 02:00", use a cron expression with a library like node-cron, or better, the scheduler of your platform. If you run several copies of your app, make sure only one of them runs a scheduled job, or you will send every email several times.
BullMQ and Redis
A queue in the memory of your process has two flaws: jobs vanish when the process restarts, and you cannot run a worker on another machine. BullMQ keeps the jobs in Redis, so they survive restarts, several workers can share the load, and you get retries with backoff, delayed jobs, repeatable jobs, priorities, rate limits and a dashboard through tools such as Bull Board. The structure of the code is the same as the small version: a Queue to add jobs and a Worker that processes them.
// The production version with BullMQ and Redis. NOT run in this course (needs a Redis server):
// npm install bullmq and a Redis at REDIS_HOST / REDIS_PORT
import { Queue, Worker } from 'bullmq';
const connection = { host: process.env.REDIS_HOST ?? '127.0.0.1', port: Number(process.env.REDIS_PORT ?? 6379) };
export const emailQueue = new Queue('emails', { connection });
// In a route: add a job and answer the user straight away.
export const sendWelcomeLater = (to) =>
emailQueue.add('welcome', { to }, { attempts: 3, backoff: { type: 'exponential', delay: 2000 }, removeOnComplete: 100 });
// In a SEPARATE process (a worker), so slow work never blocks your API.
export const worker = new Worker(
'emails',
async (job) => {
// await mailer.send({ to: job.data.to, subject: 'Welcome' });
return { sent: job.data.to };
},
{ connection, concurrency: 5 },
);
worker.on('failed', (job, error) => console.error('Job failed', job?.id, error.message));
// A repeating job (cron style): every day at 02:00
// await emailQueue.add('daily-report', {}, { repeat: { pattern: '0 2 * * *' } });
- Make jobs idempotent: running the same job twice must be safe, because a retry may repeat work that half succeeded.
- Keep job data small, such as ids, not whole documents.
- Set sensible timeouts and attempt limits, and watch the failed list.
- Shut down workers gracefully, so that a running job can finish before the process exits.
Your task
- Make
addreturn a job id, and add astatus(id)method. - Write a job handler that sends a welcome email by using the fake mailer from lesson 28.
- Add a delay option so that a job runs after a number of seconds.
How to check it worked
- A job that fails twice and then works is retried and counted as done.
- A job that always fails ends up in the failed list.
- You can explain why jobs should be idempotent.