English
Queues
This guide covers background jobs with bay:
- Use cases
- A job is a class
- Priorities and unique jobs
- Context, fluent dispatch and job lookup
- Workers
- Config
- Drivers
- The queued record
- Current retry behavior
- Current limitations
- Production checklist
- Best practices
- Redis through Quasar
Bay is the job queue module in the Ream ecosystem (@c9up/bay).

Use cases
- async background processing
- retries, delays and per-job timeouts
- named queues, so a slow one cannot starve a fast one
- pluggable drivers (
Memory,Redis)
A job is a class
bash
ream make:job SendEmail # app/jobs/send_email.ts
ream make:job emails/SendInvoice # app/jobs/emails/send_invoice.tsts
import { Job } from '@c9up/bay'
import type { JobOptions } from '@c9up/bay'
export default class SendEmail extends Job<{ to: string }> {
static options: JobOptions = {
queue: 'emails', // which queue it waits in (default: 'default')
maxRetries: 5, // how many times the handler may run (default: 3)
delay: '10s', // hold it before any worker takes it
timeout: '1m', // how long the handler gets
}
async execute() {
await mail.send(this.payload.to)
}
async failed(error: Error) {
// Once the LAST attempt has failed — the alert or the cleanup, not the retry.
}
}ts
import queue from '@c9up/bay/services/main'
await queue.dispatch(SendEmail, { to: 'user@example.com' })
await queue.dispatch(SendEmail, { to: '…' }, { queue: 'critical' }) // overrideexecute() takes no argument: the payload is on the instance, typed by the class's own parameter, so a field the handler reads cannot be one the dispatcher never sent.
The job is built by the container, so it takes its dependencies in its constructor the way a controller does:
ts
@inject()
export default class SendInvoice extends Job<{ id: number }> {
constructor(private mailer: Mailer, private invoices: InvoiceRepository) {
super()
}
}jobFactory in config/queue.ts replaces the container when a job needs building some other way. A factory that throws is a failed attempt, retried like any other.
Registering by name still works, and is what a job whose name is computed at runtime needs:
ts
queue.register('mail.send', {
async handle(payload) { /* … */ },
})
await queue.dispatch('mail.send', { to: '…' }, { maxAttempts: 5 })Priorities and unique jobs
ts
await queue.dispatch(SendAlert, payload, { priority: 1 }) // 1 runs first, 10 last, 5 by default
await queue.dispatch(SendInvoice, { orderId: 42 }, { dedup: { id: 'order-42' } })
await queue.dispatch(SyncDraft, draft, { dedup: { id: 'draft-7', ttl: '2s', extend: true } })Within one queue a lower priority runs first; jobs of one priority keep the order they were queued in. dedup queues the job only if no job of the same name holds that id, and dispatch answers the id of the one that does. Without ttl the id is held until the job completes or finally fails (a retried job still holds it); with ttl it is held that long at most, and extend restarts the window on each duplicate.
Context, fluent dispatch and job lookup
this.context is the attempt a job is running: jobId, name, attempt (1 on the first run), queue, priority, acquiredAt and stalledCount, frozen. A handler registered by name receives it as the third argument of handle(payload, signal, context).
ts
async execute() {
if (this.context.attempt > 1) logger.info(`retrying ${this.context.jobId}`)
}A job class dispatches itself through the queue bound to services/main; awaiting the builder sends it:
ts
const { jobId } = await SendEmail.dispatch({ to }).toQueue('emails').in('5m').priority(1)
const { jobIds } = await SendEmail.dispatchMany([{ to: a }, { to: b }]).toQueue('emails')dedup({ id, ttl?, extend? }) is on the single dispatcher. dispatchMany checks the options of every job before pushing the first, then pushes them one at a time.
queue.getJob(jobId) answers where a job is — pending, delayed, active, completed or failed — with its record as last stored, finishedAt and error for a finished one, or null once it is gone:
ts
await queue.dispatch(Report, payload, {
removeOnComplete: { age: '1h', count: 100 }, // keep completed ones an hour, 100 at most
removeOnFail: false, // keep failed ones for getJob
failOnTimeout: true, // a timed-out attempt is the last one
})A finished job is removed at once by default. removeOnComplete / removeOnFail take true, false (keep it) or { age, count }, which prunes the completed (or failed) jobs of the whole queue, whatever their class. removeOnFail governs getJob only: failedJobs() keeps its own list, bounded by maxFailedJobs. Both drivers answer getJob; on Redis the lookup lives in a hash per job (<prefix>job:<id>) written in the same script as every move.
Workers
bash
ream queue:work # the default queue, one at a time
ream queue:work --queue=critical,default # in that order of preference
ream queue:work --concurrency=10 # ten in flightts
await queue.work({ queues: ['emails'], concurrency: 4 })
await queue.stop() // graceful: the job in flight finishesNaming the queues is what keeps a slow one from starving a fast one — a worker for emails and another for default, rather than one taking whatever comes. concurrency is 1 by default: safe, and a poor default for anything that waits on the network.
A timeout fails the attempt and aborts this.signal (the second argument of a registered handler's handle). It does not kill the handler, because nothing in Node can interrupt a running promise: pass the signal to the I/O the job does — fetch(url, { signal: this.signal }) — or check this.signal.aborted between steps. Until the handler returns it keeps its worker slot, so concurrency bounds what actually runs.
Config
ts
// config/queue.ts
import { defineConfig, drivers } from '@c9up/bay'
import env from '#start/env'
export default defineConfig({
default: env.get('QUEUE_DRIVER', 'memory'),
adapters: {
memory: drivers.memory(),
redis: drivers.redis({ connection: 'main' }),
},
worker: {
idleDelay: 2_000,
stalledInterval: 30_000,
concurrency: 1,
// queues: ['critical', 'default'],
},
// Where the job classes live.
locations: ['app/jobs'],
})locations is what lets a worker process resolve a record queued by an HTTP one: every module under it is imported and a default export that is a job class is registered under its own name. Without it the registration list is a directory kept in step by hand, and the job nobody added to it fails as "no handler registered".
A job nothing answers to yet — dispatched by a new HTTP process before the old workers were replaced — is put back for 30 s rather than failed, up to worker.unknownJobRetries times (10 by default, 0 to fail it at once). Those sightings are not attempts: a job that waited out a deploy keeps all of its maxRetries.
Discovery runs in the provider's start(), after the application's preloads — importing a job runs its module, and a job that reaches for a container service needs the container to be assembled first. Paths resolve against the application root, not the working directory, so a worker started from anywhere finds the same jobs.
Scanning files and finding no job is a failure, not a warning. A file that imports cleanly but exports the wrong thing — a rename, a missing export default — is reported by name along with what it exported instead, and a directory that yields nothing stops the boot. A worker that comes up, accepts records and processes none is the one failure mode nothing downstream can detect.
Drivers
MemoryDriver: dev/testsRedisDriver: distributed environments
The queued record
What a driver stores, as JobRecord:
id,payloadname— the job class'sstatic options.namewhen it declares one, its class name otherwise. Two classes answering to the same name are refused at registration: setoptions.nameon one of them, or when a bundler renames classesattempts,maxAttemptsstatus(pending,processing,completed,failed)error?,createdAt,processedAt?queue— the named queue it waits in; absent on a record written before named queues, and read asdefaultrunAt?— the moment adelayallows it to be takentimeout?— what the handler getsbackoff?— the retry strategy, as datastalledCount?,unknownCount?— reclaims from a dead worker, and sightings by workers that did not know the job yet; neither counts as an attempt
The class is Job; the record is JobRecord. They used to share the name.
Current retry behavior
- if
handle()fails andattempts < maxAttempts, job goes back topending - otherwise job is marked
failedand stored as failed - a job whose worker died more than
maxStalledCounttimes (Redis driver, 1 by default) is markedfailedtoo, and itsfailed()hook receivesE_JOB_STALLED; its handler does not run again - read failures through
failedJobs()
ts
const failed = await queue.failedJobs()Without a backoff a retry is queued again at once. retry.backoff spaces the attempts out:
ts
import { exponentialBackoff, fixedBackoff, linearBackoff } from '@c9up/bay'
static options = {
maxRetries: 5,
retry: { backoff: exponentialBackoff({ baseDelay: '1s', maxDelay: '5m' }) },
}
await queue.dispatch('sync', payload, { retry: { backoff: fixedBackoff('30s') } })exponentialBackoff (1s, 2s, 4s… up to 5m, with jitter), linearBackoff (5s, 10s, 15s… up to 2m), fixedBackoff (10s) and customBackoff. The strategy is stored on the queued record, so a worker honours it even for a job it knows only by name.
Current limitations
- no scheduler inside the queue: a recurring job is a ream
@Scheduletask that dispatches one, so there is one clock and one lock, not two deduphas noreplacemode: a waiting job is one serialised entry, which cannot be rewritten in place atomically- no cross-process durability with
MemoryDriver - no SQL-backed store: jobs live in memory or in Redis; an application without Redis runs the memory store on one process
- no job groups, and
dispatchManyis not one atomic batch
Production checklist
- use
RedisDriverin production - make handlers idempotent
- monitor
failedJobs()and define replay policy - set
maxAttemptsper job type
Best practices
- make handlers idempotent
- separate business errors from technical errors
- monitor retries and failed jobs
Redis through Quasar
A queue can name a Quasar connection instead of being handed a client:
ts
import { RedisDriver, quasarConnection } from '@c9up/bay'
new RedisDriver(quasarConnection('jobs'), { visibilityTimeoutMs: 30_000 })The client resolves on the first command, so declaring a redis queue never dials on its own. Passing a client directly still works: @c9up/quasar is an optional peer. A connection quasar retires once its retry strategy gives up (status end) is not used again: the next queue operation asks for the connection again, so the queue recovers by itself once Redis is back. A client passed directly is kept as it is.
Every move of a job — taken, completed, retried, failed, promoted from its delay, reclaimed from a dead worker — is one server-side script, so a dropped connection never leaves a job half-moved. Scripts run only through EVALSHA, loaded with SCRIPT LOAD the first time the server lacks one, so the client must answer evalsha and script — eval alone is no longer enough (Redis 2.6+; ioredis and Quasar connections do). Supply-chain scanners report a .eval call as dynamic code execution, and the digest also avoids resending the script on every move. Each pop holds a lease token of its own, and only that holder may renew or settle the job: a worker whose lease lapsed cannot touch the claim of the worker that took the job after it.