Keel by ChimpLabs
Jump to page or section Esc
Primitives

JobQueue

Typed background job queues with delayed scheduling, visibility timeouts, retries, push and poll workers, and dead-letter queues.

JobQueue dispatches asynchronous work, such as sending emails, generating PDFs, resizing images, or calling slow webhooks, to background workers. It supports visibility timeouts, retry limits, delayed jobs, and dead-letter queues (DLQ).

Use JobQueue for competing-consumer work items where a single worker processes each job. For fan-out domain events consumed by multiple views or policies, see Topic.


Declaring a JobQueue

Plain TypeScript SDK (@chimp-labs/keel/sdk)

import { k } from "@chimp-labs/keel/sdk"

export const WelcomeEmailQueue = k.queue(
  "emails.welcome",
  k.object({
    to: k.string(),
    userId: k.string(),
  }),
  {
    maxAttempts: 3,
    visibilityTimeout: "30 seconds",
    dlq: true,
  }
)

Configuration options

Option Type Default Description
maxAttempts number 3 Maximum delivery attempts before failing a job or moving it to the DLQ.
visibilityTimeout Duration.Input "30 seconds" Lease window while a worker processes a job before it becomes visible again.
dlq boolean true Routes exhausted jobs to the dead-letter queue, which you inspect with deadLetters().

Effect v4 (@chimp-labs/keel/queue)

import { Schema } from "effect"
import { JobQueue } from "@chimp-labs/keel/queue"

const MailPayload = Schema.Struct({
  to: Schema.String,
  userId: Schema.String,
})

export class MailQueue extends JobQueue("emails.welcome", MailPayload, {
  maxAttempts: 3,
  visibilityTimeout: "30 seconds",
  dlq: true,
}) {}

Attaching to a Service

export const NotificationsService = k.service("notifications", {
  resources: [WelcomeEmailQueue],
  operations: { /* ... */ },
})

Operations reference

Enqueueing immediate and delayed jobs

// Enqueue for immediate processing
await keel.welcomeEmails.enqueue({
  to: "[email protected]",
  userId: "usr_1",
})

// Schedule a job to run after a delay (requires DelayedQueue)
await keel.welcomeEmails.enqueueDelayed(
  { to: "[email protected]", userId: "usr_1" },
  "15 minutes"
)

Running background workers

startWorker spawns a supervised worker daemon with configurable concurrency and error reporting. It supports "poll" mode and "push" mode, which wakes up on PostgreSQL 17 LISTEN/NOTIFY, SurrealDB 4 LIVE SELECT, or Memory notifications:

await using worker = await keel.welcomeEmails.startWorker(
  async (job) => {
    await sendEmail(job.payload.to, job.payload.userId)
    // Automatically acked on return; throwing triggers retry (or DLQ after maxAttempts)
  },
  {
    mode: "push",
    concurrency: 4,
    onError: (report) => console.error("Job failed:", report.tag, report.message),
  }
)

Manual polling, single-job processing, and dead letters

// Process one job directly (ideal for deterministic unit tests)
await keel.welcomeEmails.processOne(async (job) => {
  await sendEmail(job.payload.to, job.payload.userId)
})

// Low-level manual poll with explicit ack / nack
const job = await keel.welcomeEmails.poll()
if (job) {
  try {
    await sendEmail(job.payload.to, job.payload.userId)
    await job.ack()
  } catch (err) {
    await job.nack(String(err))
  }
}

// Inspect jobs that exhausted maxAttempts
const failed = await keel.welcomeEmails.deadLetters()

Complete SDK and Effect API mapping

SDK method (keel.<queue>.*) Effect function (@chimp-labs/keel/queue) Description
enqueue(payload) enqueue(queue, payload) Validate and push a job for immediate execution.
enqueueDelayed(payload, delay) enqueueDelayed(queue, payload, delay) Schedule a job to run after delay (requires DelayedQueue).
poll() pollJob(queue) Claim one available job and return SdkJobMessage | undefined.
processOne(handler) processOne(queue, handler) Claim, run, and acknowledge or reject a single job.
startWorker(handler, opts?) startWorker(queue, handler, opts?) Start a scoped push or poll worker with concurrency and supervision.
deadLetters() deadLetters(queue) List jobs routed to the dead-letter queue.

Errors and failure modes

Error tag Category HTTP status Retryable When it occurs
QueueError internal 500 Yes Queue storage, claim, or ack/nack operation fails.
SchemaError invalid 400 No Enqueued or dequeued job payload fails schema validation.

Backends and infrastructure

  • Memory runs an in-process FIFO queue with Clock-aware delays, visibility timeouts, retries, push notifications, and a DLQ.
  • PostgreSQL 17 (KeelPostgresLive, QueuePostgresLive, or backend: "postgres") uses a keel_jobs table with FOR UPDATE SKIP LOCKED job claiming, delayed scheduling, visibility timeouts, retries, a DLQ, and LISTEN/NOTIFY push workers.
  • SQLite and SurrealDB 4 use a durable queue table with lease tracking, retries, and a DLQ. SurrealDB 4 adds LIVE SELECT push wake-ups.

Testing in memory

await using keel = await createKeel({
  backend: "memory",
  resources: { welcomeEmails: WelcomeEmailQueue },
})

await keel.welcomeEmails.enqueue({ to: "[email protected]", userId: "u2" })

const sent: string[] = []
await keel.welcomeEmails.processOne(async (job) => {
  sent.push(job.payload.to)
})
// sent === ["[email protected]"]