library / Integrations / Queues and streams / I0057
BullMQ subscription fan-in
A Node 24 script opens a slot subscription and a Token program logs subscription, runs one for-await task for each, and hands every notification to one enqueue function that prints the job BullMQ would add. After 10 seconds an abort ends the two tasks.
Why sequential loops starve
Two for await loops written one after the other never reach the second. The first runs for as long as its subscription lives, so the logs iterator is never opened and its notifications are never read.
Merging the iterators into one stream looks like the fix, and it brings a quieter problem. A merge helper keeps a next() pending on every source and takes whichever answers first. Closing it means calling return() on every source, and an async generator queues return() behind its own pending next(). The slot stream answers about five times a second, but a mention filter on a quiet program can stay silent far longer, and a shutdown that awaits that close waits with it. A throw in the loop body hangs the same way.
Skip the merge. Give each subscription its own loop, so each has its own pending next() and none waits behind another source. The loops share one enqueue function and one AbortController.
One task per subscription
task takes a job name, a function that opens the subscription, a function that picks the jobId and a function that builds the job data. subscribe resolves to the iterator once the socket is set up, and abortSignal goes in there, so one signal covers a pending subscribe and a running loop. Each task call is an async function that starts on its own. That is the whole fan-in: two promises started together and collected by Promise.allSettled.
The slot stream is the lightest subscription to open, and the Token program's logs at confirmed carry the traffic and most of the cost.
| Task | Subscription | Job name | jobId | Open cost |
|---|---|---|---|---|
| slot | slotNotifications(), which takes no commitment setting | slot | slot-<number> | 5 credits |
| logs | logsNotifications with mentions set to the Token program, at confirmed | logs | the transaction signature | 25 credits |
After the open charge a subscription costs 20 credits per MiB sent, and a refused one costs nothing. The plan caps subscriptions per account, so a third task is a third subscription against that cap.
Job names and jobIds
One queue takes both kinds. The job name tells the worker which handler to run, so slot and logs stay apart without a second queue.
The jobId decides what counts as a duplicate, because BullMQ drops an add whose jobId already exists. A log notification carries the transaction signature, and a signature is unique, so it is the natural id: a second watcher process, or a socket that reconnects and delivers the same transaction again, adds nothing new. A slot has no signature, so its number is the id. BullMQ refuses a jobId that is a bare integer, so the id reads slot-123456.
- removeOnComplete: { age: 3600 } keeps finished jobs for an hour, and a repeat inside that hour is refused.
- removeOnComplete: { count: 1000 } keeps the newest 1000, which covers many minutes of slots and little time on a busy program's logs.
- removeOnFail sets the same window for failed jobs.
The script has no Redis, so enqueue stands in. It keeps a set of ids, ignores repeats as BullMQ would, counts each job and prints the first two of each name. The real body is await queue.add(name, data, { jobId, removeOnComplete: { age: 3600 } }). Because the loop awaits it, a rejected add ends that task.
Stopping the tasks
One signal ends everything, and what each task sees depends on where it is when the signal fires.
- A running loop ends cleanly. On @solana/kit 8.6.0 an abort makes the iterator finish with no throw, so the for await falls out and the task fulfills.
- A subscribe that has not resolved yet rejects with an AbortError. task catches it by name and returns, so that task fulfills too.
- An enqueue that throws, with Redis down for example, leaves the loop through the catch. task aborts the shared controller and rethrows, so the other task ends cleanly and Promise.allSettled reports one rejected task and one fulfilled.
The failing task closes its own iterator while it has no next() pending, so that close returns at once. The other iterator is stopped by the signal with no awaited return() in the path, so a stream with nothing to say cannot hold up the shutdown. The 10-second timer in the script runs the same stop.abort() as the error path.
Run it
Install @solana/[email protected] and run the file with Node 24, which strips the types on load. CARBIUM_KEY is required and goes on the WebSocket URL as api-key. CARBIUM_WS_URL overrides the default wss://services.carbium.sh.
// I0057 · BullMQ subscription fan-in// https://carbium.sh/library/integrate/bullmq-subscription-fan-in// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { address, createSolanaRpcSubscriptions } from "@solana/kit";const apiKey = process.env.CARBIUM_KEY;if (!apiKey) { console.error("Set CARBIUM_KEY."); process.exit(1);}const endpoint = new URL(process.env.CARBIUM_WS_URL ?? "wss://services.carbium.sh");endpoint.search = new URLSearchParams({ "api-key": apiKey }).toString();const TOKEN_PROGRAM = address("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA");const stop = new AbortController();const known = new Set<string>();const jobCount = new Map<string, number>();// Stand-in for: await queue.add(name, data, { jobId, removeOnComplete: { age: 3600 } })async function enqueue(name: string, jobId: string, data: object): Promise<void> { if (known.has(jobId)) return; // BullMQ also ignores an add whose jobId exists known.add(jobId); const total = (jobCount.get(name) ?? 0) + 1; jobCount.set(name, total); if (total <= 2) console.log(`job ${name} ${jobId}`, JSON.stringify(data));}// The one task function: each subscription gets its own loop and its own pending next().async function task<T>( name: string, open: (abortSignal: AbortSignal) => Promise<AsyncIterable<T>>, idOf: (note: T) => string, dataOf: (note: T) => object,): Promise<void> { try { const stream = await open(stop.signal); for await (const note of stream) await enqueue(name, idOf(note), dataOf(note)); } catch (err) { if (err instanceof Error && err.name === "AbortError") return; // subscribe still pending at abort stop.abort(); // a failure here stops the other task too throw err; }}const rpc = createSolanaRpcSubscriptions(endpoint.href);const started: Record<string, Promise<void>> = { slot: task( "slot", (abortSignal) => rpc.slotNotifications().subscribe({ abortSignal }), (s) => `slot-${s.slot}`, (s) => ({ slot: Number(s.slot), parent: Number(s.parent) }), ), logs: task( "logs", (abortSignal) => rpc.logsNotifications({ mentions: [TOKEN_PROGRAM] }, { commitment: "confirmed" }).subscribe({ abortSignal }), (l) => l.value.signature, (l) => ({ slot: Number(l.context.slot), failed: l.value.err !== null, lines: l.value.logs?.length ?? 0 }), ),};setTimeout(() => stop.abort(), 10_000);const entries = Object.entries(started);const outcomes = await Promise.allSettled(entries.map(([, p]) => p));outcomes.forEach((o, i) => { const detail = o.status === "rejected" ? ` (${o.reason instanceof Error ? o.reason.name : "error"})` : ""; console.log(`${entries[i][0]}: ${jobCount.get(entries[i][0]) ?? 0} jobs, ${o.status}${detail}`);});
run: node main.ts
The output is the first two jobs of each name, then one line per task with its job count and how it settled. Slots arrive about five a second, so expect around fifty slot jobs in the 10 seconds, and a logs count that follows Token program traffic. Each line ends with fulfilled. A rejected line names the error, which points at the socket or the filter.
Where it ends
- A dropped socket ends the iterators, and nothing replays what the socket missed. The tasks here finish and the script exits, so a long-running worker needs a reconnect loop around task, as in WebSocket keepalive and reconnect, and its own way to fill the gap from getBlock or getSlot reads.
- Slot jobs can name slots that do not stay. A slot whose leader never produced it sends no notification, and a slot notified at processed can end up skipped when its fork is dropped. A slot-N job says a slot was announced and proves no block exists.
- logsNotifications at confirmed includes failed transactions. The job data carries failed, and a worker should check it before acting.
- Order holds inside one task only. A slot job and a log job from the same slot can reach the queue in either order.
- Dedupe lasts as long as the removal window and no longer. A jobId whose job has aged out is accepted again.
- The queue is a stand-in. The known set grows without bound and nothing reaches Redis, so run the real add against a queue before trusting the shape of the jobs.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| The script ends with an unhandled AbortError rejection. | A subscribe still pending when the signal fires rejects with AbortError. Catch it by name inside task and return. |
| Shutdown stalls after the abort until some stream sends a notification. | A merged iterator awaits return() behind a pending next() on a quiet source. Run one task per subscription, or call return() without awaiting it. |
| Duplicate jobs reach the workers. | Either add has no jobId, or removeOnComplete clears finished jobs so soon that a repeat gets through. Set the jobId and widen the age or count. |
| add throws on slot jobs. | BullMQ refuses a jobId that is a bare integer. Prefix it, as in slot-123456. |
| subscribe rejects and the socket upgrade is refused with 401. | An unknown key gets 401 at the door. Attach the whole key as the api-key query value on the WebSocket URL. |
| The slot count rises while the logs count stays at zero. | The mentions address is not the Token program, or the program watched has little traffic. Check the address string. |
Questions
Why not one merged async iterator?
A merge waits on every source's pending next() when it closes, so a quiet stream holds up a shutdown or a throw. Separate tasks never wait on each other.
Does an abort drop notifications already received?
Jobs already added stay in the queue. The loop leaves after the add it is awaiting, and anything the socket still held is dropped.
Can I add a third subscription?
Add a third task call to the started object and its counts and settle line follow. Each subscription counts against the plan's cap per account.
Which commitment do the two tasks use?
The logs task asks for confirmed in the code. slotNotifications takes no commitment setting.