BullMQ 6 in NestJS: Stalled Jobs, Deduplication, and Moving Repeatable Jobs to Job Schedulers — Field Notes
Headline: BullMQ, the Redis-backed job queue for Node.js, fails in production mostly through configuration rather than code: a Redis
maxmemory-policyother thannoevictionlets Redis evict queue keys, a CPU-bound processor that blocks the event loop past its 30-second job lock gets the same job run twice, and a customjobIdsilently drops legitimate jobs. BullMQ 6.0.0, released on 2026-07-30, also removes the legacyrepeatoption, so recurring jobs have to move to Job Schedulers before the upgrade.
I use BullMQ behind NestJS APIs for emails, PDF reports, webhook fan-out and nightly cleanups. None of the failures below threw an error where I was looking. These notes are written against BullMQ 6.5 and @nestjs/bullmq 12.
Key takeaways
- Redis for BullMQ must run with
maxmemory-policy noeviction, and that policy applies to the whole Redis instance, not to one logical database. - A stalled job is a job whose lock expired while it was still running; BullMQ moves it back to waiting and another worker runs it again, so CPU-heavy processors belong in sandboxed processors.
- BullMQ delivers jobs at least once, so every processor must be idempotent even when
jobIdordeduplicationis set. - A custom
jobIddeduplicates against every job still stored in Redis, including completed jobs kept byremoveOnComplete; thededuplicationoption only blocks duplicates while a job is unfinished or inside a TTL. - BullMQ 6 raises an error on legacy repeatable-job data in Redis, so I moved every
repeatjob toupsertJobScheduler()while still on BullMQ 5.
How do I set up BullMQ 6 in a NestJS app?
A production BullMQ setup in NestJS is one BullModule.forRootAsync() for the Redis connection, one BullModule.registerQueue() per queue with default retry and retention options, and one processor class per queue that extends WorkerHost. BullMQ 6 made ioredis an optional peer dependency, so the install has to name it explicitly:
npm install bullmq @nestjs/bullmq ioredis // queues/queues.module.ts import { Module } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { BullModule } from '@nestjs/bullmq'; import { EmailProcessor } from './email.processor'; @Module({ imports: [ BullModule.forRootAsync({ inject: [ConfigService], useFactory: (config: ConfigService) => ({ connection: { host: config.getOrThrow<string>('REDIS_HOST'), port: config.get<number>('REDIS_PORT', 6379), }, }), }), BullModule.registerQueue({ name: 'email', defaultJobOptions: { attempts: 5, backoff: { type: 'exponential', delay: 2_000, jitter: 0.5 }, removeOnComplete: { age: 24 * 3600, count: 5_000 }, // seconds, jobs removeOnFail: { age: 7 * 24 * 3600 }, }, }), ], providers: [EmailProcessor], }) export class QueuesModule {} Retry defaults belong on the queue, not on every add() call. Exponential backoff waits 2^(attempts - 1) × delay milliseconds before each retry, and jitter: 0.5 randomizes each delay between half and all of that value, so a burst of failures does not retry in lockstep. removeOnComplete and removeOnFail take an age in seconds and a count; without them, BullMQ keeps every finished job in Redis forever.
The processor is a normal NestJS provider, so it can inject services. Throwing UnrecoverableError from bullmq moves a job straight to the failed set without spending its remaining attempts; it replaces Job#discard(), which BullMQ 6 removed.
// queues/email.processor.ts import { Logger } from '@nestjs/common'; import { OnWorkerEvent, Processor, WorkerHost } from '@nestjs/bullmq'; import { Job, UnrecoverableError } from 'bullmq'; import { MailService } from '../mail/mail.service'; type ReceiptEmail = { orderId: string; to: string }; @Processor('email', { concurrency: 10 }) export class EmailProcessor extends WorkerHost { private readonly logger = new Logger(EmailProcessor.name); constructor(private readonly mail: MailService) { super(); } async process(job: Job<ReceiptEmail>) { if (!job.data.to.includes('@')) { // A bad address will not fix itself: fail now instead of retrying 5 times throw new UnrecoverableError(`invalid recipient for order ${job.data.orderId}`); } // Retries and stalls can run this twice; the provider dedupes on the key await this.mail.sendReceipt(job.data, { idempotencyKey: `job-${job.id}` }); } @OnWorkerEvent('failed') onFailed(job: Job | undefined, error: Error) { this.logger.error(`job ${job?.id} failed after ${job?.attemptsMade} attempts: ${error.message}`); } } Why does BullMQ lose jobs when Redis is also used as a cache?
BullMQ loses jobs when Redis is allowed to evict keys, because every job, lock and queue list is a Redis key that an eviction policy such as allkeys-lru treats as disposable cache. A job evicted from the wait list is never processed and never fails, so no alert fires. The BullMQ production guide states that noeviction is the only maxmemory-policy that guarantees correct queue behavior.
# redis.conf for the queue instance maxmemory 1gb maxmemory-policy noeviction appendonly yes The Redis maxmemory-policy setting is instance-wide: logical databases selected with SELECT share it. A cache wants eviction and a queue must never evict, so I run them on separate Redis instances. Under noeviction, a full Redis rejects writes with an out-of-memory error, which turns silent job loss into a loud queue.add() failure and makes the removeOn* retention settings the real memory budget. I also enable AOF persistence (appendonly yes) so a Redis restart does not drop queued jobs.
Two client settings matter as well. Worker connections need the ioredis option maxRetriesPerRequest: null, which BullMQ sets by default and warns about when a shared ioredis instance overrides it. For producer Queue connections, the BullMQ docs suggest enableOfflineQueue: false, so an HTTP request that enqueues a job fails fast while Redis is down instead of hanging.
Why did my BullMQ job run twice?
A BullMQ job runs twice when it stalls: the worker processing it did not renew its lock in time, so BullMQ assumed the worker had died and handed the job to another worker. Each active job holds a lock for lockDuration (default 30,000 ms), and the worker renews it every lockRenewTime (default 15,000 ms, half of lockDuration). Renewal runs on the Node.js event loop, so a processor that blocks the loop — a synchronous PDF render, an image resize, a huge JSON.parse() — misses the renewal while it is still working.
The stalled-job checker, which runs every stalledInterval (default 30,000 ms), then moves the job back to waiting; once a job has stalled more than maxStalledCount times (default 1), it goes to the failed set instead. That recovery is correct when a container is killed mid-job and wrong when the original worker is alive, because two copies now run at once. Raising lockDuration hides the symptom and delays recovery from real crashes by the same amount, so I moved the CPU-bound work off the main thread instead. A sandboxed processor is a processor file that BullMQ runs in a separate child process, or in a worker thread when useWorkerThreads: true is set:
// reports/pdf.worker.ts — the processor runs off the main event loop import { Injectable, OnModuleDestroy } from '@nestjs/common'; import { Worker } from 'bullmq'; import { join } from 'node:path'; @Injectable() export class PdfWorker implements OnModuleDestroy { private readonly worker = new Worker('pdf', join(__dirname, 'render-pdf.processor.js'), { connection: { host: process.env.REDIS_HOST, port: 6379 }, concurrency: 2, useWorkerThreads: true, }); async onModuleDestroy() { await this.worker.close(); // stop taking jobs, finish the active ones } } // reports/render-pdf.processor.ts — compiled to render-pdf.processor.js import type { SandboxedJob } from 'bullmq'; import { renderReport } from './render-report'; export default async function (job: SandboxedJob<{ reportId: string }>) { return renderReport(job.data.reportId); // CPU-heavy, blocks only this thread } The trade-off is dependency injection: a sandboxed processor runs outside the NestJS container, so it builds its own database and storage clients instead of injecting providers. I/O-bound jobs stay on regular WorkerHost processors.
How do I stop BullMQ from enqueuing the same job twice?
BullMQ has two built-in ways to drop duplicate jobs — a custom jobId and the deduplication job option — and they differ in how long the duplicate check lasts:
Custom jobId | deduplication: { id } | deduplication: { id, ttl } | |
|---|---|---|---|
| Duplicate ignored while | Any job with that ID is still stored in Redis, including completed and failed jobs | The first job is waiting, delayed or active | The TTL window is open |
| Event emitted | duplicated | deduplicated | deduplicated |
| Fits | One job per entity, ever | No second job while one is in flight | Throttling and debouncing bursts |
The custom jobId trap is retention. With removeOnComplete: { age: 86400 }, a completed job with the ID receipt-42 stays in Redis for a day, and every add() with the same ID during that day is ignored without throwing. Custom job IDs also cannot be digit-only strings such as "123"; BullMQ throws Custom Id cannot be integers. For "not while one is already pending", the deduplication option is the better fit. BullMQ 6 removed the old debounce option; a debounce is now a delayed job with a matching ttl and both extend and replace set:
// Ignore new receipt jobs while one for this order is waiting or running await this.emailQueue.add('receipt', { orderId, to }, { deduplication: { id: `receipt-${orderId}` }, }); // Debounce: a burst of product edits produces one reindex, 5 s after the last edit await this.searchQueue.add('reindex', { productId }, { delay: 5_000, deduplication: { id: `reindex-${productId}`, ttl: 5_000, extend: true, replace: true }, }); Neither mechanism makes processing exactly-once. Retries and stalls still run the same job again, which is why the email processor above passes an idempotency key derived from job.id to the mail provider.
What breaks when upgrading from BullMQ 5 to BullMQ 6?
BullMQ 6.0.0 removes legacy repeatable jobs and raises an error when it finds their metadata in Redis, so repeatable jobs have to be migrated to Job Schedulers while the app still runs BullMQ 5. A Job Scheduler is a named, upsertable definition that produces jobs on a cron pattern or an every interval; calling upsertJobScheduler() again with the same ID updates the schedule instead of creating a second one.
// Before (BullMQ 5, removed in 6): // await queue.add('purge-expired-sessions', {}, { repeat: { pattern: '0 3 * * *', utc: true } }); // After: maintenance/maintenance.schedules.ts import { Injectable, OnApplicationBootstrap } from '@nestjs/common'; import { InjectQueue } from '@nestjs/bullmq'; import { Queue } from 'bullmq'; @Injectable() export class MaintenanceSchedules implements OnApplicationBootstrap { constructor(@InjectQueue('maintenance') private readonly queue: Queue) {} async onApplicationBootstrap() { await this.queue.upsertJobScheduler( 'purge-expired-sessions', // scheduler ID: upserting again updates, never duplicates { pattern: '0 3 * * *', tz: 'UTC' }, { name: 'purge-expired-sessions', data: {} }, ); } } Because the upsert is idempotent, every replica can run it on boot. Job Schedulers already exist in BullMQ 5, so I shipped this change first, then removed the legacy definitions on v5 with queue.getRepeatableJobs() and queue.removeRepeatableByKey(), and only then bumped the version. The other BullMQ 6 breaking changes are mechanical:
-
repeat.utc: truebecomestz: 'UTC'on the scheduler. - The
debounceoption and thedebouncedevent are removed; usededuplicationand thededuplicatedevent. -
Job#discard()is removed; throwUnrecoverableErrorinstead. -
Worker#resume()andQueue#resume()are now asynchronous and must be awaited. -
ioredisis an optional peer dependency and must be installed explicitly. -
Queue#clientandWorker#blockingClientare removed; raw Redis access goes through the backend returned bygetBackend().
BullMQ 6 also introduces pluggable queue backends, including an optional PostgreSQL backend that runs the same Queue and Worker API on PostgreSQL 13 or newer through the createPostgresBackend factory. The BullMQ docs still describe Redis as the default and most battle-tested backend, and I have not moved a production queue to PostgreSQL yet.
FAQ
Q: Does BullMQ guarantee exactly-once job processing?
A: No. BullMQ delivers jobs at least once: a retry, a stalled job or a worker crash mid-job runs the processor again. Make every processor idempotent, for example with an idempotency key derived from job.id.
Q: Can BullMQ share a Redis instance with my application cache?
A: Not safely if the cache relies on an eviction policy such as allkeys-lru. The Redis maxmemory-policy setting applies to the whole instance, and BullMQ needs noeviction, so the queue should get its own Redis instance.
Q: How many finished jobs should removeOnComplete keep?
A: Bound completed jobs by both age and count — I use 24 hours and 5,000 jobs — and keep failed jobs longer. Leaving both options unset keeps every finished job in Redis forever.
Q: When should I increase lockDuration in BullMQ?
A: Rarely. A longer lockDuration also delays recovery of jobs from crashed workers by the same amount, so first move CPU-bound work into a sandboxed processor and keep the event loop free to renew locks.
Originally published on devya.dev. Also on eng-ahmed.com. Built by Devya Solutions.