Skip to content

Jobs

A job is work the app does after a request, or that a request should not wait for: mail an invoice, push a change to another system, recompute a report. Jobs live in the app’s own Postgres database, in a schema named jobs, so a job can commit in the same transaction as the write that asks for it. The queue underneath is pg-boss, pinned to one version; Protobase’s own API in front of it is what the app uses.

A job is declared in protobase.config.ts, by its name, under jobs: what it does, its arguments and when it runs. What it does is the default export of jobs/<name>.ts, which Protobase finds by that path and loads the first time the job runs.

protobase.config.ts
import { defineConfig } from '@protobase/config'
export default defineConfig({
// Each job's run is jobs/<name>.ts; the worker in `protobase dev` and `protobase serve` runs them.
jobs: {
'send-invoice': {
description: 'Renders an invoice as a PDF and mails it to the customer.',
arguments: { invoiceId: 'integer' },
maxAttempts: 10, // then kept as failed, with its last error
retryDelay: '30 seconds', // doubling with each retry, up to maxRetryDelay
},
'sync-customer': {
description: 'Pushes the changed fields of a customer to the CRM.',
arguments: { customerId: 'integer', fields: 'json' },
ordered: true, // one at a time per customer, in the order the changes were made
},
'remind-overdue': {
description: 'Mails a reminder for every invoice past its due date.',
schedule: '0 7 * * *', // every morning at 7: one run per time, however many workers run
timezone: 'Europe/Amsterdam',
},
},
// hooks/queue-sent-invoice.ts
writeHooks: ['queue-sent-invoice'],
})
jobs/send-invoice.ts
import { FatalJobError, type JobPayload, type JobRun } from '@protobase/server'
import type config from '../protobase.config'
export default (async ({ invoiceId }, { db }) => {
const invoice = await db.selectFrom('sales.invoices').select(['id', 'status']).where('id', '=', invoiceId).executeTakeFirst()
// Retrying will not bring it back: fail for good.
if (!invoice) throw new FatalJobError(`Invoice ${invoiceId} is gone`)
// ... render the PDF and mail it
}) satisfies JobRun<JobPayload<typeof config, 'send-invoice'>>
Key of a job
its name Letters, digits, _, -, . and /; the file jobs/<name>.ts holds what it does.
description What the job does, for the people who read the config.
arguments Its arguments by name, each a field type such as 'integer' or 'bigint', or the type with options: { type: 'enum', values: ['day', 'week'] }, { type: 'text', min: 1 }, { type: 'integer', optional: true }, { type: 'decimal', precision: 8, scale: 2 }. Each value is checked as a field of that type checks it, when the job is enqueued and again before it runs, and no other argument is taken. A payload refused at run time fails the job for good. The same is JSON in a protobase.config.json.
the default export of jobs/<name>.ts (payload, { db, job, signal, decryptField, mail, sendNotification }), typed with JobRun<Payload> from @protobase/server, its payload JobPayload<typeof config, '<name>'> (see Typed names and payloads): the work. db is the app’s pool: the enqueuer’s transaction has committed by then. db works in the organization of the db the job was enqueued with, such as a function’s in a request, and sees only that organization’s rows of the organization’s tables; a job enqueued with db.unscoped(...), a plain database or from SQL, and a recurring job, works in none, so db reads no row of those tables and writes none, unless db.unscoped('<reason>'). The payload never sets the organization. job holds its id, name, attempt, maxAttempts and startedOn, when this try took it. signal aborts when the try times out or the worker shuts down. decryptField(resource, key, field) reads an encrypted field’s value, audited, see Reading in jobs and functions. mail sends mail, see Mail. sendNotification sends a notification, see Sending; inside a transaction of db, a try that throws in it queues nothing. It is undefined in an app without notifications.
maxAttempts Tries before the job is kept as failed; default 10.
retryDelay, maxRetryDelay The wait before the first retry, doubling with each one (with some jitter), and its ceiling; default 2s and 1 hour. Milliseconds or text such as 30 seconds.
timeout How long one try may run before it counts as failed; default 15 minutes.
concurrency Jobs of this name running at once in each worker process; default 1.
longQueries Its queries through db may run up to 30 seconds instead of the database’s own limit, for imports, backfills and large deletes; see Long queries. A query stopped at its limit fails the try with an error that names the job.
ordered Jobs run one at a time per group, in the order they were enqueued; see Ordered groups.
schedule, timezone Runs the job on a cron schedule, in a time zone (default the config’s timezone, else UTC); see Recurring jobs.

A job runs at least once: a worker that dies mid-job, or a try cut off by a shutdown, means it runs again. Write the job so that running twice does no harm, for example by checking the state it is about to change.

import { enqueueJob } from '@protobase/server'
await enqueueJob(db, 'send-invoice', { invoiceId: 7 }, { delay: '5 minutes', key: 'invoice:7', priority: 10 })

db is the app’s database, or the transaction of a write hook or an API function: there, the job commits with the caller’s writes, or not at all. It returns the job’s id. A write hook is named in the config’s writeHooks and is the default export of hooks/<name>.ts:

hooks/queue-sent-invoice.ts
import { enqueueJob, type EnqueueJob, type PipelineHook } from '@protobase/server'
import type config from '../protobase.config'
// enqueueJob, typed with the config's jobs: a name it does not declare, or a payload that does not fit, fails to compile.
const enqueue: EnqueueJob<typeof config> = enqueueJob
// In the write's own transaction: the invoice and its job commit together or not at all.
export default (async (event, trx) => {
if (event.resource.name !== 'invoices' || event.after?.status !== 'sent' || event.before?.status === 'sent') return
const invoiceId = Number(event.after.id)
await enqueue(trx, 'send-invoice', { invoiceId }, { key: `invoice:${invoiceId}` })
}) satisfies PipelineHook

enqueueJob takes any name and payload, and checks them when it runs. EnqueueJob<typeof config> of @protobase/server, with config the default export of protobase.config.ts imported as a type, checks them as the code compiles, as the hook above does: a name the config does not declare, a required argument left out, one it does not take, or a value of the wrong type is an error. The payload follows each argument’s type: a number for integer, a boolean for boolean, any JSON value for json, one of an enum’s values, and a string for the others, bigint and decimal too, which JSON numbers cannot hold exactly. JobPayload<typeof config, '<name>'> is the same payload, for the job’s JobRun. A job without arguments takes any payload. A protobase.config.json gives the names only, since JSON keeps no argument’s type.

Option
runAt or delay When the job may run first: a Date, or milliseconds or text from now. Default now.
priority Higher runs first; default 0.
key and mode One waiting job per key: with mode: 'dedupe' (the default) an enqueue while one waits returns that one’s id and leaves it as it is; with mode: 'replace' the waiting job takes this payload and these options. A job that is running does not count, so a change made while it runs gets a job of its own.
group The group of an ordered job: required there, refused elsewhere.

A job this process enqueues starts at once when this process runs its jobs, and one enqueued in a transaction starts once that transaction commits, never when it rolls back; a wake starts up to the job’s concurrency of its due jobs. A job enqueued by another process, or from SQL, is picked up within the poll interval, 2 seconds, and so is one enqueued in a transaction of a Kysely instance the app built itself rather than its db.

Each worker takes one job per poll, so a queue that fills faster drains one job per worker every 2 seconds at first. Once the queue maintenance, about every minute, counts more jobs ready than the job’s concurrency, a worker that found a job fetches the next one at once, until a fetch finds none: a backlog then drains as fast as its jobs run.

A trigger or a migration can enqueue in its own transaction:

select jobs.enqueue('send-invoice', '{"invoiceId": 7}');
select jobs.enqueue('send-invoice', '{"invoiceId": 7}', run_at => now() + interval '1 hour', key => 'invoice:7');
select jobs.enqueue('sync-customer', '{"customerId": 3, "fields": ["email"]}', group_key => 'customer:3');

jobs.enqueue(job_name, payload, run_at, key, group_key, priority) returns the job’s id. The job works in no organization, whatever its payload holds: the runtime keeps a job’s organization under a top-level ~organization key beside the payload, and a payload with a ~organization key of its own reaches the job whole, as payload. A key dedupes as mode: 'dedupe' does. The job takes its retry settings from its definition, as the workers last saw it; a job no worker has started yet gets pg-boss’s defaults until one does.

mail.send({ to, subject, text, html }) sends one message, with an optional HTML part beside the plain text, through the app’s mail, the one that also sends password resets and sign-in codes: the mailer of auth/mailer.ts when the app has one, else the SMTP server of PROTOBASE_SMTP_URL and PROTOBASE_MAIL_FROM (see Email). An email template sends through it with template.send(to, data, mail). It rejects when the server refuses the message, so the try fails and is retried. Without either, mail is undefined: a job that must send fails for good with FatalJobError, and one that may skip mail leaves it out.

jobs/send-invoice.ts
export default (async ({ invoiceId }, { mail }) => {
if (!mail) throw new FatalJobError('Mail is off: set PROTOBASE_SMTP_URL and PROTOBASE_MAIL_FROM')
await mail.send({ to: '[email protected]', subject: `Invoice ${invoiceId}`, text: 'Your invoice is attached in the portal.' })
}) satisfies JobRun<JobPayload<typeof config, 'send-invoice'>>

A message is sent once per try, so a try that sends and then fails sends again: record what was sent in the same run, and check it first.

A try that throws is retried after its backoff, until maxAttempts. Then the job is kept as failed with its last error, for 7 days. throw new FatalJobError('410 Gone') fails it at once, without the attempts it has left.

A job that has waited 14 days past its start time without running is deleted.

While the database is read-only, as during a deploy’s write freeze, a write in the job fails with SQLSTATE 25006: the try waits 5 seconds and runs the job again, without using an attempt, until the database takes writes or the try times out.

With ordered: true, every enqueue names a group, and the jobs of one group run one at a time, in the order they were enqueued; different groups run side by side, up to concurrency. A job that is waiting for a retry, or has failed, holds back the rest of its group until it succeeds or is retried or deleted: that is what keeps the order. An ordered job takes no key: its group is how pg-boss finds its jobs.

Turning ordered on or off for a job whose queue exists stops startup: let its jobs finish or delete them, then drop the queue with select jobs.delete_queue('<name>').

schedule: '0 7 * * *' runs a job on that cron schedule, with no payload; a seconds field may come first (*/30 * * * * *). timezone reads it in a zone such as Europe/Amsterdam, so 07:00 stays 07:00 across daylight saving time.

Each run is a job of its own, enqueued ahead for its time by the workers: its id is made from the job’s name and the time, so however many workers enqueue a run, it is one job and runs once. As a run starts, the next one is enqueued. A run that came due while no worker ran, as when the app slept or was deployed, runs once as soon as one does; the times missed after it are skipped. Changing the schedule drops the waiting run that is no longer one of its times, and a job that loses its schedule, or is removed, loses its waiting run.

While several versions of an app serve one database, as in a rolling deploy, the schedule of the newest version holds: the version of a bundle is when protobase build built it, and the version of an app without a bundle, such as protobase dev, is the time it takes its jobs, at start and at each reload. Each version stores its schedules in the database unless a newer version stored them, and leaves the schedules and runs of jobs a newer version has alone. A run checks the stored schedule as it starts: it runs only at one of that schedule’s times, and a run left from an older schedule completes without running. Either way it enqueues the next run of the stored schedule, so each time runs once, whichever version takes it. A failed run’s retry is not checked again and runs at its retry time. A job only an older version still has stops once the newest version starts without it, and an older version that starts again later does not bring it back. A version without any jobs ends the recurring jobs of older versions. A process that runs no jobs, with PROTOBASE_JOBS=false, stores and ends no schedules, so it can serve with a role that changes nothing: the processes that run the jobs do it.

The schedules follow the newest build that has served, so roll back with a fresh build of the older code. Redeploying an older bundle as it was built cannot bring back its own schedules because storing the schedules when a deploy migrates the database is not implemented; until a newer build serves, it runs on the schedules of the newest one.

Because the next run waits in the database like any delayed job, jobs.next_due() sees it, and a host that wakes the app for due jobs wakes it for its recurring jobs too. That is why Protobase does not use pg-boss’s own scheduler, which keeps no next run in the database and works the time out in a running process.

isSchedule(schedule, timezone) from @protobase/server tells whether a recurring job takes a schedule in a time zone, for a tool that writes the config, such as an import.

With jobs, the admin app has a Failed jobs page, for admins only: each job that used up its attempts or failed for good, with its payload and last error. Retry gives a job one more attempt, from now, and Delete removes it. It reads the jobs.failed view, which a project’s SQL can query too.

  • protobase dev runs them in its process. An edited job runs its new code from the next job on. protobase dev --no-jobs runs none, for a dev server on a hosted app’s database.
  • protobase serve runs them in its process, beside the API, unless PROTOBASE_JOBS=false; it enqueues them either way. On SIGTERM it stops taking jobs and gives running ones 30 seconds to finish. A job still running then is failed, to be retried.
  • protobase worker <bundle> runs the same jobs from the same bundle in a process of its own, with the same shutdown, for a serve with PROTOBASE_JOBS=false.
  • Each worker checks every job name for due jobs every 2 seconds: one indexed query per job name and interval. Once a minute, one of the workers also counts the queues and retries the jobs whose worker died (their timeout passed); once a day it deletes completed and failed jobs older than 7 days.

A host that stops an idle app needs to know when a job is due, and to have it run:

  • select jobs.next_due() answers when the next job is due, or null when none waits: a waiting job’s start time, a recurring job’s next run, or the timeout of a job that was running when the app stopped. It is one read-only statement, through any pooler.
  • POST /api/jobs/drain?seconds=25 runs the due jobs until none is due or running, or the seconds have passed, and answers { "drained": true, "remaining": 0, "nextDue": "2026-10-12T05:00:00.000Z" }. It takes the operator’s token, PROTOBASE_JOBS_DRAIN_TOKEN, as a bearer token; without that variable there is no such endpoint. A process with PROTOBASE_JOBS=false answers 409.

The schema is pg-boss’s tables at its pinned schema version, plus Protobase’s jobs.enqueue, jobs.next_due and jobs.failed. It is a module with numbered steps, like the auth schema, created and upgraded by the project’s migrations:

Terminal window
bun run protobase migration # writes db/migrations/NNN_jobs.sql when the snapshot lacks the jobs schema's steps
bun run db:migrate

Step 1 is pg-boss’s own construction plan for schema version 45, copied into Protobase without its BEGIN and COMMIT and with any CONCURRENTLY index build made a plain one, so the file runs in the project’s migration transaction; pg-boss stays pinned to an exact version, and a newer pg-boss comes with a step of its own holding its migration plan. Protobase’s functions are written whole at their version after the steps, and again when a newer Protobase changes them. protobase migration writes both from protobase.snapshot.json alone, which records the step and the functions’ version. The server never creates or migrates it: protobase dev, protobase serve and protobase worker read the record of migrations at startup and refuse to start while it lacks the jobs schema or has it at an older step or functions version, naming what is missing. A jobs schema an earlier version’s protobase migration wrote, before the snapshot recorded it, is described once with protobase migration baseline.

pg-boss runs here without what needs a session of its own: no LISTEN/NOTIFY (a job enqueued in the same process wakes its worker directly, the rest is polled), only transaction-scoped advisory locks, unnamed prepared statements, no index rebuilds and no instance registry. It works through PgBouncer in transaction mode, over the app’s own connection pool.