PackagesjobsMenu

@intelligo-dev/jobs

A Postgres-backed job queue: enqueue, claim with SKIP LOCKED, retry with backoff and prune. No Redis.

Install

Terminal
pnpm add @intelligo-dev/jobs drizzle-orm

drizzle-orm is a peer. The queue is one table, jobs, in the framework’s schema: intelligo migrate from @intelligo-dev/cli creates it, and the connection is the DATABASE_URL that @intelligo-dev/core reads.

Use

Enqueue from anywhere that can reach the database:

TypeScript
import { enqueue } from "@intelligo-dev/jobs";

await enqueue({
  kind: "digest.send",
  workspaceId, // or null: a job no workspace owns (an anonymous request's work)
  payload: { userId },
  runAt: new Date(Date.now() + 60_000), // optional: not before
  maxAttempts: 5, // optional: 3 by default
});

Drain from a cron route, a long-running worker or a script — handlers are keyed by kind:

TypeScript
import { drain } from "@intelligo-dev/jobs";

const result = await drain(
  {
    "digest.send": async (job) => {
      await sendDigest(job.payload);
    },
  },
  { limit: 25, deadlineMs: 45_000 }
);
// { claimed, succeeded, failed, unhandled, deferred }

The options:

Option What it sets
limit The most jobs one drain claims. Default 10
deadlineMs Stop claiming this long after the drain began, so a run fits its route’s time limit
untilEmpty Keep claiming past limit until nothing is due. Bound it with deadlineMs
concurrency How many jobs run at once. Default 1; each is still claimed alone, as its worker becomes free
abandonedAfterMs How long a running job is left to its worker before another may claim it. Default thirty minutes; every worker draining one queue should agree on it
kinds Claim jobs of these kinds only: enqueue work and drain its kind to start it now, not at the next scheduled drain

A handler’s second argument is an AbortSignal that aborts once the job has run for abandonedAfterMs: from then on another worker may claim it, so a handler that can stop should.

TypeScript
"export.build": async (job, signal) => {
  for (const chunk of chunksOf(job.payload)) {
    if (signal.aborted) throw new Error("out of time; the next attempt resumes");
    await writeChunk(chunk);
  }
},

Drain on a schedule

The framework runs no worker. The maintenance route that intelligo add maintenance writes prunes the queue but does not drain it, because only the application has the handlers. Give the drain a route of its own, behind the same CRON_SECRET, and schedule it beside maintenance. intelligo add jobs writes this route and an empty lib/job-handlers.ts, and schedules it every minute in vercel.json when the app has none:

app/api/cron/jobs/route.ts
import { drain } from "@intelligo-dev/jobs";
import { withCronSecret } from "@intelligo-dev/next/route";

import { composeIntelligo } from "@/lib/intelligo";
import { handlers } from "@/lib/job-handlers";

export const maxDuration = 60;

export const GET = withCronSecret(async () => {
  composeIntelligo();
  return Response.json(
    await drain(handlers, { untilEmpty: true, deadlineMs: 45_000 })
  );
});

withCronSecret answers 401 to a caller without the bearer and 403 to everyone while CRON_SECRET is unset or shorter than 32 characters.

Recurring work is a handler that enqueues its own next run:

TypeScript
"digest.daily": async (job) => {
  // The next run first, so a failure below does not end the schedule.
  const next = new Date(Date.now() + 24 * 60 * 60_000);
  await enqueue({
    kind: "digest.daily",
    workspaceId: null,
    payload: {},
    runAt: next,
    // Keyed by the day it runs: a retry of this run, or a second seed,
    // finds that day's job waiting and adds none.
    dedupeKey: next.toISOString().slice(0, 10),
  });
  await sendDailyDigests();
},

The first run is one enqueue of the same kind with a key for its day, from a deploy step or a script. A run that fails all its attempts is marked failed and enqueues nothing more by itself, which is why the next run is added before the work.

In development, call the route by hand or in a loop: curl -H "Authorization: Bearer $CRON_SECRET" localhost:4002/api/cron/jobs.

Enqueue with your own write

A job that must exist exactly when a row of yours does is enqueued in the same transaction: kept if it commits, gone if it rolls back.

TypeScript
import { db } from "@intelligo-dev/core/db";
import { enqueue } from "@intelligo-dev/jobs";

await db.transaction(async (tx) => {
  await tx.insert(orders).values(order);
  await enqueue({ kind: "order.confirm", payload: { id: order.id } }, { tx });
});

One job for one thing

Work asked for from several places and wanted once takes a dedupeKey. While a job of that kind waits or runs under the key, enqueue adds nothing and returns that job’s id; once it has finished, the key is free.

TypeScript
await enqueue({
  kind: "workspace.sync",
  workspaceId,
  dedupeKey: workspaceId,
});

Retrying a failed job

retryJob(id) puts a failed job back in the queue, due now and with its attempts returned; retryFailedJobs({ kind }) does it for every failed job of a kind, or of all kinds, up to 500 a call, and returns how many. Neither retries a job whose dedupe key another job already holds. The admin console’s operations page has the button.

Work a person asked for and comes back to

A job someone started from a page takes their userId, so the page can show them their own:

TypeScript
const id = await enqueue({
  kind: "report.build",
  workspaceId,
  userId,
  payload: { reportId },
});

The handler says where it is with reportProgress, and what it returns is kept as the job’s result:

TypeScript
import { reportProgress, type JobHandler } from "@intelligo-dev/jobs";

export const handlers: Record<string, JobHandler> = {
  "report.build": async (job) => {
    const sections = await outline(job.payload);
    for (const [index, section] of sections.entries()) {
      await write(section);
      await reportProgress(job, { done: index + 1, of: sections.length });
    }
    return { documentId: await save(sections) };
  },
};

progress and result are the product’s own shape: the queue stores them and reads nothing from them. Keep result to the id of what was made; the thing itself belongs in a table of yours. reportProgress is false when this worker no longer holds the job, and a failed job that is retried starts with neither.

listJobs({ workspaceId, userId, kinds }) reads a workspace’s jobs, newest first and whatever their status, 50 a call; before takes the createdAt of the last one for the next page. getJob(id, { workspaceId, userId }) reads one, and is null for a job of another workspace or of another person. Leave userId out for work the whole workspace sees. Both are the read behind a “your work” page: a job is pending, running, succeeded or failed. lastError is the handler’s own message, written for an operator, so show a person the status and not the text. Finished jobs are pruned (a week, in the maintenance route), so the list is recent work, not an archive.

A handler that calls a model

A handler runs once per attempt, and each attempt that calls a model is its own execution: wrap the call with runWithExecution from @intelligo-dev/executions/runner and let it mint the request id. Do not derive the id from the job’s: the second attempt would be refused as request_id_taken, because the first attempt’s execution exists and is settled or waiting for reconcile. A handler that must not pay twice for one piece of work records its result under the job’s id and returns early when it finds one.

What the queue guarantees

  • No double-processing. Claiming is FOR UPDATE SKIP LOCKED, so several workers drain the same queue and each takes different rows. A worker writes to a job only while it still holds the claim, so a late outcome never overwrites a newer one.
  • One job held at a time. A drain claims a job only to run it at once, and the next only when that one has ended. A handler that takes the worker down with it, by a crash or a function killed at its time limit, strands that one job; the rest stay pending with no attempt spent.
  • A recorded outcome. A handler runs once per attempt: a failed status write is retried rather than counted as a handler failure, and one job’s failed write does not stop the rest of the batch.
  • Retry with backoff. A handler that throws puts the job back, one more minute later per attempt; after maxAttempts it is failed and keeps its last error. listFailedJobs() reads them, newest first.
  • A dead worker does not strand a job. One still running thirty minutes after its handler started is claimed again, so a handler must finish well inside that — until it has used its attempts: a handler that keeps killing its worker ends failed.
  • A drain fits its time limit. With deadlineMs, no job is claimed after that long, so none spends an attempt it had no time for. deferred in the result is always 0 and is kept for callers that read it.
  • An unknown kind costs nothing. A job with no handler in this worker goes back without spending an attempt, a minute behind the jobs the worker can run — another deployment may know it.

pruneJobs(before, { failedBefore }) deletes succeeded jobs finished before before and failed ones finished before failedBefore (the same cutoff when omitted), in bounded batches, and returns how many. postgresJobQueue is the same enqueue and drain as one JobQueue value; a different queue implements that type, and call sites stay as they are.

Entry points

  • @intelligo-dev/jobs
  • @intelligo-dev/jobs/db

npm · source