# BullMQ, and the Mongo queue I did not use

> The service was already on MongoDB, so Agenda would have cost no new infrastructure. A blocking pop, retries I did not have to write, and a five second poll interval decided otherwise.

- Author: Deyan Peev (https://deyanpeev.com)
- Published: 2023-11-19
- Tags: BullMQ, Agenda, Redis, MongoDB, Node.js, TypeScript, Queues
- URL: https://deyanpeev.com/posts/bullmq-and-the-mongo-queue-i-did-not-use

The accounts service had MongoDB in it long before it had a queue. Then the
work arrived that has no business happening inside the request that caused it
(Stripe webhooks to reconcile, seat counts to recalculate, invoices to sync)
and it needed somewhere to go.

The cheap answer was already installed. Agenda stores jobs in a MongoDB
collection, and we ran MongoDB. That's one connection string, no new service in
the Terraform, and nothing new to be woken up about at three in the morning. I
spent an afternoon wiring it up and then added Redis anyway. This is the
comparison I wish I'd read first.

# What BullMQ is

BullMQ is a job queue for Node that keeps its state in Redis. You write to it
with a `Queue`, you consume from it with a `Worker`, and if you want to watch
what's happening from a process that is doing neither, you attach
`QueueEvents`.

What matters is underneath those classes. A queue is a Redis list of job IDs,
a job is a hash, delayed jobs live in a sorted set keyed by the millisecond
they become due, and every transition between those structures is a Lua script
that Redis runs as a single command. Take moving a job from waiting to active,
or incrementing its attempt counter and re-delaying it, or promoting a delayed
job when its time comes. Not one of those is a read, then a decision in Node,
then a write back. There is no window in which two workers have both decided
the job is theirs.

The current release as I write this is 4.14.0, published yesterday. Version 4
landed in June, and you should know about the churn before you go reading. If
a tutorial tells you to construct a `QueueScheduler` alongside your worker,
it's describing version 1. That class was removed in 2.0.0 and its two jobs
(promoting delayed jobs and recovering stalled ones) moved into `Worker`.
Half the BullMQ material on the internet still creates it.

A producer and a consumer, in full:

```ts
import { Queue, Worker, UnrecoverableError } from 'bullmq'
import IORedis from 'ioredis'

// Workers issue blocking commands, and ioredis will abort a command that is
// still outstanding after maxRetriesPerRequest. BullMQ requires null here and
// warns loudly if you forget.
const connection = new IORedis(process.env.REDIS_URL, {
  maxRetriesPerRequest: null,
})

export const invoices = new Queue('invoices', {
  connection,
  defaultJobOptions: {
    attempts: 5,
    backoff: { type: 'exponential', delay: 2_000 },
    removeOnComplete: { age: 3_600, count: 1_000 },
    removeOnFail: { age: 7 * 24 * 3_600 },
  },
})

await invoices.add('sync', { subscriptionId }, { jobId: `sync:${subscriptionId}` })
```

```ts
const worker = new Worker<{ subscriptionId: string }>(
  'invoices',
  async (job) => {
    const result = await stripe.subscriptions.retrieve(job.data.subscriptionId)
    if (result.status === 'canceled') {
      // Nothing about this gets better on the fourth attempt.
      throw new UnrecoverableError('subscription is canceled')
    }
    return reconcile(result)
  },
  {
    connection,
    concurrency: 10,
    limiter: { max: 25, duration: 1_000 },
  },
)

process.on('SIGTERM', () => worker.close())
```

`concurrency` defaults to 1, which surprises people who assume a worker is a
pool. `limiter` is a real rate limiter across every worker on that queue (not
per process), and that's why it is in this example. Stripe's API has opinions
about how fast you may talk to it, and I'd rather express that once than write
a token bucket.

# What Agenda is

Agenda is a job scheduler for Node that keeps its state in a MongoDB
collection, `agendaJobs` unless you name it something else. You describe a
job with `define`, and you put work on it with `now`, `schedule` or `every`.

```ts
import { Agenda } from 'agenda'

const agenda = new Agenda({
  db: { address: process.env.MONGO_URL, collection: 'agendaJobs' },
  processEvery: '5 seconds',
  maxConcurrency: 20,
})

agenda.define(
  'sync invoice',
  { concurrency: 10, lockLifetime: 60_000, priority: 'high' },
  async (job) => {
    const result = await stripe.subscriptions.retrieve(job.attrs.data.subscriptionId)
    await reconcile(result)
  },
)

await agenda.start()

await agenda.now('sync invoice', { subscriptionId })
await agenda.every('1 hour', 'sweep stale invoices', {}, { skipImmediate: true })
```

The API is nice to read. `agenda.schedule('tomorrow at noon', ...)` works,
because Agenda parses English through `human-interval` and `date.js`, and I've
never once had to look up what `'in 20 minutes'` means.

The current release is 5.0.0, published in November 2022. That date isn't a
typo, and I will come back to it.

# A blocking pop against a five second poll

Both libraries hand you a `Job` and both call your function. The mechanical
difference is in how your function comes to be called at all.

A BullMQ worker sits inside `BRPOPLPUSH` on the waiting list. That's a blocking
Redis command, so the connection is parked in the server until something is
pushed, and when a producer pushes a job ID the worker is handed it and wakes
up. Nothing gets asked repeatedly. The delay between `add` and the first line
of the processor is a network round trip.

An Agenda instance runs a timer. Every `processEvery` (five seconds by
default) it asks Mongo for work, and it asks per defined job name, with a
`findOneAndUpdate` that matches documents that are due and unlocked (or whose
lock has expired past `lockLifetime`) and stamps `lockedAt` in the same
operation. It is a correct lock. Mongo's document-level atomicity does the
same job that Redis's single-threadedness does on the other side. But it
happens on a clock, and nothing can start faster than the clock ticks.

So the same eight jobs, enqueued at the same eight moments, come off the two
queues very differently. On the blocking side each one leaves when it arrives.
On the polling side they queue up against the next tick and leave in a clump,
somewhere between zero and five seconds late, averaging two and a half.

For the nightly invoice sweep that's a rounding error and I wouldn't have
cared. But for the job behind a customer clicking **Upgrade** and then staring
at a seat count that hasn't moved, a p50 of two and a half seconds of pure
waiting settled it. You can turn `processEvery` down, sure, and then you are
paying for a `findOneAndUpdate` per job name per instance per tick against a
production Mongo cluster, forever, whether or not there is any work.

# The retries I did not want to write

BullMQ gives you `attempts` and `backoff` as job options, with `fixed` and
`exponential` built in, and `UnrecoverableError` to opt a specific failure out
of the remaining attempts. A job that exhausts its attempts lands in the failed
set with its stack trace, and stays there for as long as `removeOnFail` says.

Agenda has no equivalent. `job.fail(reason)` sets `failReason`, `failedAt` and
increments `failCount`, and it doesn't touch `nextRunAt`. So a one-off job that
throws is a document that failed once and will never run again. There's an
unusually candid comment in Agenda's own source next to that code saying it
"is not equipped to handle errors originating in user code".

So you write it. You listen for `fail`, read `failCount`, decide on a ceiling,
compute a backoff, and reschedule the job yourself. Now the retry policy for
your billing jobs is bespoke code in your repository that has never been
load-tested. It is not hard. I'd still rather import it than own it.

Recurring jobs muddy this a bit. A recurring job's `nextRunAt` is computed
when the run starts, so a failed occurrence doesn't stop the schedule and the
job runs again on time. That one occurence is just lost, and the only trace is
`failCount` climbing.

# What Agenda is better at

I don't want the above to read as a rout. Three things mattered enough that I
hesitated.

**Jobs are documents you can query.** During an incident, `db.agendaJobs.find({
name: 'sync invoice', failCount: { $gt: 0 } })` in a Mongo shell is an answer
in ten seconds, using a tool everyone on the team already has open. BullMQ's
state is hashes and sorted sets with a key layout you're explicitly not meant
to depend on, so you go through the library or you stand up Bull Board. That is
a real operational difference and it's on Agenda's side.

**Enqueue can be transactional.** The job document and the business write it
depends on can go into one Mongo transaction. With BullMQ the write is in
Mongo and the job is in Redis, so you have two stores and no transaction across
them, and you inherit the usual problem where the row committed, the enqueue
failed, and nothing ever picks it up. The fix is the usual one too (make the
job idempotent, or write an outbox) and both cost you something.

**Recurring definitions do not drift.** `agenda.every()` saves the job with
`type: 'single'` and upserts on the name, so calling it at boot on all six
replicas leaves you one document. BullMQ derives a repeatable job's key from
`name:jobId:endDate:tz:pattern`, so changing the schedule creates a *new*
repeatable entry and leaves the old one firing. You find out when something
runs twice. The fix is to reconcile at boot: `getRepeatableJobs()`, compare
against what the code declares, `removeRepeatableByKey()` for anything left
over. I have now written that code twice, at two companies, which suggests it
shouldn't be my code.

# What it costs to make Redis hold jobs

Once BullMQ is in the service, Redis is a durable store and not a cache, and
most Redis installations were configured by someone who believed the opposite.

BullMQ does check some of this. It reads `maxmemory-policy` on connect and
warns if it isn't `noeviction`, because every other policy means Redis may
decide to delete your job under memory pressure. It also refuses outright to
start against anything older than Redis 5.0.0. The rest is yours to check.
Persistence needs to be on and appropriate, and a managed Redis with a default
eviction policy and no AOF is not a queue, however well the client library
behaves.

The blast radius changes too. Mongo going down took the service with it
anyway. Redis going down is a second thing that can take the service down, so
now it needs the monitoring and the failover story to match.

# The release cadence, which I have gone back and forth on

Agenda 5.0.0 was published in November 2022 and is still the current release
twelve months later. In the same month I'm writing this, BullMQ has shipped
4.13.0, 4.13.1, 4.13.2, 4.13.3, 4.14.0 and counting.

I want to be careful here, because the obvious reading is lazy in both
directions. A library that has stopped releasing may just be finished. And I
have been bitten more than once by a BullMQ minor release changing behaviour I
was leaning on.

But `@hokify/agenda` exists. It's a TypeScript fork of Agenda (itself last
published in December 2022), and a fork says something about the upstream
however charitably you read it. For the thing that decides whether a customer
gets billed, I want the queue's bug-fix cycle to be visibly alive.

# When I would still pick Agenda

If the service is already on Mongo, there's no Redis anywhere near it, and the
work is *scheduled* and not *reactive* (nightly reports, hourly sweeps,
unattended cleanup), then Agenda is the right answer and BullMQ is a second
datastore you're adding for nothing. A five second floor on a job that runs at
3am is not a number anyone will ever measure. Add the transactional enqueue,
and that your on-call can read the queue with tools they already know, and
Agenda is a good choice in its own right.

Once any of that stops holding, BullMQ is the better fit. That means reactive
work where somebody is watching a spinner, retries with backoff that you'd
otherwise hand-roll, a rate limit shared across every worker because a payment
provider is on the other end. Also jobs with dependencies, which BullMQ's
`FlowProducer` expresses and Agenda has no concept of at all.

For this service that was every requirement on the list, so it got Redis and
a queue in it.

---

*Versions as of writing: `bullmq@4.14.0` (18 November 2023) and `agenda@5.0.0`
(7 November 2022). BullMQ 4.x targets Redis 5 and above; Agenda 5.x brings its
own `mongodb` v4 driver.*
