Full answer
Why queues
- Respond fast: accept the request, queue the email, report or image resize, and return 202 or 201.
- Reliability: a job survives restarts and can be retried.
- Smoothing: workers process at their own speed, so spikes do not overload the database or an external API.
- Scaling: add worker processes without changing the web service.
BullMQ concepts (it stores state in Redis)
- Queue: producer side. queue.add('send-email', { to }, options).
- Worker: new Worker('emails', async (job) => { ... return result }, { connection, concurrency: 5 }). If the function throws, the job fails. If it returns, the job completes and the return value is stored.
- Job options: attempts and backoff (type fixed or exponential, delay), delay (run later), priority, removeOnComplete and removeOnFail (limit how much history stays in Redis), jobId (use for de-duplication).
- QueueEvents: listens to completed, failed and progress for any job in the queue.
- Repeatable jobs and schedulers run on a cron pattern.
- Flows for parent and child jobs, and rate limiting per queue.
Operational notes
- Redis configuration: workers need maxmemory-policy noeviction, otherwise Redis may evict queue data.
- Run workers as separate processes from the web server and handle graceful shutdown with worker.close().
- Jobs are delivered at least once. A job may run twice (after a crash or stalled lock), so the processor must be idempotent.
- Keep job data small (ids, not whole records), and JSON serialisable.
- Monitor with Bull Board or metrics: waiting, active, failed counts and age of the oldest job.
javascript
const { Queue, Worker, QueueEvents } = require('bullmq');
const url = new URL(process.env.REDIS_URL || 'redis://127.0.0.1:6379');
const connection = { host: url.hostname, port: Number(url.port) };
const name = `demo-emails-${process.pid}`;
async function main() {
const queue = new Queue(name, { connection });
const events = new QueueEvents(name, { connection });
await events.waitUntilReady();
const attemptsSeen = {};
const worker = new Worker(name, async (job) => {
attemptsSeen[job.data.to] = (attemptsSeen[job.data.to] || 0) + 1;
if (job.data.to === 'flaky@example.com' && job.attemptsMade < 1) throw new Error('temporary SMTP failure');
return { sent: job.data.to };
}, { connection, concurrency: 2 });
// Producers add jobs. The flaky one fails once and is retried after 20 ms.
const jobs = await Promise.all([
queue.add('send-email', { to: 'asha@example.com' }),
queue.add('send-email', { to: 'flaky@example.com' }, { attempts: 3, backoff: { type: 'fixed', delay: 20 } }),
queue.add('send-email', { to: 'later@example.com' }, { delay: 100 }),
]);
for (const job of jobs) {
const result = await job.waitUntilFinished(events);
console.log(job.data.to.padEnd(18), 'result:', JSON.stringify(result), '| attempts run:', attemptsSeen[job.data.to]);
}
const counts = await queue.getJobCounts('waiting', 'active', 'delayed', 'completed', 'failed');
console.log('counts:', JSON.stringify(counts));
await worker.close();
await events.close();
await queue.obliterate({ force: true });
await queue.close();
}
main();Three jobs are queued: a normal one, one that fails once and is retried, and a delayed one. The script needs a running Redis server. Install first with npm install bullmq (run here with bullmq 6.7.12). Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): asha@example.com result: {"sent":"asha@example.com"} | attempts run: 1 flaky@example.com result: {"sent":"flaky@example.com"} | attempts run: 2 later@example.com result: {"sent":"later@example.com"} | attempts run: 1 counts: {"waiting":0,"active":0,"delayed":0,"completed":3,"failed":0}
Key points
- A queue moves slow work out of the request path.
- Producers add jobs and workers process them from Redis.
- attempts and backoff handle retries; delay schedules a later run.
- Delivery is at least once, so processors must be idempotent.
- Run workers separately and close them gracefully.
Common mistakes
- Doing slow work inside the HTTP request.
- Assuming a job runs exactly once.
- Storing large payloads in the job data.
- Never removing completed jobs, so Redis memory grows.
- Running workers inside the web process with no graceful shutdown.
Follow-ups
- What happens to a job when a worker crashes while processing it?
- How do you add a job that must run every day at 02:00?
- How do you prioritise jobs or limit the rate to an external API?
Tips
- Explain producer, queue, worker in one sentence.
- Say 'at least once'.
- Mention retries and removeOnComplete.