BullMQ is the de-facto job queue for Node.js — it uses Redis as the backing store, gives you typed Queue/Worker/QueueEvents classes, and handles retries, delays, repeat jobs, and rate limits without you writing lock logic against Redis directly. This article is the BullMQ setup we run for Node.js clients: install, a Queue and a Worker in clean classes, the job options that actually matter in production, and the operational gotchas (Redis eviction, lost jobs on --maxmemory-policy allkeys-lru, repeat-job clock drift) that show up at three months, not three days.
How to verify
BullMQ requires Redis 5+ with maxmemory-policy set to noeviction for queue keys. Confirm both:
redis-cli INFO server | grep -E 'redis_version|process_id'
redis-cli CONFIG GET maxmemory-policy
redis-cli DBSIZE
node --version
npm ls bullmq 2>/dev/null || echo "not installed yet"
If maxmemory-policy is allkeys-lru or volatile-lru, Redis can evict in-flight jobs. For a shared Redis you must isolate the queue keys (separate DB, separate Redis instance, or BullMQ plus connection.prefix and Redis ACLs scoped to the prefix).
What’s happening
BullMQ has four core classes:
- Queue — the producer. You call
queue.add(name, data, opts)to enqueue a job. - Worker — the consumer. You instantiate
new Worker(name, processor, opts); the worker polls Redis for jobs, runsprocessor(job), and writes the result back. - QueueEvents — a lightweight listener for queue-level events (
completed,failed,progress,delayed). Use this for dashboards and alerting, not as the main consumer. - QueueScheduler (older API; merged into Worker in 4.x) — handles delayed jobs and stalled-job recovery.
Under the hood, BullMQ stores each queue as a set of Redis keys: bull:<queue>:waiting (list), bull:<queue>:active (list), bull:<queue>:completed (sorted set), bull:<queue>:failed (sorted set), bull:<queue>:delayed (sorted set keyed on the run-at timestamp), plus a hash per job with its payload, opts, attempts, and result. The atomicity of state transitions is enforced via Lua scripts that run server-side in Redis.
Job options that matter:
attemptsandbackoff— automatic retries with exponential or fixed delay.removeOnCompleteandremoveOnFail— keep memory bounded by setting{ count, age }removal policies.delay— schedule a job to run later.repeat: { pattern: '*/5 * * * *' }— cron-style recurring jobs.priority— lower number = higher priority (rarely needed; a separate queue is usually cleaner).jobId— supplied externally for idempotent enqueue; reusing an id is a no-op.
The procedure
-
Install BullMQ and a Redis client:
npm install bullmq ioredis # peer-dependency note: BullMQ uses ioredis internally; the API takes a connection object -
Create the Redis connection. Keep it as a single shared instance, not per-queue:
// src/queues/connection.js import { Redis } from 'ioredis'; export const connection = new Redis({ host: process.env.REDIS_HOST, port: Number(process.env.REDIS_PORT || 6379), password: process.env.REDIS_PASSWORD, maxRetriesPerRequest: null, // required by BullMQ enableReadyCheck: false, // recommended by BullMQ });maxRetriesPerRequest: nullandenableReadyCheck: falseare explicit BullMQ requirements; without them you get cryptic errors on Redis reconnect. -
Define a Queue:
// src/queues/emails.js import { Queue } from 'bullmq'; import { connection } from './connection.js'; export const emailsQueue = new Queue('emails', { connection, defaultJobOptions: { attempts: 5, backoff: { type: 'exponential', delay: 1000 }, removeOnComplete: { count: 1000, age: 24 * 3600 }, removeOnFail: { count: 5000, age: 30 * 24 * 3600 }, }, }); -
Enqueue a job:
import { emailsQueue } from './queues/emails.js'; await emailsQueue.add('welcome', { to: 'user@example.com', templateId: 'welcome-v3', locale: 'en', }, { jobId: `welcome-${userId}`, // idempotent: re-enqueue with same id is a no-op }); -
Define a Worker:
// src/workers/emails.js import { Worker } from 'bullmq'; import { connection } from '../queues/connection.js'; import { sendEmail } from '../lib/email.js'; const worker = new Worker('emails', async (job) => { if (job.name === 'welcome') { await sendEmail(job.data); return { sent: true, at: new Date().toISOString() }; } throw new Error(`unknown job name: ${job.name}`); }, { connection, concurrency: 8, limiter: { max: 100, duration: 1000 }, // 100 jobs/sec global cap }); worker.on('failed', (job, err) => { console.error(`[emails] job ${job?.id} failed:`, err); }); worker.on('error', (err) => { console.error('[emails] worker error:', err); }); process.on('SIGTERM', async () => { await worker.close(); process.exit(0); }); -
Add a repeat job for scheduled work:
await emailsQueue.add('weekly-digest', { type: 'digest' }, { repeat: { pattern: '0 9 * * MON', tz: 'America/Toronto' }, jobId: 'weekly-digest', });The
tzis critical — without it, the cron pattern runs in the worker’s local timezone, which is rarely what you want for global services. -
Wire QueueEvents for observability in a separate process or in a dashboard service:
import { QueueEvents } from 'bullmq'; const events = new QueueEvents('emails', { connection }); events.on('completed', ({ jobId }) => { metrics.increment('queue.emails.completed'); }); events.on('failed', ({ jobId, failedReason }) => { metrics.increment('queue.emails.failed'); log.warn({ jobId, failedReason }, 'job failed'); }); events.on('stalled', ({ jobId }) => { metrics.increment('queue.emails.stalled'); }); -
Run the worker under a supervisor (systemd, pm2, or your container runtime). One worker process per CPU core typically; set
concurrencyper worker based on whether the work is I/O-bound (high concurrency) or CPU-bound (concurrency = 1, more worker processes).
Operational notes
- BullMQ uses Redis keyspace notifications under the hood for delayed jobs; ensure
notify-keyspace-eventsincludesExin your Redis config or delayed jobs do not fire on time. removeOnCompleteandremoveOnFailare not optional in production — without them, Redis memory grows without bound. Set both with{ count, age }policies.- Stalled-job recovery (the Worker re-queues jobs that a dead worker did not finish) defaults to 30s; the
stalledIntervalandmaxStalledCountknobs control how aggressive that is. - Idempotent producers use the
jobIdoption — re-enqueueing with the same id is silently ignored. This is the cleanest way to deduplicate webhook-driven jobs. - Workers and queues can share a Redis connection in dev but should have separate connections in production; BullMQ holds blocking subscriptions on its connections which conflict with regular request/reply usage.
Stack Harbor stands up BullMQ as the worker-queue layer for Node.js clients — Queue and Worker classes in code review, Redis isolated with noeviction and the right keyspace events, repeat jobs given an explicit timezone, and dashboards on completed/failed/stalled rates. If your BullMQ install grew from a tutorial into the spine of your async work, this is the work covered by our Managed Operations practice.