GuidesBackground jobsMenu

Background jobs

Put work on the Postgres queue, write its handler, drain it from a scheduled route, and retry what failed, with no Redis and no worker to host.

At the end of this page a job enqueued by a Server Action runs on a schedule, retries when its handler throws, and shows up in the admin console when it runs out of attempts.

The queue is one table, jobs, in the framework’s schema. intelligo migrate creates it. There is no worker process: a route of yours drains the queue when a scheduler calls it.

Enqueue

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

await enqueue({
  kind: "digest.send",
  workspaceId,
  payload: { userId },
});

kind names the handler. workspaceId is the workspace the work belongs to, or null for work no workspace owns. Two more fields are optional: runAt (not before this time) and maxAttempts (3 by default).

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

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

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:

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

Write the handlers

Terminal
pnpm exec intelligo add jobs

That writes the drain route and an empty lib/job-handlers.ts, and records both in intelligo.manifest.json. Handlers are a map from kind to a function, kept in that one file so the drain route and your tests import the same map.

lib/job-handlers.ts
import type { JobHandler } from "@intelligo-dev/jobs";

export const handlers: Record<string, JobHandler> = {
  "digest.send": async (job) => {
    await sendDigest(job.workspaceId, job.payload);
  },
  "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);
    }
  },
};

A handler runs once per attempt, so write it to be safe to run again. One that throws puts the job back, one more minute later per attempt. After maxAttempts the job is failed and keeps its last error. The signal aborts once the job has run for thirty minutes, the point at which another worker may claim it.

The job carries the workspaceId it was enqueued with. Scope every query in the handler by it, as you would in a route.

Drain on a schedule

The route intelligo add jobs wrote is yours from then on:

app/api/cron/jobs/route.ts
export const GET = withCronSecret(async () => {
  composeIntelligo();
  const result = await drain(handlers, {
    untilEmpty: true,
    deadlineMs: DEADLINE_MS,
  });
  if (result.failed > 0 || result.unhandled.length > 0) {
    log.warn("The drain left jobs unfinished", { ...result });
  }
  return Response.json(result);
});

deadlineMs stops the drain claiming new jobs in time for the route’s own limit, so no job spends an attempt it had no time for. Schedule the route beside maintenance, with the same CRON_SECRET. On Vercel, add jobs writes the every-minute entry to vercel.json when the app has none, and tells you the line to add when it has one; on another host, a scheduler of your own calls the route with Authorization: Bearer $CRON_SECRET.

In development, call it by hand:

Terminal
curl -H "Authorization: Bearer $CRON_SECRET" localhost:3000/api/cron/jobs

The maintenance route prunes finished jobs but does not drain the queue, because only your app has the handlers.

Recurring work

A handler that enqueues its own next run is a schedule:

TypeScript
"digest.daily": async () => {
  await sendDailyDigests();
  await enqueue({
    kind: "digest.daily",
    workspaceId: null,
    payload: {},
    runAt: new Date(Date.now() + 24 * 60 * 60_000),
  });
},

Work a person comes back to

Work someone starts from a page and returns to later (a report, an import, a file being read) needs three things the queue keeps for you: who asked, where it is, and what it made.

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

The handler reports where it is, and what it returns is the job’s result:

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

"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) };
},

The page reads them back, inside the workspace and for the person who asked:

TypeScript
import { getJob, listJobs } from "@intelligo-dev/jobs";

const work = await listJobs({ workspaceId, userId, kinds: ["report.build"] });
const one = await getJob(id, { workspaceId, userId });

Each job is pending, running, succeeded or failed, with its progress and result in the shape you wrote them. Return the id of what the handler made and keep the thing itself in a table of yours: finished jobs are pruned after a week, so the list is recent work. lastError is written for an operator; show a person the status.

A handler that calls a model

Each attempt that calls a model is its own execution. Wrap the call with runWithExecution and let it mint the request id:

TypeScript
import { runWithExecution } from "@intelligo-dev/executions/runner";

"report.write": async (job) => {
  if (!job.workspaceId) return;
  const result = await runWithExecution(
    { executions, workspaceId: job.workspaceId, capability: "report.write", model },
    () => generateText({ model: provider(model), prompt })
  );
  await saveReport(job.id, result.text);
},

Do not derive the request id from the job’s id: the second attempt would be refused as request_id_taken, because the first attempt’s execution exists. 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.

Work the deployment gives away takes billTo: "platform" in the same options: the workspace’s balance is neither checked nor charged, and the run still counts against a spend cap.

A signup bootstrap that is retried

What a new workspace starts with (trial credits, a welcome note) runs once, in the background, when the workspace is created: onWorkspaceCreated in lib/workspace-bootstrap.ts. A failure there is logged and never run again, so a billing outage during a signup leaves that workspace without its trial. Put it on the queue and it is retried:

lib/job-handlers.ts
import { runWorkspaceCreated } from "@intelligo-dev/auth";
import type { JobHandler } from "@intelligo-dev/jobs";

export const WORKSPACE_BOOTSTRAP = "workspace.bootstrap";

export const handlers: Record<string, JobHandler> = {
  [WORKSPACE_BOOTSTRAP]: (job) => runWorkspaceCreated(job.payload),
};
lib/intelligo.ts
import { setWorkspaceCreatedDelivery } from "@intelligo-dev/auth";
import { drain, enqueue } from "@intelligo-dev/jobs";

import { WORKSPACE_BOOTSTRAP, handlers } from "@/lib/job-handlers";

setWorkspaceCreatedDelivery(async (created) => {
  await enqueue({
    kind: WORKSPACE_BOOTSTRAP,
    workspaceId: created.workspaceId,
    payload: created,
    dedupeKey: created.workspaceId,
  });
  // The first attempt now, not at the next scheduled drain.
  await drain(handlers, { kinds: [WORKSPACE_BOOTSTRAP], limit: 1 });
});

The first attempt still runs at signup, so a new user finds their trial when the dashboard opens; one that fails waits for the scheduled drain. Because it can run twice for one workspace, the handler has to be safe to repeat: provisionTrialCredits is, and a grant of your own should carry a key the second run finds. If the queue itself cannot take the job, the handler runs once as it would without a delivery.

When a job fails

listFailedJobs() reads the jobs that ran out of attempts, newest first, and the admin console’s operations page lists them with a retry button. retryJob(id) puts one back in the queue, due now with its attempts returned, and retryFailedJobs({ kind }) does it for every failed job of a kind.

The package page lists every option of drain and what the queue guarantees.