Wednesday, November 25, 2026

Introducing the BullMQ Relay

Cover for Introducing the BullMQ Relay

A queue is for work: every job is processed by one worker, with retries, rate limits and persistence. But an application with several processes also needs to tell the others that something happened, and that doesn't fit a queue:

  • a job is 60% done, and the API server that holds the user's browser connection should show it;
  • a user's permissions changed, and every instance of the service should drop them from its cache;
  • a user pressed "Cancel", and whichever worker is running that export should stop.

Until now, the usual answer was Redis pub/sub, or adding a message broker to the stack. BullMQ 6.4 adds the Relay for this: live messages between your processes, over the Redis or PostgreSQL that BullMQ already uses.

import { Relay } from "bullmq";

const relay = new Relay({ connection: { host: "localhost", port: 6379 } });

// In one process:
await relay.subscribe("orders.*.status", (message) => {
console.log(message.topic, message.data); // orders.42.status { status: 'shipped' }
});

// In any other process:
await relay.publish("orders.42.status", { status: "shipped" });

Every process that creates a Relay is a node. Create one per process and share it.

Topics and patterns

A topic is a dot-separated path from the general to the specific, such as tenants.acme.users.17.notifications or jobs.transcode.42.progress. You always publish to a concrete topic, and you subscribe to a topic or a pattern:

Pattern Matches
orders.42.status only that topic
orders.*.status orders.42.status, orders.7.status (* is one segment)
orders.> everything below orders (> is one or more trailing segments)
tenants.*.invoices.> the invoices of every tenant

Topics cost nothing until somebody subscribes, so you can use one per job, user or document. Design them like REST paths, with identifiers in their own segments, so that a wildcard can select a whole branch.

Why not Redis pub/sub?

Redis pub/sub is fire-and-forget: if a subscriber's connection drops for a second, the messages published during that second are gone. It also needs a dedicated connection per subscriber, and it doesn't exist on PostgreSQL.

The Relay works differently. When a message is published, the datastore finds every subscription that matches the topic and appends one entry to the inbox of each node involved. Each node reads its own inbox and calls your listeners. This gives you:

  • No lost messages on short disconnections. Messages published while a node is reconnecting wait in its inbox.
  • Only interested nodes are reached. The routing runs inside the datastore (Lua scripts on Redis, SQL functions on PostgreSQL), and a message is only written to the inboxes of nodes with a matching subscription.
  • Dead nodes are cleaned up. Every node keeps a lease alive with heartbeats. A node that crashes is removed with its subscriptions once its lease expires, 30 seconds by default.
  • The latest value for newcomers. A message published with retain is kept as the topic's current value, and a new subscriber to that topic gets it first.
  • The same behaviour on Redis and PostgreSQL, because all of the logic lives in the datastore.

Here is how it compares to what BullMQ already had:

Queue QueueEvents Redis pub/sub Relay
Each message goes to one worker every listener every subscriber every matching subscription
What you can send jobs queue events only anything any JSON value
Addressing queue name queue name channel or glob topics with * and >
Briefly disconnected jobs wait resumes from its last id messages are lost messages wait in its inbox
Latest value for new listeners no no no retained messages
Datastores Redis, PostgreSQL Redis, PostgreSQL Redis Redis, PostgreSQL

Example: live job progress

Users upload videos, a fleet of workers transcodes them, and the video's page shows a progress bar. The user's browser is connected to one of your API servers, while the job runs on any worker.

The worker publishes the progress on the job's own topic, as a retained message:

import { Relay, Worker } from "bullmq";

const connection = { host: "redis.internal", port: 6379 };
const relay = new Relay({ connection });
const HOUR = 60 * 60 * 1000;

const worker = new Worker(
"transcode",
async (job) => {
const chunks = await splitVideo(job.data.videoUrl);
for (const [index, chunk] of chunks.entries()) {
await transcode(chunk);
const progress = Math.round(((index + 1) / chunks.length) * 100);
await relay.publish(`jobs.transcode.${job.id}.progress`, progress, {
retain: HOUR,
});
}
return { url: await mergeChunks(chunks) };
},
{ connection },
);

The API server subscribes only to the jobs its users are watching, and forwards the updates to the browser with Server-Sent Events:

app.get("/videos/:jobId/events", async (req, res) => {
// Check that the user may see this job before subscribing.
res.writeHead(200, { "Content-Type": "text/event-stream" });

let closed = false;
res.on("close", () => (closed = true));

const subscription = await relay.subscribe(
`jobs.transcode.${req.params.jobId}.progress`,
(message) => {
if (!closed) res.write(`data: ${JSON.stringify(message.data)}\n\n`);
},
);

// The browser may have left while we were subscribing.
if (closed) return void subscription.unsubscribe();
res.on("close", () => void subscription.unsubscribe());
});

Because the progress is retained, a user who opens the page halfway through sees the current value right away instead of an empty bar. And only the server with a viewer receives the updates of that job. With QueueEvents, every API server would read every event of the queue. The full version, with authorization, error handling and the job's final status, is in the live job progress example.

Example: cancelling a job on another worker

worker.cancelJob() aborts a running job, but only from the process that runs it. The request to cancel usually arrives at an API server. With the Relay, every worker subscribes to a cancellation topic, and the worker that runs the job cancels it:

// Every worker process
await relay.subscribe("jobs.exports.cancel", (message) => {
const { jobId, reason } = message.data as { jobId: string; reason: string };
worker.cancelJob(jobId, reason); // a no-op on workers that don't run it
});

// The API server
const { endpoints } = await relay.publish("jobs.exports.cancel", {
jobId,
reason: "cancelled by user",
});

endpoints tells you how many subscriptions received the request, so 0 means no worker was listening. The processor has to react to the AbortSignal it receives, as described in the cancellation guide.

Example: cache invalidation

Each instance of a service keeps users in an in-memory cache. When a user changes, every instance should drop the entry:

const users = new LRUCache<string, User>({ max: 10_000, ttl: 5 * 60_000 });

await relay.subscribe("cache.users.*", (message) => {
users.delete(message.topic.split(".")[2]);
});

// Invalidations may have been missed: the node was removed after being frozen
// or disconnected for longer than its lease, or it is falling behind and its
// oldest unread messages may be dropped. Start over in both cases.
relay.on("recovered", () => users.clear());
relay.on("lag", () => users.clear());

export async function updateUser(id: string, changes: Partial<User>) {
await db.users.update(id, changes);
await relay.publish(`cache.users.${id}`, null); // after the commit
}

The recovered and lag handlers are the part people usually forget with pub/sub: they tell you when the cache may have missed something. The cache's own expiry (five minutes here) is the safety net that bounds how stale an entry can get in any case.

Running it on PostgreSQL

If your queues already run on PostgreSQL, the Relay can use the same database:

import { Relay, createPostgresRelayBackend } from "bullmq";

const relay = new Relay({
connection: {
connectionString: "postgres://user:password@localhost:5432/app",
migrate: true,
},
backend: createPostgresRelayBackend,
});

The API is the same. Each node uses LISTEN to wake up when its inbox gets a message, and a second connection for commands. On Redis, the Relay needs Redis 6.2 or newer, or a compatible server such as Valkey or Dragonfly.

What the Relay is not

The Relay is for messages that matter now. Some things it deliberately does not do:

  • It is not a log. A subscription only sees messages published after it, apart from the retained value. There is no replay, and a message published when nobody is subscribed is gone.
  • It doesn't guarantee that work gets done. A node that is removed after missing its lease loses the messages in its inbox. A node that can't keep up keeps at most 10,000 unread messages by default, and the oldest are dropped, with a lag event to warn you. When a message must lead to work that has to happen, add a job to a queue from the listener.
  • It is not for bulk data. A namespace lives in one Redis slot or one PostgreSQL database, which is plenty for control and notification traffic but not for streaming large volumes. Keep messages small (the limit is 512 KiB by default): publish an id and let the receiver fetch the rest.

If you are wondering about Kafka: Kafka is a durable, replayable event log for data pipelines, and the Relay is live messaging inside an application. The docs have a full comparison.

Seeing what's going on

A relay can also describe its namespace, which is useful for dashboards and debugging:

const { nodes, subscriptions, retained } = await relay.getCounts();
const firstNodes = await relay.getNodes(0, 19); // backlog, dropped messages, lease
const cancelListeners = await relay.getSubscriptions({ pattern: "jobs.*.cancel" });

These getters read the datastore directly, not the nodes, so they are cheap to poll.

Getting started

The Relay is available in BullMQ 6.4.0 and later, in the Node.js library for now. It is still marked experimental, so its API may change in minor releases while we finish it.

To try it:

  1. Upgrade to the latest BullMQ: npm install bullmq@latest.
  2. Create one Relay per process, next to your queues and workers, and close it on shutdown.
  3. Read the Relay guide, which covers topics, retained messages, failures and more examples, such as live configuration and controlling a fleet of workers.

We'd like to hear what you build with it, and what's missing, on GitHub.