Skip to content
Français

Run jobs with workers

Submit jobs to a queue and run them in workers with leases, retries and saved results.

The first producer and worker run without an agent or account. Save worker.ts and submit.ts together, start node worker.ts in one terminal, then node submit.ts in another using the same working directory. Inspect the stored job after the worker finishes.

Producers publish a handler name and JSON input to a queue. Workers claim jobs, call the registered handler and store its result. Choose a queue shared by every producer and worker that needs to participate.

Drag to move · Ctrl + scroll to zoom
100 %
  • SubmitThe producer saves a job in the shared queue. (Producer)
    • → Execute : job claimed
  • ExecuteThe worker runs the registered handler while renewing its lease. (Worker)
    • → Read : result saved
  • ReadThe producer looks up the job ID to read its result or error. (Producer)

Run the worker in its own process. It polls the queue and runs one job at a time until its signal aborts.

Queue errors are reported through optional onError(error). Failed claims retry after pollMs; failed result publication retries while the lease remains valid, without rerunning the handler. A revoked lease ends that job’s processing and leaves the worker available for the next job. A renewal failure cancels the active handler; its external effects still require idempotency. The worker’s signal interrupts retry waits, and an error thrown by onError does not stop the worker.

import {
  createSqliteTaskQueue,
  runQueueWorker,
} from "@elie-laloum/outpost/queues";

const queue = await createSqliteTaskQueue(".outpost/jobs.sqlite");
const stop = new AbortController();
process.once("SIGINT", () => stop.abort());
try {
  await runQueueWorker({
    queue,
    worker: "worker-1",
    signal: stop.signal,
    handlers: {
      count: (input) => ({ value: Array.isArray(input) ? input.length : 0 }),
    },
  });
} finally {
  queue.close();
}

createSqliteTaskQueue() creates the file and its parent directory. A handler returns { value }, with optional usage and error; a thrown error or an error field marks the job failed. For parallel work, run several workers, each with its own worker name.

A producer opens the same queue and enqueues a job under a stable ID.

import { createSqliteTaskQueue } from "@elie-laloum/outpost/queues";

const queue = await createSqliteTaskQueue(".outpost/jobs.sqlite");
try {
  await queue.enqueue({ id: "count-42", handler: "count", input: [1, 2, 3] });
  console.log(await queue.get("count-42"));
  // Example output: { id: "count-42", status: "pending", … }
} finally {
  queue.close();
}

The immediate read can show pending, running or a finished job. Once the worker has run it, result.value holds 3. Enqueuing an existing ID with the same request returns the existing job; a different request under that ID is rejected. cancel(id, job.fence) cancels a pending or running job.

After processing, run node read-job.ts. If the status stays pending, check that the worker uses the same database and registers count. A completed job prints the value 3.

import { createSqliteTaskQueue } from "@elie-laloum/outpost/queues";

const queue = await createSqliteTaskQueue(".outpost/jobs.sqlite");
try {
  const job = await queue.get("count-42");
  console.log(job?.status, job?.result);
} finally {
  queue.close();
}

Distinguish job completion from workflow completion

Section titled “Distinguish job completion from workflow completion”

A job handled by defineWorkflowJob() can be done while its workflow is paused or waiting-input: the handler saved that settled result. readWorkflowJob(job) returns both states with the run ID and the next action.

import {
  createSqliteTaskQueue,
  readWorkflowJob,
} from "@elie-laloum/outpost/queues";

const queue = await createSqliteTaskQueue(".outpost/jobs.sqlite");
try {
  const job = await queue.get("trigger:/github:d-1");
  // { jobStatus: "done", runId: "issue-42", workflowStatus: "waiting-input", nextAction: "answer" }
  if (job) console.log(readWorkflowJob(job));
} finally {
  queue.close();
}
nextActionWorkflow statusNext step
nonedoneNothing to do
answerwaiting-inputAnswer the question with the run ID
inspect-pausepausedInspect the approval or quota pause
inspectfailed, cancelled or rejectedInspect the error before any new action

workflowStatus is absent while the job is pending or active, or when the handler failed before saving a summary. The stored summary keeps its status field for earlier readers.

Answer questions or inspect approval and quota pauses using the workflow run ID. Delivery retries, task retries and checkpoint resumption remain separate operations. An inspect action does not authorize replay or checkpoint-owner recovery; stop the owner and provide the required authorization explicitly.

BackendCreateUse it forClose
SQLitecreateSqliteTaskQueue(path)Processes on one machine sharing a file.queue.close()
HTTPcreateHttpTaskQueue({ url, token })Clients of a queue served by serveTaskQueue.Nothing to close
Redis/BullMQcreateBullMQTaskQueue() from @elie-laloum/outpost/queues/bullmqWorkers spread across machines.await queue.close()

The BullMQ backend has its own setup: see Redis and BullMQ.

Workers also execute configuration-3 file recipes through the same recipe runtime. Each owned job gets a distinct materialization; shared publication destinations still coordinate through host-wide locks. See independent file jobs.

  • Inputs and values are JSON, up to 256 KiB each. IDs and handler names are at most 512 characters, a runId at most 256.
  • A worker registers at most 100 handlers.
  • A failed job keeps its result. A retried or resumed defineQueuedTask() finds the same failed job, so retry inside the handler.
  • One job at a time per runId: a second job for a run still in progress fails.
  • The queue fences stale writes but does not make external effects exactly-once.
  • An HTTP token grants every queue operation. Serve it behind TLS on a private network, and keep tokens out of URLs and logs.

API: runQueueWorker · createSqliteTaskQueue · TaskQueue · QueueHandler · QueueHandlerContext · defineQueuedTask · defineWorkflowJob · serveTaskQueue · createHttpTaskQueue.