Worker Queues
Distributed job processing with BullMQ — background execution for agents, workflows, and swarms.
Overview
The @cogitator-ai/worker package provides distributed job processing backed by BullMQ and Redis. It supports background execution of agents, workflows, and swarms with automatic retries, job priorities, and Prometheus metrics for autoscaling.
pnpm add @cogitator-ai/worker @cogitator-ai/core ioredisJobQueue
JobQueue dispatches serialized agent, workflow and swarm configurations as jobs to Redis. Without options, the queue is named cogitator-jobs and jobs get 3 attempts with exponential backoff from 1 s, keeping the last 100 completed and 500 failed jobs.
import { JobQueue } from '@cogitator-ai/worker';
const queue = new JobQueue({
name: 'cogitator-jobs',
redis: { host: 'localhost', port: 6379 },
defaultJobOptions: {
attempts: 3,
backoff: { type: 'exponential', delay: 1000 },
removeOnComplete: 100,
removeOnFail: 500,
},
});
const job = await queue.addAgentJob(
{
name: 'researcher',
instructions: 'You are a research assistant.',
model: 'gpt-5.5',
provider: 'openai', // prepended when `model` names no provider the worker routes to
tools: [],
},
'Summarize the latest AI papers on reasoning',
{ priority: 1, threadId: 'thread_abc123', userId: 'user_42', delay: 5_000 }
);
console.log('State:', await queue.getJobState(job.id!));The worker routes model like the same agent in-process: a prefix naming a built-in provider, a backend in the worker Cogitator's llm.backends or a registered plugin picks that provider, so openrouter/deepseek/deepseek-v4-pro runs on an openrouter backend whatever provider says. The optional provider (any provider the worker routes to, custom backends and plugins included) is prepended only to a model whose prefix names none, such as meta-llama/llama-4-scout with provider: 'openrouter'. Without it such a model runs on the worker's llm.defaultProvider, and a provider the worker cannot route to fails the job. serializeAgent sends an agent with an explicit provider as <provider>/<model>, so { model: 'openai/gpt-5', provider: 'openrouter' } runs on openrouter on the worker as it does in-process.
Queueing an agent you already have
serializeAgent turns an Agent into a job in the agent wire format of @cogitator-ai/core (toAgentWire), the one workflow jobs and distributed swarms use too: its whole configuration (model and provider, instructions, sampling, stop sequences, reasoning, response format, iteration limit, timeout), its tool schemas and the agents it can hand over to. A Zod response schema travels as JSON Schema and the worker turns it back into a Zod schema, so a queued run validates and repairs its structured answer like an in-process run, and the job result carries it. The worker refuses a config with a key it does not know (a producer newer than the worker) instead of running the agent without that setting:
import { serializeAgent, type AgentJobResult } from '@cogitator-ai/worker';
const job = await queue.addAgentJob(serializeAgent(chiefEditor), 'Pitches: ...');
// once the job completes
const result = (await queue.getJob(job.id!))?.returnvalue as AgentJobResult;
result.structured; // the validated answer of a json_schema agent, when it fits
result.usage; // { inputTokens, outputTokens, totalTokens, cost, duration, reasoningTokens?, ... }
result.truncated; // also blocked, iterationLimitReached, structuredError, toolCalls with outputsAgent jobs that wait for approval
An agent whose tool needs approval (requiresApproval) pauses its run, and the job completes with status: 'paused': output is then not the answer, pendingApprovals lists the calls that wait, and checkpoint holds what the run continues from. Resume it with the decisions as a new job, on any worker, since the checkpoint travels with it:
const result = (await queue.getJob(job.id!))?.returnvalue as AgentJobResult;
if (result.status === 'paused') {
await queue.resumeAgentJob(serializeAgent(support), result, {
decisions: { [result.pendingApprovals![0].toolCallId]: { approved: true } },
// or defaultDecision: { approved: false, reason: 'not eligible' }
});
}Calls left without a decision pause the run again, and the new job's result says so the same way. A result without its checkpoint is resumed by thread from the worker's runCheckpoints store, which the workers then have to share (a memory adapter or your own store). A workflow or swarm job cannot wait for a decision: when one of its agents pauses, the job fails without retries with an AgentRunPausedError naming the agent, the node or swarm and the calls.
The redis config also takes a url (redis://user:password@host:port/db, or rediss:// for TLS); explicit host, port, username, password, db and tls fields override what it says.
getJobState(id) returns 'waiting', 'prioritized' (added with a priority), 'delayed', 'active', 'completed', 'failed', 'waiting-children' (the parent of a BullMQ flow) or 'unknown' (the JobState type).
threadId defaults to a fresh id; userId makes the run act for that user (it owns the thread), and metadata is stored on the payload. Other queue methods: getJob(id), getMetrics(), pause(), resume(), clean(grace, limit, state), getQueue() (the underlying BullMQ Queue) and close().
Workflow and swarm jobs follow the same pattern:
await queue.addWorkflowJob(workflowConfig, { query: 'input' }, { priority: 2 });
await queue.addSwarmJob(
{ topology: 'debate', agents: [proAgent, conAgent], coordinator: moderatorAgent, maxRounds: 2 },
'Debate the pros and cons of microservices'
);Workflow jobs run a SerializedWorkflow graph (agent, transform, condition and parallel nodes over a shared state object) on the WorkflowExecutor of @cogitator-ai/workflows. Nodes run in rounds, each running at once every node whose nodes before it all settled, and a graph with many roots starts at all of them. An agent node takes the same serializeAgent config, and writes its validated structured answer to the state when its agent has a JSON schema response format (its text otherwise), so later nodes read fields like {{decision.verdict}}. The run keeps its own bookkeeping in state keys starting with __cogitator:, which are left out of the job's output, and input keys, node ids and output keys starting with __cogitator: are refused. Swarm topologies map to strategies (sequential → pipeline, hierarchical → hierarchical with the coordinator as supervisor, collaborative → a pipeline in which every agent contributes in each of maxRounds rounds (default 3) seeing all contributions so far, the coordinator (if any) combining them, debate → debate, voting → consensus). See the package README for the full workflow node reference.
Workflow checkpoints and retries
A workflow job keeps one checkpoint, saved over after every node under the job's id and runId, so jobs sharing a runId never resume from each other. When an attempt fails and BullMQ retries the job, the next attempt goes on from the checkpoint instead of running the agent nodes that already finished again. The checkpoint is deleted once the run finished, and once no attempt follows a failure: after the last attempt, a cancelled job or a paused agent run. A job a shutdown stopped keeps it for the worker that takes the job up. WorkerPool keeps the checkpoints in its Redis under <queue prefix>:<queue name>:workflow-checkpoints (cogitator, or {cogitator} in cluster mode) for checkpointTtl seconds after the last save (7 days by default), so the checkpoint of a run whose worker crashed goes on its own. checkpoints in the pool config takes a CheckpointStore of your own (any store of @cogitator-ai/workflows, such as PostgresCheckpointStore).
processWorkflowJob(payload, runtime, execution) called on its own runs without checkpoints unless runtime.checkpoints is given. With a store, pass execution.willRetry: a run whose failure another attempt follows (willRetry(error) returns true) keeps its checkpoint for it, any other failure deletes it.
Job ids
addAgentJob, resumeAgentJob, addWorkflowJob, addSwarmJob and addSwarmAgentJob take a jobId, and the job is added under it. Adding a job whose id the queue holds already returns that job instead of adding a second one, so a producer can retry an add (after a timeout, say) without running the work twice:
const job = await queue.addAgentJob(config, 'Summarize the report', {
jobId: `summary-${reportId}`,
});
// a retry of the same add returns the same job
await queue.addAgentJob(config, 'Summarize the report', { jobId: `summary-${reportId}` });Two adds racing with the same id both get the job the queue holds. A job the queue removed (past removeOnComplete or removeOnFail) is gone, and its id adds a new job. BullMQ builds Redis keys from the id, so an empty id, one containing :, an integer and a name of the queue's own keys (meta, id, events, stalled-check and the like) are refused, and an id the queue holds as another kind of job (an agent job for addWorkflowJob, say) throws. Without jobId every add gets a fresh id.
Usage of workflow and swarm jobs
Workflow and swarm results carry usage, summed over their agent runs (JobUsage): inputTokens?, outputTokens?, totalTokens, cost (USD) and runs. A workflow sums its agent nodes. A swarm adds byAgent, a Record of agent name to { tokens, cost, runs }, and has no input and output split.
const result = (await queue.getJob(job.id!))?.returnvalue as SwarmJobResult;
result.usage; // { totalTokens, cost, runs, byAgent: { researcher: { tokens, cost, runs }, ... } }WorkerPool
WorkerPool spawns BullMQ workers that consume jobs from the queue. Built-in processors handle agent, workflow, swarm, and swarm-agent job types (queue.addSwarmAgentJob, one turn of a swarm queued by your own code). Distributed swarms (distributed.enabled) do not use this queue: their turns go to a Redis list that DistributedSwarmWorker consumes, see below. Without a cogitator, the pool runs agents with new Cogitator() (provider keys from the environment).
import { Cogitator } from '@cogitator-ai/core';
import { WorkerPool } from '@cogitator-ai/worker';
const pool = new WorkerPool(
{
name: 'cogitator-jobs',
redis: { host: 'localhost', port: 6379 },
workerCount: 4,
concurrency: 5,
cogitator: new Cogitator({
llm: { providers: { openai: { apiKey: process.env.OPENAI_API_KEY! } } },
}),
tools: [webSearch, calculator],
},
{
onJobStarted: (jobId, type) => console.log(`${type} job ${jobId} started`),
onJobCompleted: (jobId, result) => console.log(`${jobId} done`, result.type),
onJobFailed: (jobId, error) => console.error(`${jobId} failed:`, error.message),
onWorkerError: (error) => console.error(error),
}
);
await pool.start();
process.on('SIGTERM', async () => {
await pool.stop(30_000); // graceful, force-closes after the timeout
await queue.close();
});lockDuration and stalledInterval are passed to BullMQ. Each job gets the abort signal BullMQ gives it, down to every agent run, workflow node and swarm turn of the job: pool.cancelJob(jobId, reason?) stops a running job (it fails without retries), and stop(timeout) aborts the jobs still running when the timeout runs out before force-closing the workers, so BullMQ hands them to another worker once their locks expire instead of a stalled run going on unlocked. forceStop() aborts running jobs and closes workers without waiting, getWorkerCount() and isPoolRunning() report pool state.
Serialized agents carry tool schemas only. The pool resolves tools by name from its tools option; jobs that need tools the worker does not provide fail with a clear error instead of running with stubs.
Distributed Swarm Workers
Swarms with distributed.enabled dispatch each agent turn to Redis. Run DistributedSwarmWorker on worker nodes to execute them:
import { DistributedSwarmWorker } from '@cogitator-ai/worker';
const worker = new DistributedSwarmWorker({
redis: { url: 'redis://localhost:6379' }, // the same Redis as the swarm's distributed.redis
keyPrefix: 'swarm', // must match the swarm's distributed.redis.keyPrefix
queue: 'swarm-agent-jobs', // must match distributed.queue
concurrency: 4, // default 4
cogitator,
tools: [webSearch],
});
await worker.start();redis is the same RedisConnectionConfig as the swarm's distributed.redis and the queue's redis: a url (rediss:// for TLS), host, port, username, password, db, tls or cluster.nodes, the url read first and the explicit fields winning over it. pollTimeout (seconds, default 1) controls how long a blocking poll waits before re-checking state. A second constructor argument takes onJobStarted, onJobCompleted, onJobFailed, onJobCancelled, onJobsRecovered and onError callbacks.
The queue is reliable: a worker moves each turn with BLMOVE (Redis 6.2 or newer) from the list <keyPrefix>:jobs:{<queue>} to its own list <keyPrefix>:jobs:{<queue>}:processing:<workerId> and takes it off once the turn is done. It keeps a heartbeat key <keyPrefix>:jobs:{<queue>}:heartbeat:<workerId> alive every heartbeatInterval ms (default 5000, the key expires after three intervals) and is listed in the set <keyPrefix>:jobs:{<queue>}:workers. On start() and on every beat, a worker moves the turns of workers whose heartbeat is gone back to the head of the queue, drops those workers from the set and reports onJobsRecovered(workerId, count). A worker also checks its own list on every beat: a turn on it that the worker does not run at two beats in a row, such as one a BLMOVE moved while a dropped connection lost its reply, goes back to the head of the queue and is reported with the worker's own id. A worker silent for three intervals counts as gone, so a turn on a stalled worker can run twice. The result is kept under the job's stateKeys.result for resultTtl ms before it is published, and a worker skips a job whose result is already there. stop() waits for in-flight turns, hands back what is left on its list, leaves the set and deletes its heartbeat. getWorkerId() gives the worker's id, new on every start().
The braces in <keyPrefix>:jobs:{<queue>} are a Redis Cluster hash tag, so the queue and its worker keys sit in one slot. Earlier versions used <keyPrefix>:jobs:<queue>, so upgrade the processes that run swarms and the workers together.
See Distributed Swarms for the coordinator side.
Redis Cluster
Pass cluster nodes to both queue and workers. They connect to every listed node through an ioredis Cluster, and cluster mode uses the {cogitator} hash tag prefix to keep keys on the same slot.
const redisConfig = {
password: process.env.REDIS_PASSWORD,
cluster: {
nodes: [
{ host: 'redis-1.example.com', port: 6379 },
{ host: 'redis-2.example.com', port: 6379 },
],
},
};
const queue = new JobQueue({ redis: redisConfig });
const pool = new WorkerPool({ redis: redisConfig, workerCount: 4, concurrency: 10 });DistributedSwarmWorker and the swarm's distributed.redis take the same config, their keys carry their own hash tags (the queue name and the swarm id).
Prometheus Metrics
queue.getMetrics() returns the queue counts, WorkerPool records job durations, per-type counts, usage and final failures in pool.metrics (a MetricsCollector: recordJob(type, durationMs) and recordUsage(type, result.usage) on completion, recordFailure(type) when a job fails its last attempt). Combine them in the Prometheus exposition format for monitoring and Kubernetes HPA:
app.get('/metrics', async (req, res) => {
const metrics = await queue.getMetrics();
res.set('Content-Type', 'text/plain');
res.send(pool.metrics.format(metrics, { queue: 'cogitator-jobs' }));
});Label values are escaped per the Prometheus exposition format. Without a pool, formatPrometheusMetrics(await queue.getMetrics(), labels) renders the queue metrics alone.
| Metric | Type | Description |
|---|---|---|
cogitator_queue_depth | gauge | Jobs waiting + delayed |
cogitator_queue_waiting | gauge | Jobs ready to run, prioritized jobs included |
cogitator_queue_delayed | gauge | Delayed / scheduled jobs |
cogitator_queue_active | gauge | Jobs currently processing |
cogitator_queue_completed | gauge | Completed jobs kept in Redis (capped by removeOnComplete) |
cogitator_queue_failed | gauge | Failed jobs kept in Redis (capped by removeOnFail) |
cogitator_workers_total | gauge | Workers connected to the queue |
cogitator_jobs_by_type_total | counter | Jobs processed by type |
cogitator_jobs_failed_total | counter | Jobs that failed their last attempt, by type |
cogitator_job_duration_seconds | histogram | Processing time distribution |
cogitator_job_tokens_total | counter | Tokens the agent runs of completed jobs used, by type |
cogitator_job_input_tokens_total | counter | Input tokens of completed jobs, by type |
cogitator_job_output_tokens_total | counter | Output tokens of completed jobs, by type |
cogitator_job_cost_usd_total | counter | USD the agent runs of completed jobs cost, by type |
cogitator_queue_completed and cogitator_queue_failed come from BullMQ and drop as old jobs are trimmed, so they are not counters. Alert on cogitator_jobs_failed_total instead, for example increase(cogitator_jobs_failed_total[5m]) > 5. The per-type counters appear after the first job of that type. The usage counters add up the usage of completed agent, workflow, swarm and swarm-agent jobs, input and output tokens only where a job reported them apart (swarm jobs report totals only), so sum by (type) (increase(cogitator_job_cost_usd_total[1h])) shows what each job type spent in the last hour.
HPA Autoscaling
Use cogitator_queue_depth as the scaling signal in a Kubernetes HorizontalPodAutoscaler (through a custom-metrics adapter such as prometheus-adapter or KEDA):
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: cogitator-worker
minReplicas: 1
maxReplicas: 20
metrics:
- type: Pods
pods:
metric:
name: cogitator_queue_depth
target:
type: AverageValue
averageValue: '10'