Queues
Introduction
A queue lets you move slow or unreliable work (sending an invoice, resizing an image, calling a third-party API) out of the request that triggered it. You describe the work as a job class, push an instance onto a queue, and something else runs it later, retrying it if it fails.
@plinthjs/queue gives you the job contract, two in-process drivers (sync and array), a dispatcher for chains and batches, a set of job middleware, lifecycle events, and a QueueManager that names connections. @plinthjs/bus builds on the same ideas for commands, and is covered at the end of this page.
pnpm add @plinthjs/queueINFO
The built-in drivers are in-memory. sync runs a job the moment you push it and array holds jobs in a list until you call work(). Nothing in the package sleeps or reads the wall clock on its own: delays are recorded as timestamps and checked against an injectable clock, so every code path is deterministic. To run jobs from a durable store, implement the small Queue interface and register it with the QueueManager (see Connections and the queue manager).
Writing jobs
A job extends Job and implements handle(). It may be synchronous or return a promise. Anything the job needs goes through its constructor, so the data is captured when you push it.
import { Job } from '@plinthjs/queue'
export class SendInvoice extends Job {
tries = 3
constructor(private readonly invoiceId: number) {
super()
}
async handle(): Promise<void> {
// Do the work. Throwing marks the attempt as failed.
console.log(`sending invoice ${this.invoiceId}`)
}
}tries is the maximum number of attempts before the job is treated as failed. It defaults to 1.
Dispatching jobs
The quickest way to enqueue a job is to push it onto a queue driver. SyncQueue runs it immediately and awaits it; ArrayQueue stores it until you work the queue.
import { ArrayQueue, SyncQueue } from '@plinthjs/queue'
const sync = new SyncQueue()
await sync.push(new SendInvoice(1)) // runs now: logs "sending invoice 1"
const queue = new ArrayQueue()
await queue.push(new SendInvoice(2))
queue.size() // => 1
const summary = await queue.work()
// => { processed: 1, failed: 0 }A Dispatcher wraps a default queue so you can dispatch without holding on to the driver. With no argument it uses an inline SyncQueue.
import { ArrayQueue, Dispatcher } from '@plinthjs/queue'
const dispatcher = new Dispatcher(new ArrayQueue())
await dispatcher.dispatch(new SendInvoice(3))
// Or target a specific queue for one call:
await dispatcher.dispatch(new SendInvoice(4), new ArrayQueue())Delayed jobs
Call later(seconds, job) to make a job available after a delay. The driver records an absolute availableAt from its clock, and work() leaves the job in place until that instant has passed.
let now = 0
const queue = new ArrayQueue({ now: () => now })
await queue.later(60, new SendInvoice(5))
await queue.work() // => { processed: 0, failed: 0 } (not due yet)
queue.size() // => 1
now = 61_000 // advance the injected clock (milliseconds)
await queue.work() // => { processed: 1, failed: 0 }A job can also carry its own delay. When it declares delay and is pushed without an explicit later(), the array driver treats push(job) as later(job.delay, job).
class Reminder extends Job {
delay = 300 // seconds
handle() {
// ...
}
}The sync driver never defers: both push and later run the job inline.
Unique jobs
Set uniqueId to make sure only one copy of a job waits at a time. While a job with the same id is queued or running, the array driver ignores further pushes of that id.
class RebuildIndex extends Job {
uniqueId = 'rebuild-index'
handle() {
// ...
}
}
const queue = new ArrayQueue()
await queue.push(new RebuildIndex())
await queue.push(new RebuildIndex())
queue.size() // => 1The lock is released when the job finishes, whether it succeeds or fails for good. To keep the id reserved for a fixed window even after completion, also set uniqueFor (in seconds). A duplicate pushed inside that window is refused.
class NightlyReport extends Job {
uniqueId = 'nightly-report'
uniqueFor = 3600 // seconds
handle() {
// ...
}
}Dispatching after a transaction commits
A job that is queued inside a database transaction can start running before the transaction commits and read data that is not visible yet. Set afterCommit = true on the job and give the dispatcher a TransactionsAware object. While inTransaction() is true, the push is registered with addAfterCommitCallback instead of happening right away.
import { Dispatcher, SyncQueue } from '@plinthjs/queue'
class NotifyShipping extends Job {
afterCommit = true
handle() {
// ...
}
}
const callbacks: Array<() => void | Promise<void>> = []
let inTransaction = true
const dispatcher = new Dispatcher(new SyncQueue(), {
transactions: {
inTransaction: () => inTransaction,
addAfterCommitCallback: (callback) => {
callbacks.push(callback)
},
},
})
await dispatcher.dispatch(new NotifyShipping()) // deferred, callbacks.length => 1
inTransaction = false
for (const callback of callbacks) await callback() // the job runs nowJobs without afterCommit, and any dispatch outside a transaction, are pushed immediately.
Retries and backoff
When a job throws and has attempts left, the driver tries again. What happens between attempts depends on whether the job declares a backoff.
With no backoff (the default), the driver retries inline inside the same work() call, up to tries attempts.
With a backoff, the job is put back on the queue to become due later, carrying its attempt count with it. Return a number to wait that many seconds before every retry, or an array to wait a different time per attempt (the last entry repeats). backoff() may be async.
class CallPartnerApi extends Job {
tries = 3
async handle() {
// might throw
}
backoff() {
return [10, 30] // 10s after the first failure, 30s after the second
}
}With the array driver, the first work() runs the first attempt and leaves the job queued with a 10 second delay. Advancing the clock past that and calling work() again runs the second attempt, and so on.
maxExceptions caps how many attempts may throw before the job is failed early, even if tries would allow more. The effective limit is the lower of tries and maxExceptions.
class Strict extends Job {
tries = 10
maxExceptions = 2 // fail after two thrown attempts
handle() {
throw new Error('always')
}
}A job can also ask to be retried later without failing. Calling this.release(seconds) from inside the job (or middleware) puts it back on the queue after that delay and does not consume an attempt. The array driver honours it; the sync driver cannot defer, so it ignores a release.
Failed jobs
Once a job has used all its attempts, the driver calls its failed(error) hook and then records it. Override the hook to clean up or notify someone.
class ChargeCard extends Job {
tries = 2
handle() {
throw new Error('card declined')
}
failed(error: unknown) {
console.error('charge failed for good:', (error as Error).message)
}
}
const queue = new ArrayQueue()
await queue.push(new ChargeCard())
await queue.work() // => { processed: 0, failed: 1 }
queue.failed[0]?.attempts // => 2
queue.failer.jobs.length // => 1Every driver keeps its own failed list of { job, error, attempts } and also forwards each failure to a FailedJobStore. By default that is an in-memory ArrayFailedJobStore (reachable as queue.failer, with a flush() method). Pass your own store with the failer option to persist failures. A store only needs a log(job, error) method.
const queue = new ArrayQueue({
failer: {
log(job, error) {
console.error(job.constructor.name, error)
},
},
})By default a failure is recorded and the drain keeps going. Pass rethrow: true to stop and throw the final error instead. The job's failed() hook still runs first.
const sync = new SyncQueue({ rethrow: true })
try {
await sync.push(new ChargeCard())
} catch (error) {
// => Error: card declined
}Running a worker
ArrayQueue.work() is the worker loop. It drains every due job in first-in-first-out order, runs each one through its middleware, and resolves with a summary. process() is an alias.
const { processed, failed } = await queue.work()Delayed and backed-off jobs that are not yet due stay on the queue and are reported by size(). Jobs that release themselves are not re-run in the same drain unless the clock still reads the instant the drain started, so a job that releases itself forever cannot spin the loop.
To keep draining on a schedule and scale the number of workers, hand the queue to the queue supervisor.
Chains
dispatchChain runs jobs one after another and stops at the first one that fails for good. Only the first job is pushed onto the queue, and the rest of the chain travels with it: when a job succeeds, the worker pushes the next one. Every chained job therefore goes through the normal worker path, with its own queue, tries, backoff, middleware, failed() hook and failed-job store.
const result = await dispatcher.dispatchChain([new StepOne(), new StepTwo(), new StepThree()], {
onFailure: (error) => console.error('chain stopped', error),
})
result.completed // => true when every job ran
result.ran // => how many jobs finished so far
result.error // => the error from the job that failed for good, if anyWhen a job exhausts its attempts the chain stops, the remaining jobs never run, and onFailure (the chain's catch handler) is called with the error. A job that retries stays in place: the next job is pushed only after it finally succeeds.
The returned result is live. With the default sync queue the chain has finished by the time dispatchChain resolves. With the array driver, dispatchChain only queues the first job, and result updates as work() advances the chain (the next job is pushed during the same drain while the clock has not moved, otherwise on the next work()). Pass { queue } to use a queue other than the dispatcher's default.
Batches
A batch runs a group of jobs and tracks how many finished. Create one from the dispatcher, attach callbacks, and call dispatch().
import { ArrayBatchRepository, Dispatcher } from '@plinthjs/queue'
const dispatcher = new Dispatcher(undefined, { batches: new ArrayBatchRepository() })
const batch = await dispatcher
.batch([new SendInvoice(1), new SendInvoice(2)])
.onSuccess((batch) => console.log('all jobs succeeded', batch.id))
.onFailure((batch, error) => console.log('a job failed first with', error))
.onFinally((batch) => console.log('done', batch.progress()))
.dispatch()
batch.totalJobs // => 2
batch.processedJobs // => 2
batch.failedJobs // => 0
batch.pendingJobs // => 0
batch.progress() // => 100
batch.successful // => true
batch.finished() // => trueThe handlers are named onSuccess, onFailure and onFinally. onFailure receives the first error. onFinally always runs, after either of the other two.
By default a batch is considered cancelled as soon as one job fails. Call allowFailures() to keep going: every job runs, onFailure still fires at the end if any failed, and cancelled() only becomes true after an explicit cancel().
const batch = dispatcher.batch([new A(), new B(), new C()]).allowFailures()
await batch.dispatch()
batch.failedJobs // => 1 if B threw, and C still randispatch() pushes every job onto the queue, so batch jobs get the driver's retries, backoff, middleware, failed() hook and failed-job store. The worker counts each job as it finishes and fires onSuccess, onFailure and onFinally when the last one is done. With the default sync queue that has all happened by the time dispatch() resolves; with the array driver dispatch() only queues the jobs and the callbacks fire from work():
const queue = new ArrayQueue()
const batch = new Dispatcher(queue)
.batch([new SendInvoice(1), new SendInvoice(2)])
.onFinally((batch) => console.log('done', batch.progress()))
await batch.dispatch() // jobs are queued, nothing has run
await queue.work() // runs both, then fires onFinallyA job that calls release() inside a batch is put back on the queue without being counted, so the batch finishes only when that job eventually succeeds or fails for good. Jobs added with batch.add() after dispatch are pushed to the queue straight away.
Inside a job, this.batch() returns the batch it belongs to (or undefined). A job can cancel the batch, check its progress, or add follow-up jobs:
class ImportRow extends Job {
handle() {
const batch = this.batch()
if (batch?.cancelled()) return
// ...
batch?.add(new ImportRow()) // append more work to the running batch
}
}dispatcher.findBatch(id) looks a batch up in the repository you passed in. ArrayBatchRepository keeps batches in memory; implement BatchRepository (store, find, delete) to keep them elsewhere.
Job middleware
A job's middleware() method returns a list of functions that wrap handle(). Each receives the job and a next continuation. Run await next() to continue, or return without calling it to skip the job. Middleware runs outermost first, in array order.
import { Job, type JobMiddleware } from '@plinthjs/queue'
const timing: JobMiddleware = async (job, next) => {
const start = Date.now()
await next()
console.log(job.constructor.name, Date.now() - start, 'ms')
}
class Report extends Job {
handle() {
// ...
}
middleware() {
return [timing]
}
}A throw from handle() or any middleware counts as a failed attempt.
The package ships several ready-made middleware.
Preventing overlap
withoutOverlapping takes a lock and runs the job only if it can acquire it. A lock provider needs acquire(key, ttlSeconds) and release(key). If the lock is held, the job is released back to the queue.
import { withoutOverlapping } from '@plinthjs/queue'
class SyncAccount extends Job {
constructor(private readonly accountId: number) {
super()
}
middleware() {
return [withoutOverlapping(String(this.accountId), { lock }).releaseAfter(5)]
}
handle() {
// only one SyncAccount per account at a time
}
}releaseAfter(seconds) sets the delay before the released job is tried again, dontRelease() drops the job instead of re-queueing it, and expireAfter(seconds) sets the lock's time to live. The key is optional: withoutOverlapping({ lock }) locks per job class.
Rate limiting jobs
rateLimited lets a job run only a limited number of times per window. Pass a name (which uses a shared in-memory limiter) or any object with tooManyAttempts, hit and availableIn.
import { rateLimited } from '@plinthjs/queue'
class PostToSlack extends Job {
middleware() {
return [rateLimited('slack', { maxAttempts: 30, decaySeconds: 60 })]
}
handle() {
// ...
}
}When the limit is hit, the job is released for however long availableIn reports. Chain .dontRelease() to drop it instead. The defaults are 60 attempts per 60 seconds, and key lets several job classes share one budget.
Throttling exceptions
throttlesExceptions(maxAttempts, decaySeconds) is for flaky dependencies. When the job throws, the error is swallowed, counted against a budget, and the job is released to try again; once the budget is spent, the job is released until the window clears. Defaults are 10 and 600.
import { throttlesExceptions } from '@plinthjs/queue'
class FetchRates extends Job {
tries = 5
middleware() {
return [
throttlesExceptions(2, 60)
.backoff(5) // seconds to wait before the retry
.when((error) => error instanceof TypeError) // only throttle these; rethrow the rest
.report((error) => console.warn(error)) // called for each throttled error
.by('rates-api'), // share the budget across job classes
]
}
handle() {
// ...
}
}Skipping jobs
skip(condition) runs the job only when the condition is false. It accepts a boolean or a function of the job, which may be async.
import { skip, skipIfBatchCancelled } from '@plinthjs/queue'
class SendNewsletter extends Job {
constructor(private readonly paused: boolean) {
super()
}
middleware() {
return [skip(this.paused), skipIfBatchCancelled()]
}
handle() {
// ...
}
}skipIfBatchCancelled() skips the job when its batch has been cancelled.
Lifecycle events
Pass an events object, anything with a dispatch(event) method, to a driver (or to the QueueManager) and it announces what happens to each job.
| Event | When | Fields |
|---|---|---|
JobQueued | A job is added to an ArrayQueue | job, delaySeconds |
JobProcessing | An attempt starts | job, attempt |
JobProcessed | An attempt succeeds | job, attempt |
JobReleased | A job is re-queued (backoff or release()) | job, delaySeconds |
JobFailed | A job exhausts its attempts | job, error, attempts |
import { ArrayQueue, JobFailed, JobProcessed } from '@plinthjs/queue'
const queue = new ArrayQueue({
events: {
dispatch(event) {
if (event instanceof JobProcessed) console.log('done', event.job.constructor.name)
if (event instanceof JobFailed) console.error('failed', event.error)
},
},
})These events are also what you feed to the supervisor's metrics recorder; see Queue supervisor. For the framework's own dispatcher, see Events.
Connections and the queue manager
QueueManager resolves named connections. sync and array are built in, default picks the one used when you do not name a connection (sync if omitted), and connections are created once and cached.
import { QueueManager } from '@plinthjs/queue'
const manager = new QueueManager({ default: 'array' })
await manager.push(new SendInvoice(1)) // default connection
await manager.later(30, new SendInvoice(2), 'array')
manager.getDefaultConnection() // => 'array'
manager.connection() // the cached ArrayQueueShared options (now, failer, events) are passed to the built-in drivers. To add your own driver, supply a factory that returns anything implementing Queue (push, later, size, pop), either up front or with extend.
manager.extend('reports', () => new ArrayQueue())
await manager.push(new SendInvoice(3), 'reports')
manager.connection('missing')
// => Error: Queue connection [missing] is not defined.TIP
A generated app contains config/queue.ts with default, connections and failed keys. Those are the app's configuration values; the manager above takes its connections as code, so map your configuration onto QueueManager where you bootstrap your application.
Testing jobs
Use ArrayQueue with an injected clock. You can assert on size(), drain with work(), and inspect failed.
const queue = new ArrayQueue()
const dispatcher = new Dispatcher(queue)
await dispatcher.dispatch(new SendInvoice(10))
queue.size() // => 1
await queue.work()
queue.size() // => 0To test a job on its own, construct it and call handle().
The command bus
@plinthjs/bus dispatches command objects to handlers through a middleware pipeline. A command is any object; a handler is a function registered against the command's class.
pnpm add @plinthjs/busRegistering handlers and dispatching
import { Bus } from '@plinthjs/bus'
class CreateUser {
constructor(public readonly name: string) {}
}
const bus = new Bus()
bus.register(CreateUser, (command) => ({ id: 1, name: command.name }))
await bus.dispatch(new CreateUser('Ada'))
// => { id: 1, name: 'Ada' }
bus.hasHandler(CreateUser) // => truemap([[CommandClass, handler], ...]) registers several at once. If no handler is registered but the command has its own handle() method, that runs instead, so a command can handle itself:
class Ping {
handle() {
return 'pong'
}
}
await bus.dispatch(new Ping()) // => 'pong'A command with neither throws No handler registered for [Name], and it is not self-handling.
Middleware
pipeThrough sets the middleware that wraps every command. Each receives the command and a next function. Return next(command) to continue, or return a value to short-circuit.
bus.pipeThrough([
async (command, next) => {
console.log('before', command.constructor.name)
const result = await next(command)
console.log('after', result)
return result
},
])A command can add its own middleware by defining a middleware() method that returns a list. It runs after the bus-wide middleware, closest to the handler.
class Audited {
middleware() {
return [
async (command: object, next: (command: object) => Promise<unknown>) => {
console.log('audited')
return next(command)
},
]
}
handle() {
return 1
}
}Synchronous dispatch
dispatchSync returns the handler's result directly instead of a promise. Everything in the pipeline must be synchronous; if any step returns a promise, it throws dispatchSync requires synchronous handlers and middleware; got a Promise.
bus.register(CreateUser, (command) => command.name.toUpperCase())
bus.dispatchSync(new CreateUser('x')) // => 'X'dispatchNow is an alias for dispatch.
Queueing commands and chains
dispatchToQueue(command) pushes a command onto the bus's queue. By default that is a list on bus.queued; give the bus a CommandQueue (any object with push(command)) through the constructor or useQueue to forward commands to a real queue.
await bus.dispatchToQueue(new CreateUser('queued'))
bus.queued.length // => 1chain dispatches commands in order through the bus (its handlers and middleware) in the current process, and returns the results. It does not push anything onto a queue; to run a sequence of queue jobs with retries and failure handling, use the dispatcher's dispatchChain above. A failure calls the catch callback and then rethrows, so the remaining commands do not run. onQueue and onConnection set those properties on each command (through onQueue()/onConnection() methods when the command has them, otherwise as plain properties).
const results = await bus
.chain([new CreateUser('a'), new CreateUser('b')])
.catch((error) => console.error(error))
.dispatch()
// => ['A', 'B']bus.batch(jobs, queue?) creates a queue Batch (pass the queue its jobs should run on, or give one to batch.dispatch(queue)), and Batch, ArrayBatchRepository and the callback types are re-exported from @plinthjs/bus.
Faking the bus
fake() returns a FakeBus that records dispatched commands instead of running them, and has assertions.
import { fake } from '@plinthjs/bus'
const bus = fake()
await bus.dispatch(new CreateUser('z'))
bus.assertDispatched(CreateUser, (command) => command.name === 'z')
bus.assertDispatchedTimes(CreateUser, 1)
bus.assertNotDispatched(Ping)
bus.assertNothingDispatched() // throws: 1 command(s) were: [CreateUser]
bus.dispatched // every recorded command