Skip to content

Building blocks

Background jobs

A background job is work that runs after the response, on a Cloudflare Queue, and gets retried when it fails. Use one when the work calls a slow or flaky service (mail, a payment provider, an AI model) and must not be lost while that service is down. Cron-driven work, the kit's cleanup and your own, lives in scheduled tasks further down this page.

How it works

  1. Each file in the kit's layers/kit/server/jobs/(Licensees only) and in your server/jobs/ is a job, and its file name is the job's kind. Yours wins a name both have. At build time layers/kit/modules/jobs-registry.ts(Licensees only) turns both directories into a dispatch table and a QueueJob type.
  2. enqueue(event, { kind, payload }) sends the job to the nuxter-jobs queue through the QUEUE binding.
  3. The same Worker consumes that queue. layers/kit/server/plugins/queue-consumer.ts(Licensees only) finds the handler by kind and runs it. A handler that returns is done. One that throws is retried with a growing delay.
  4. After the last retry, Cloudflare moves the message to nuxter-jobs-dlq. The Worker reports each message there as an error and deletes it without running it.

Add a job

Create server/jobs/crm-sync.ts and default-export defineJob:

import { defineJob } from '#layers/kit/server/utils/jobs'

export interface Payload {
  userId: number
}

export default defineJob<Payload>({
  async run({ userId }, event) {
    const [user] = await useDrizzle(event)
      .select({ email: tables.users.email })
      .from(tables.users)
      .where(eq(tables.users.id, userId))

    if (!user) return

    await $fetch('https://crm.example.com/contacts', {
      method: 'POST',
      body: { email: user.email },
    })
  },
})

Nothing else needs editing. The kind is crm-sync, and enqueue takes its payload type from the run parameter, so a wrong kind or payload shape fails type checking at the call site. File names must be lowercase kebab-case, or the build fails. The registry is generated when Nuxt starts, so restart pnpm dev after you add, rename or delete a job file.

The event passed to run holds the Cloudflare bindings and nothing else. useDrizzle(event), useRuntimeConfig(event), requireLinkBase(event) and event.context.cloudflare.env work, but there are no headers, cookies or session. requireLinkBase answers NUXT_SITE_URL, or http://localhost:3000 under pnpm dev without one, and throws a 500 elsewhere without one, so a job that mails a link builds it the way the invitation mail does. Copy what the job needs from the request into the payload.

Enqueue a job

enqueue lives in layers/kit/server/utils/queue.ts(Licensees only). It returns true when the queue accepts the job and false when the queue is off, the event has no QUEUE binding, or the send failed. It never throws, so the caller decides what false means:

import { enqueue } from '#layers/kit/server/utils/queue'

export default defineEventHandler(async (event) => {
  const session = await requireVerifiedSession(event)

  const queued = await enqueue(event, {
    kind: 'crm-sync',
    payload: { userId: session.user.id },
  })

  if (!queued) {
    throw createError({ statusCode: 503, statusMessage: 'Try again later.' })
  }

  return { queued }
})

The shipped listeners answer false by running the same work inline, as layers/kit/server/listeners/00-billing-email.ts(Licensees only) does. A listener's own work is never retried, so enqueue from it when the work has to survive a failure (Events).

Run jobs locally

pnpm dev has no queue consumer, so enqueue starts the handler in the same process without awaiting it, logs a [queue] warning naming the kind, and returns true. Two things differ from production: a throw is logged and dropped instead of retried, and the payload is passed as-is instead of going through the queue.

pnpm preview builds the Worker and runs it under wrangler dev with the real queue, retries and dead letter queue. It needs a real Postgres, not the PGlite that pnpm dev uses (Database).

Change the retry policy

The consumer waits one minute after the first failure and doubles the wait each time. With the shipped max_retries: 5, a job gets six attempts over about 31 minutes (waits of 1, 2, 4, 8 and 16 minutes) before it dead-letters.

Every job shares this policy. A job that shouldn't retry a failure catches it and returns, as layers/kit/server/jobs/email.ts(Licensees only) does when every provider refuses a message permanently.

A dead job goes to the error hook, which logs it and forwards it to your error trackers (Observability) tagged queue and dead-letter:

[queue] a "crm-sync" job died after 6 attempts: message <id> on "nuxter-jobs-dlq", dead letter delivery 1; acknowledged without running

The report leaves out the payload, and the message is deleted right after, so a dead job can't be replayed. A kind with no handler is retried like any failure, which carries a new job across a deploy while the old Worker is still consuming. Messages for a job file you deleted end up in the dead letter queue.

Turn the queue off

Set queue.enabled: false in starter.config.ts(Licensees only). enqueue then returns false everywhere and the shipped callers fall back: a mail every provider refuses returns a 502 instead of being retried later, and the billing-email sync, invitation mail and subscription cancel run inside their listeners. The build skips the queues checks and bundles no job handlers. QueueJob still lists every job, so your enqueue calls still type-check.

Wrangler still binds whatever the queues block in wrangler.jsonc lists, so either create the queues anyway or remove that block.

Shipped jobs

KindWhat it doesEnqueued by
emailResends a rendered mail after a transient failuredeliverEmail in layers/kit/server/email/index.ts(Licensees only)
billing-emailMoves the user's payment-provider customers to a new email00-billing-email.ts on auth:emailChanged
cancel-billingCancels provider subscriptions of a deleted account00-cancel-billing.ts on account:deletionScheduled, 00-cancel-stranded-billing.ts on account:subscriptionsStranded
org-invitation-emailSends an organization invitation00-org-invitation-mail.ts on org:invitation:created

These four live in layers/kit/server/jobs/. Your jobs go in server/jobs/<kind>.ts, and one under a kit job's name replaces it (Project structure).

Scheduled tasks

Scheduled tasks don't use the queue. They are Nitro tasks in the kit's layers/kit/server/tasks/(Licensees only) and in your server/tasks/, run by the crons in triggers.crons in wrangler.jsonc. The kit's own tasks run on schedule.cleanup in starter.config.ts(Licensees only) (0 3 * * *, daily at 03:00 UTC) and on no other cron.

TaskDeletesRuns when
activity:pruneActivity entries older than activity.retentionDaysactivity.retentionDays is not false
sessions:pruneRevoked and idle sessionsauth.enabled
account:purgeAccounts whose deletion grace period has endedauth.enabled
notifications:pruneRead notifications older than notifications.retentionDaysnotifications.enabled and retention is not false
invitations:pruneInvitations 30 days past their expiryorgs.enabled
checkouts:pruneExpired open-checkout rowspayments.enabled

Prunes delete 1,000 rows at a time and stop after 20 chunks per run, shared across all of them. If your tables gain more than 20,000 prunable rows a day, run the cleanup more often: set schedule.cleanup and its triggers.crons entry to 0 * * * *, or to one expression that names several hours, such as 0 3,15 * * *.

To add a task, create server/tasks/reports/sync.ts, which Nitro names reports:sync. A task gets no event, so build one from its context with withFabricatedEvent, which ends the event's database pool when the callback returns:

import {
  taskCloudflareBinding,
  withFabricatedEvent,
} from '#layers/kit/server/events/fabricated-event'
import { defineReportedTask } from '#layers/kit/server/monitoring/task'
import { enqueue } from '#layers/kit/server/utils/queue'

export default defineReportedTask({
  meta: { name: 'reports:sync', description: 'Queue a CRM sync per user' },

  async run({ context }) {
    const binding = taskCloudflareBinding(context)

    if (!binding) throw new Error('reports:sync has no Cloudflare bindings')

    return withFabricatedEvent(binding, async (event) => {
      const users = await useDrizzle(event)
        .select({ id: tables.users.id })
        .from(tables.users)

      for (const { id } of users) {
        await enqueue(event, { kind: 'crm-sync', payload: { userId: id } })
      }

      return { result: { queued: users.length } }
    })
  },
})

defineReportedTask sends a throw to your error trackers, so throw when the bindings are missing rather than returning quietly. Await every query inside the callback. One issued after it returns either fails on the ended pool or opens a new pool that nothing ends.

Then give the task a cron. Add the cron to triggers.crons in wrangler.jsonc(Licensees only):

"triggers": {
  "crons": ["0 3 * * *", "0 9 * * MON"],
},

Name the task under that cron in schedule.tasks in starter.config.ts, spelled exactly as triggers.crons spells it:

schedule: {
  cleanup: '0 3 * * *',
  tasks: { '0 9 * * MON': ['reports:sync'] },
},

Nitro picks the tasks to run by the cron's exact text, so 0 9 * * 1 and 0 9 * * MON are two different crons. Prefer day names: Cloudflare counts weekday 1 as Sunday. To run a task with the kit's, list it under the schedule.cleanup cron. It then runs alongside them in the same invocation and shares its time, and a delete it makes through deleteInChunks (layers/kit/server/database/chunked-delete.ts(Licensees only)) draws from the same 20 chunks.

Define every task with defineReportedTask, as above. Each task it defines holds the invocation open until that task settles, so one task that throws does not cut the others on its cron short. A task defined with plain defineTask is not held, and can be cut short when another task on its cron throws.

The six tasks above live in layers/kit/server/tasks/. A file of yours at the path a kit task's name gives, such as server/tasks/sessions/prune.ts, replaces it (Project structure).

pnpm dev fires no cron. To run one locally, start pnpm preview --test-scheduled, which passes the flag on to wrangler dev, and request the cron by its text from a second terminal:

curl 'http://localhost:8787/__scheduled?cron=0+3+*+*+*'

Configuration

KeyWhereDefaultWhat it does
queue.enabledstarter.config.tstrueTurns the queue on. Off, enqueue returns false.
queues.producers bound as QUEUEwrangler.jsoncnuxter-jobsThe queue enqueue sends to.
max_retries on the jobs consumerwrangler.jsonc5Retries before a job dead-letters.
max_batch_size, max_batch_timeout on the jobs consumerwrangler.jsonc10, 5 secondsMessages per consumer run, and how long Cloudflare waits to fill a batch.
dead_letter_queue on the jobs consumerwrangler.jsoncnuxter-jobs-dlqWhere exhausted jobs go.
Consumer for the dead letter queuewrangler.jsoncbatches of 100Reports and deletes dead jobs.
schedule.cleanupstarter.config.ts'0 3 * * *'The cron the kit's tasks run on.
schedule.tasksstarter.config.ts{}Your tasks by cron, named as Nitro names them.
triggers.cronswrangler.jsonc["0 3 * * *"]When scheduled tasks run. Each is schedule.cleanup or a schedule.tasks key, spelled the same.

There are no environment variables. The build reads the queue names from wrangler.jsonc, so a rename happens there and nowhere else. With the queue on, the build fails unless wrangler.jsonc has the QUEUE producer, a consumer for that queue naming a dead_letter_queue, and a consumer for the dead letter queue. It also refuses a dead letter queue that is the jobs queue or names one of its own.

The schedule is checked against triggers.crons whenever Nuxt loads its config, so a mismatch fails pnpm install and pnpm dev as well as the build. It fails when triggers.crons lists a cron twice, or one that is neither schedule.cleanup nor a schedule.tasks key; when schedule.cleanup is missing from triggers.crons while any of the kit's tasks runs; and when schedule.tasks names a cron triggers.crons does not list, one of the kit's six tasks, the same task twice under one cron, or a cron with no tasks. When Nitro starts, under pnpm dev as well as in the build, the kit also refuses a scheduled task Nitro does not register, which for one of yours means no file at the path its name gives, and a schedule that a layer's nuxt.config or a module changed instead of starter.config.ts.

Create both queues before the first deploy (Deployment):

pnpm exec wrangler queues create nuxter-jobs
pnpm exec wrangler queues create nuxter-jobs-dlq

Good to know

  • A handler can run more than once, and a retry reruns all of it. Make it safe to repeat. For work billed per attempt, keep a status row and check it first.
  • Throw only when a retry can help. A failure that will repeat the same way, like bad input or a permanent refusal, should be logged and returned, or it burns six attempts and dead-letters.
  • Keep payloads to plain JSON: ids, strings, numbers. A queue message is capped at 128 KB, so store files in R2 (Storage) and pass the key.
  • The messages of one batch run in turn on one event, whose database pool ends after the last of them has been acknowledged or retried. Await every query a job starts: one issued after the batch settles either fails on the ended pool or opens a new pool that nothing ends. What a helper keeps on that event lasts the batch too: activePlansForOrg reads an organization's plans once per event, so a plan check in one job does not see a grant an earlier job in the batch wrote. A task's event holds what it keeps for the whole run.
  • enqueue reads QUEUE off the event. A request's event, a listener's event and the event withFabricatedEvent hands its callback all carry it. An event built without cloudflare makes enqueue return false.
  • Unit tests alias #jobs-registry to a stub with no handlers. Test a job by importing its default export and calling run(payload, event), as layers/kit/test/unit/invitation-mail.test.ts(Licensees only) does (Testing).

A link with a lock opens the kit’s private repository, which every licensee can read.