Background jobs and cron
One table, one loop, one deployable process
Everything in the background is a row in one table. A job is a type, a payload,
a time to run, and an attempt count. A cron is a job that gets created on a
schedule. One loop — tick() — moves rows forward.
import * as v from 'valibot'
const backend = bunderstack({
schema,
jobs: (j) =>
j.define({
sendEmail: j.job({
input: v.object({ userId: v.string() }),
retries: 3,
handler: async ({ userId }, ctx) => {
// ctx.db, ctx.messaging, ctx.storage, ctx.jobs, ctx.realtime, ctx.env
},
}),
dailyReport: j.cron({
schedule: '0 9 * * 1-5',
retries: 2,
handler: async ({ scheduledFor }, ctx) => {},
}),
}),
})
const app = await backend.start()
await app.jobs.enqueue('sendEmail', { userId: 'usr_123' })j.job() is durable queue work and is the only declaration accepted by
app.jobs.enqueue(). Delivery is at-least-once: make handlers idempotent.
Production worker
The default all role keeps local development and small single-process
deployments simple. In production, run queue work as a separate process and
keep the web runtime from auto-starting another loop:
// src/worker.ts
import { backend } from './bunderstack/backend'
const app = await backend.start({
env: { ...process.env, BUNDERSTACK_ROLE: 'web' },
})
await app.runWorker()Topology is controlled by BUNDERSTACK_ROLE, not by application code:
BUNDERSTACK_ROLE | Serves HTTP | Runs background work |
|---|---|---|
all (default) | yes | yes |
web | yes | no |
worker | no | yes |
Use BUNDERSTACK_ROLE=web for the web entry. The dedicated worker command owns
runWorker() and its shutdown lifecycle.
# One process, everything. The default.
bun run start
# Split production commands.
BUNDERSTACK_ROLE=web bun run start
bun run workerapp.backgroundRunning reports whether the current process runs the loop.
app.startWorker() is useful for an explicitly embedded worker;
app.runWorker() owns a dedicated worker process until shutdown.
Concurrency
Queue jobs run in a continuous per-type pool. With one worker, omitted
concurrency gives that type 10 execution slots.
generateAnswer: j.job({
concurrency: 32,
timeout: 120_000,
handler: async (input, ctx) => {},
})The worker claims rows in internal batches of at most 10 until all 32 slots are full. Ten is a database batch size, not a concurrency ceiling. When one handler finishes, the worker fills that slot immediately without waiting for the other handlers that started beside it.
Across several worker processes, the current database-observed capacity check
is best effort and can race; concurrency is not a strict provider-wide
semaphore. Use an application/provider limiter when several workers share one
external quota.
Deduplication
A dedupeKey collapses enqueues of the same job type into one row. The second
call returns the existing row's id instead of inserting another:
await app.jobs.enqueue('syncPerson', { personId }, { dedupeKey: personId })dedupeUntil on the job declaration decides how long the key collapses new
enqueues:
'finish'(default) — the key is held until the job succeeds or finally fails. An enqueue while the job runs returns the running row. Right for "at most one of these at a time" work.'start'— the key is released when a worker claims the job. A burst of enqueues before the claim still collapses into one row, but an enqueue during the run creates one more row that runs after it and reads the newer state. Right for debounced sync, reindexing, and cache rebuilds.
syncPerson: j.job({
input: v.object({ personId: v.string() }),
dedupeUntil: 'start',
retries: 5,
handler: async ({ personId }, ctx) => {
// Read the latest state, then push it.
},
})With 'start', a job that fails and waits for a retry no longer holds its key,
so a newer row can exist beside it and both run. 'start' also does not
serialize runs per key: two workers can run an older and a newer row at the
same time. Keep the default, or take a lock in the handler, when runs for one
key must never overlap.
Cron tasks reject dedupeUntil; a schedule owns one row, and that row's key
is what keeps every worker on it.
Transactional enqueue
Pass tx to insert the job row through your own Drizzle transaction. The job
becomes visible to workers only when the transaction commits, and a rollback
removes it. Your data and the work that follows from it are written atomically,
so you do not need an outbox table:
await context.db.transaction(async (tx) => {
const person = await mergePerson(tx, event)
await context.jobs.enqueue(
'syncPerson',
{ personId: person.id },
{ tx, dedupeKey: `sync:${person.id}` },
)
})tx works on app.jobs, on context.jobs in procedures, on ctx.jobs in job
handlers, and on fixture.app.jobs in tests. It must be a transaction on the
app's own database. A transaction of the other dialect throws; a transaction
from an unrelated connection of the same dialect is not supported.
- Postgres: an enqueue whose
dedupeKeyconflicts with a row that another open transaction inserted waits for that transaction to end. Two transactions that enqueue the same key therefore run one after the other. Keep such transactions short. - SQLite and libSQL: a write transaction already holds the database write
lock, so
txadds no contention.
Delivery stays at-least-once. tx removes lost jobs (a crash between commit and
enqueue) and phantom jobs (an enqueue whose transaction rolled back). It does
not make handlers exactly-once.
Cron
j.cron() uses a five-field UTC schedule. Each schedule owns one job row,
whose runAt is the slot it last ran or is running for. A due minute moves
that row onto the new slot with one insert-or-update, so a slot runs exactly
once no matter how many processes are ticking — including the brief overlap
during a rolling deploy — and the table never grows with occurrences. Slots
run one at a time per schedule: a missed slot under catchUp: 'all' is taken
once the current one has finished.
Because cron occurrences are jobs, they take the same options queue jobs do:
weeklyDigest: j.cron({
schedule: '0 9 * * 1',
retries: 3, // a throwing handler now retries with backoff
timeout: 120_000, // lease duration
catchUp: 'latest', // or 'all'
onFailed: async (invocation, error, ctx) => {},
handler: async ({ scheduledFor }, ctx) => {},
})Missed slots
If the process was down when a slot came due, catchUp decides what happens on
the next tick:
'latest'(default) — only the most recent missed slot runs. Right for handlers that bring state up to date.'all'— every missed slot runs, bounded bycatchUpWindow(default one hour). Right when each interval represents distinct work.
A newly declared cron never backfills from the past — it starts from the minute it is first seen.
Job names may not begin with cron:; the prefix is reserved.
Testing jobs deterministically
Fixtures never auto-start background work. fixture.jobs.runNext() claims and runs one tick, while fixture.jobs.runUntilIdle() runs ticks until all runnable jobs are processed:
await using fixture = await backend.test()
await fixture.app.jobs.enqueue('sendWelcomeEmail', { userId: 'user_1' })
const report = await fixture.jobs.runUntilIdle({ failOnJobError: true })
expect(report.ran).toBe(1)
expect(await fixture.jobs.pending({ name: 'sendWelcomeEmail' })).toEqual([])
expect(await fixture.jobs.failed()).toEqual([])Jobs recursively enqueued by handlers are processed until the queue converges or maxTicks is reached. Delayed jobs wait for their explicit now timestamp without sleeping.
Use fixture.jobs.inspect(filter?) for every row still in the queue (a job
that succeeded has none), or
pending(filter?) and failed(filter?) for status-specific assertions. Filters
accept name and dedupeKey; rows expose id, normalized name, kind, status,
attempts, runAt, dedupeKey, and lastError.
Realtime from a separate worker process
With BUNDERSTACK_ROLE=all — the default — job handlers and realtime subscribers
share a process, so realtime works with no extra configuration.
When you split roles, the web and worker processes are separate. An in-memory
realtime broker cannot carry an event published by a job handler to clients
connected to the web process. If a handler calls ctx.realtime.publish(),
configure a shared Redis transport in both:
const backend = bunderstack({
schema,
realtime: (env) => ({ redis: env.REDIS_URL }),
jobs: (j) =>
j.define({
generateImage: j.job({
input: v.object({ itemId: v.string() }),
handler: async ({ itemId }, ctx) => {
const item = await generateAndSaveItem(itemId)
await ctx.realtime.publish(schema.items, 'update', item)
},
}),
}),
})
const app = await backend.start()REDIS_URL=redis://localhost:6379 BUNDERSTACK_ROLE=web bun run start
REDIS_URL=redis://localhost:6379 BUNDERSTACK_ROLE=worker bun run startSetting REDIS_URL is enough when realtime is enabled; the explicit
realtime.redis option is useful when the URL comes from another source.
realtime: true without Redis selects a process-local memory transport, which
is correct for BUNDERSTACK_ROLE=all.
app.runWorker() rejects the unsafe standalone memory-transport combination
rather than silently losing cross-process events. If handlers never publish
realtime events, say so explicitly:
await app.runWorker({ allowProcessLocalRealtime: true })Inspect the selected transport through app.realtime.transport
('disabled', 'memory', or 'redis'). The deploy manifest exposes the
configured value as app.manifest.realtimeTransport.
Standalone job handlers
When extracting handler logic into separate files, annotate ctx with
BunderstackJobContext:
// src/server/jobs/generate-resume.ts
import type { BunderstackJobContext } from 'bunderstack'
export async function generateResume(
adaptationId: string,
ctx: BunderstackJobContext,
) {
const url = await ctx.storage.getUrl(`adaptations/${adaptationId}/resume.pdf`)
await ctx.messaging.email.send({ ... })
}Retries and failures
A handler that throws is retried with jittered exponential backoff until
retries is exhausted, then the row is marked failed with its error and
onFailed fires once. Failed rows stay queryable in _bunderstack_jobs for
30 days after they finish and keep the job's full input until then, so pass IDs
rather than secrets.
A job that succeeds leaves no row: the table holds work still to do, not
history. What remains of a finished attempt is the structured
job.completed / job.retrying / job.failed log line and, when the app
reports to Bunderhost, a run record (type, outcome, attempt, duration, error;
never the payload) that its Background tab lists. Everything but failures
therefore costs the database one insert, one claim and one delete.
Long cron work should enqueue a queue job and return quickly rather than holding its lease for minutes.