Workers

Durable background job execution with retries and dead-letter queues.

Workers process jobs from durable queues. Jobs survive restarts and are retried on failure. Failed jobs can be routed to a dead-letter queue (DLQ).

Defining a Worker

import { worker } from "@chimpbase/runtime";

const syncCustomer = worker(
  "customer.sync",
  async (ctx, payload) => {
    ctx.log.info("syncing customer", { customerId: payload.customerId });
    await ctx.query(
      "update customers set synced_at = now() where id = ?1",
      [payload.customerId],
    );
  },
);

Enqueuing Jobs

Jobs are enqueued from actions, subscriptions, or other handlers:

await ctx.queue.enqueue("customer.sync", {
  customerId: customer.id,
});

Delayed Jobs

You can delay job execution:

await ctx.queue.enqueue("reminder.send", { userId: 123 }, {
  delayMs: 60_000, // 1 minute
});

Dead-Letter Queues

By default, failed jobs (after retries) are routed to a DLQ named <queue>.dlq. You can handle DLQ items with another worker:

worker("customer.sync.dlq", async (ctx, envelope) => {
  ctx.log.error("customer sync failed permanently", {
    queue: envelope.queue,
    attempts: envelope.attempts,
    error: envelope.error,
    payload: envelope.payload,
  });
});

To disable the DLQ for a specific worker:

worker("customer.sync.dlq", handler, { dlq: false });

Using Decorators

import { Worker } from "@chimpbase/runtime";

class SyncModule {
  @Worker("customer.sync")
  async syncCustomer(ctx, payload) {
    // ...
  }
}