Queue Supervisor
Introduction
A queue worker drains jobs. Once you have more than one queue, or more load than one worker can handle, you also need something that decides how many workers to run, which queue each one serves, and whether they should be running at all. @plinthjs/queue-supervisor is that layer.
It is headless: there is no dashboard and no operating-system process management. A worker "process" here is a logical concurrency slot over a work loop you provide, so scaling, balancing and the running / paused / terminated lifecycle are deterministic and easy to test. A MasterSupervisor coordinates several supervisors, and a MetricsRecorder reports throughput, runtimes, wait times and processed and failed counts.
pnpm add @plinthjs/queue-supervisor @plinthjs/queueRunning a supervisor
A Supervisor takes three things: a work loop (a function that drains one queue and reports how it went), options, and an optional probe that reports how many jobs are pending on a queue. For an ArrayQueue the helpers workLoopFor and pendingSizeFor build the first and last for you.
import { ArrayQueue } from '@plinthjs/queue'
import { pendingSizeFor, Supervisor, workLoopFor } from '@plinthjs/queue-supervisor'
const queue = new ArrayQueue()
const supervisor = new Supervisor(
workLoopFor(queue), // each slot drains the queue once per tick via queue.work()
{ queues: ['default', 'emails'], maxProcesses: 4, balance: 'auto' },
pendingSizeFor(queue), // load probe used by 'auto' balancing
)
supervisor.state() // => 'paused'
supervisor.start()
supervisor.state() // => 'running'
await supervisor.tick()
// => { processed: 0, failed: 0 } one round across every slotA supervisor starts paused, and tick() does nothing until you call start(). Each tick() runs the work loop once for every slot, in parallel, and sums the { processed, failed } results.
workLoopFor takes a single queue, or several. With one queue, every configured queue name is served by it (a driver is one queue, so the name means nothing). With a record keyed by queue name, or a function from a name to a queue, the supervisor's queue name picks the queue, so each name you list in queues drains its own queue. An unknown name throws No queue is configured for [name]. pendingSizeFor accepts the same record to probe each queue's depth.
const queues = { default: new ArrayQueue(), emails: new ArrayQueue() }
const supervisor = new Supervisor(
workLoopFor(queues),
{ queues: ['default', 'emails'], maxProcesses: 4, balance: 'auto' },
pendingSizeFor(queues),
)Which queue gets worked is decided by the supervisor, not the work loop. Each tick visits the queues in the order you listed them (so list them in priority order) and runs as many concurrent drains per queue as that queue's slot allocation says. With balance: 'off' the whole pool sits on the first queue (strict priority, later queues are never worked), with 'simple' slots are split evenly, and with 'auto' slots shift toward the queues with more pending jobs. There is no round-robin within a tick: every queue with slots is drained in the same tick.
A supervisor needs at least one queue and maxProcesses of at least 1, or the constructor throws.
Looping until told to stop
run() calls tick() repeatedly for as long as the supervisor is running, and resolves with the totals. A tick that worked nothing is followed by an idle sleep (idleSleepMs, default 1000) so an empty queue is polled instead of spun on; set it to 0 to poll back to back. Inject sleep to control the wait in tests.
const supervisor = new Supervisor(workLoopFor(queue), {
queues: ['default'],
maxProcesses: 2,
idleSleepMs: 500, // wait this long after an empty tick
maxJobs: 1000, // stop after this many jobs (processed + failed)
maxTimeSeconds: 3600, // stop after this long, measured with the injected `now`
})
supervisor.start()
const totals = await supervisor.run()
// => { processed: 12, failed: 0 }The loop ends when the supervisor is paused or terminated, when maxJobs jobs have been worked, when maxTimeSeconds has elapsed (checked after each tick and idle sleep), or when an optional predicate returns false after a round. maxJobs is checked after a tick, so the last tick may overshoot it.
let rounds = 0
await supervisor.run(() => ++rounds < 10)To test a loop without waiting, pass a fake sleep (and a fake now for maxTimeSeconds):
const supervisor = new Supervisor(loop, {
queues: ['default'],
maxProcesses: 1,
idleSleepMs: 1000,
maxTimeSeconds: 3,
now: () => clock,
sleep: async (ms) => {
clock += ms
},
})Controlling the lifecycle
A supervisor is in one of three states, and state() returns it as a string.
supervisor.pause() // 'paused': tick() does nothing
supervisor.continue() // back to 'running'
supervisor.isRunning() // => true
supervisor.terminate() // 'terminated'start(), continue() and pause() return the supervisor, so they chain. Termination is final: calling start(), pause() or continue() afterwards throws A terminated Supervisor cannot be restarted. (with paused or continued in place of restarted for the other two).
Scaling workers
maxProcesses is the ceiling and also the starting number of slots. scale(n) changes the current count, clamped between 1 and maxProcesses, and redistributes the slots.
supervisor.processCount() // => 4
supervisor.scale(2)
supervisor.processCount() // => 2
supervisor.scale(100)
supervisor.processCount() // => 4 (clamped to maxProcesses)To see where the slots are going:
supervisor.processes() // => { default: 2, emails: 2 }
supervisor.processesFor('emails') // => 2
supervisor.watching() // => ['default', 'emails']Balancing strategies
The balance option decides how slots are shared between queues.
'off'(the default): every slot works the first queue.'simple': slots are split evenly across the queues, with any remainder going to the earlier queues.'auto': slots follow each queue's pending size, as reported by your load probe.
new Supervisor(loop, { queues: ['a', 'b'], maxProcesses: 4 }).processes()
// => { a: 4, b: 0 }
new Supervisor(loop, { queues: ['a', 'b', 'c'], maxProcesses: 4, balance: 'simple' }).processes()
// => { a: 2, b: 1, c: 1 }Auto balancing has three knobs:
minProcesses(default 1) is the number of slots each queue keeps even when it is idle.balanceMaxShift(default 1) is the most slots that may move to or from a queue in one rebalance, so the allocation changes gradually.balanceCooldownMs(default 0) is the minimum time between rebalances, measured with the injectablenowclock.
Each tick() rebalances first when the strategy is auto. You can also force one and read the resulting allocation:
const supervisor = new Supervisor(
(name) => queues[name as keyof typeof queues].work(),
{
queues: ['default', 'emails'],
maxProcesses: 4,
minProcesses: 1,
balance: 'auto',
balanceMaxShift: 2,
},
(name) => queues[name as keyof typeof queues].size(),
)
supervisor.start()
// 'emails' has 6 pending jobs and 'default' has 1.
supervisor.processes() // => { default: 2, emails: 2 }
await supervisor.tick()
supervisor.processes() // => { default: 1, emails: 3 }rebalance() does the same adjustment on demand and returns the allocation. It has no effect unless the strategy is auto.
Coordinating several supervisors
A MasterSupervisor holds named supervisors and applies lifecycle calls to all of them. Give it a map up front or add them one at a time.
import { MasterSupervisor } from '@plinthjs/queue-supervisor'
const master = new MasterSupervisor({
web: new Supervisor(workLoopFor(queue), { queues: ['default'], maxProcesses: 2 }),
})
master.add(
'mail',
new Supervisor(workLoopFor(queue), {
queues: ['emails', 'sms'],
maxProcesses: 3,
balance: 'simple',
}),
)
master.names() // => ['web', 'mail']
master.processCount() // => 5
master.processes() // => { default: 2, emails: 2, sms: 1 }
master.start()
await master.tick() // => { processed: 0, failed: 0 }, summed across supervisors
master.states() // => { web: 'running', mail: 'running' }
master.state() // => 'running'pause(), continue() and terminate() fan out the same way. The master's own state() is running if any child is running, terminated if every child is terminated, and paused otherwise. supervisor(name) returns one child, supervisors() all of them, and size() counts them.
Recording metrics
MetricsRecorder collects one record per finished job and answers questions about them. It does not observe the queue itself: you tell it about each job, most conveniently from the queue's lifecycle events (see Queues).
import { ArrayQueue, JobFailed, JobProcessed } from '@plinthjs/queue'
import { MetricsRecorder } from '@plinthjs/queue-supervisor'
const metrics = new MetricsRecorder()
const queue = new ArrayQueue({
events: {
dispatch(event) {
if (event instanceof JobProcessed) {
metrics.recordJob({ queue: 'default', runtimeMs: 20, status: 'processed', waitMs: 5 })
}
if (event instanceof JobFailed) {
metrics.recordJob({ queue: 'default', runtimeMs: 40, status: 'failed' })
}
},
},
})A recorded job has a queue name, a runtime, a status of processed or failed, and an optional wait time. After some jobs have run you can read the numbers per queue or overall:
metrics.processed() // => 2
metrics.failed('default') // => 0
metrics.averageRuntime() // => 20 (milliseconds)
metrics.averageWait() // => 5
metrics.throughput() // => jobs per minute over the last window
metrics.forQueue('default')
// => { queue: 'default', processed: 2, failed: 0, averageRuntimeMs: 20,
// averageWaitMs: 5, throughputPerMinute: 2 }
metrics.snapshot()
// => { at, overall: { queue: '*', ... }, queues: { default: { ... } } }total() counts every recorded job and queues() lists the queue names in the order they were first seen. Throughput counts records inside a sliding window (60 seconds by default; set throughputWindowMs) and scales to a per-minute figure. Both throughput and the snapshot timestamp use the injectable now clock, so you can test them with a fixed time:
let now = 0
const metrics = new MetricsRecorder({ now: () => now, throughputWindowMs: 60_000 })Average wait only includes jobs that supplied waitMs.
Testing
Everything here is deterministic: use ArrayQueue with a controlled clock, call tick() yourself, and pass now to the supervisor and recorder when you need to test cooldowns or throughput.
const supervisor = new Supervisor(workLoopFor(queue), { queues: ['default'], maxProcesses: 1 })
supervisor.start()
await queue.push(new SendInvoice(1))
await supervisor.tick() // => { processed: 1, failed: 0 }