Skip to content

Getting Started ​

WARNING

kern-jobs is in early development, and its API changes between minor versions.

Install ​

sh
npm install kern-jobs postgres
sh
pnpm add kern-jobs postgres
sh
bun add kern-jobs postgres

Install the database client of your application beside kern-jobs: postgres.js, as in this guide, or another one, such as node-postgres.

kern-jobs runs on Node.js 24 or newer and Bun 1.4 or newer, with PostgreSQL 15 or newer. Use TypeScript 6.0 or newer.

Try it ​

To see a job run from start to end, create a project in an empty directory, and install kern-jobs and postgres in it as above:

sh
npm init -y
npm pkg set type=module

Save this module in it:

ts
import { createJobs, defineTask } from "kern-jobs"
import { postgresJsDriver } from "kern-jobs/drivers/postgres-js"
import { migrateJobs } from "kern-jobs/migrations"
import { defineManifest, startWorker } from "kern-jobs/worker"
import postgres from "postgres"

const sql = postgres(process.env.DATABASE_URL!)
const driver = postgresJsDriver(sql)

// Create the schema of kern-jobs, or update it.
await migrateJobs(driver)

// Define a task and enqueue a job of it.
const greetTask = defineTask("greet").withPayload<{ name: string }>()

const jobs = createJobs(sql)
await jobs.enqueue(greetTask, { name: "world" })

// Run a worker until it has run the job, and stop it.
const greeted = Promise.withResolvers<void>()

const greet = greetTask.implement(async ({ name }) => {
  console.log(`Hello, ${name}!`)
  greeted.resolve()
})

const worker = startWorker(driver, { manifest: defineManifest({ tasks: [greet] }) })
await greeted.promise
await worker.stop()
await sql.end()

Run it with the URL of a PostgreSQL database, such as:

sh
DATABASE_URL=postgres://localhost:5432/postgres node quickstart.ts
sh
DATABASE_URL=postgres://localhost:5432/postgres bun quickstart.ts

It creates the schema of kern-jobs in the database, enqueues a job, runs it in a worker, which prints Hello, world!, and stops the worker.

The sections below split it into the modules of an application, which connects kern-jobs through its database client in two ways:

  • The code that enqueues jobs passes createJobs the client itself, such as sql, or the client of a transaction, so that its enqueues join that transaction.
  • migrateJobs and the worker take a driver that wraps the client, such as postgresJsDriver(sql), and the worker runs outside the transactions of your application.

See Database Clients and Transactions for each client.

Create the schema ​

kern-jobs keeps its jobs in a PostgreSQL schema of its own, kern_jobs. Create it with migrateJobs before your application starts, such as in the script that applies its migrations:

ts
import { postgresJsDriver } from "kern-jobs/drivers/postgres-js"
import { migrateJobs } from "kern-jobs/migrations"
import postgres from "postgres"

const sql = postgres(process.env.DATABASE_URL!)

await migrateJobs(postgresJsDriver(sql))
await sql.end()

Run it at every deploy as well, as Updating kern-jobs describes.

To use a different schema name, pass it as schemaName to migrateJobs, and to createJobs and startWorker below. Each schema is an installation of kern-jobs of its own: its jobs, the code that enqueues them, and its workers do not see those of another one.

Define tasks ​

A task is a kind of work, such as sending an email, and a job is one run of it. Define each task with its name and the type of its payload in a module that both the code that enqueues jobs and the worker import:

ts
import { defineTask } from "kern-jobs"

export const sendWelcomeEmailTask = defineTask("email.sendWelcome").withPayload<{
  userId: string
}>()

Defining Tasks describes the options of a task, and the pages after it describe enqueueing, recurring jobs, keys, queues, and scopes.

Connect ​

Create the jobs API of your application with the database client to enqueue through:

ts
import { createJobs } from "kern-jobs"
import postgres from "postgres"

export const sql = postgres(process.env.DATABASE_URL!)

export const jobs = createJobs(sql)

Database Clients and Transactions shows how to connect node-postgres and other clients.

Enqueue ​

Enqueue a job of a task with its payload:

ts
await jobs.enqueue(sendWelcomeEmailTask, { userId: user.id })

Enqueue a job in the transaction that writes its data by passing createJobs the client of the transaction:

ts
await sql.begin(async tx => {
  const [user] = await tx`insert into users (email) values (${email}) returning id`
  await createJobs(tx).enqueue(sendWelcomeEmailTask, { userId: user.id })
})

The job becomes visible to workers when the transaction commits and never runs when it rolls back, so it never misses the data that the transaction writes. To share jobs across your application and still enqueue in its transactions, or to enqueue in the transactions of an ORM, see Database Clients and Transactions. Enqueueing Jobs describes delays, overriding the options of a task, and enqueueing many jobs at once.

Run a worker ​

Implement each task with the handler of its jobs, as the default export of a module that only the worker imports:

ts
import { sendWelcomeEmail } from "../../email"
import { sendWelcomeEmailTask } from "../../tasks"

export default sendWelcomeEmailTask.implement(async ({ userId }) => {
  await sendWelcomeEmail(userId)
})

List the implementations of your tasks in a manifest:

ts
import { defineManifest } from "kern-jobs/worker"

import sendWelcomeEmail from "./tasks/send-welcome-email"

export const manifest = defineManifest({ tasks: [sendWelcomeEmail] })

Start a worker with the manifest in a process of its own:

ts
import { postgresJsDriver } from "kern-jobs/drivers/postgres-js"
import { startWorker, stopOnSignals } from "kern-jobs/worker"

import { sql } from "../jobs"
import { manifest } from "./manifest"

const worker = startWorker(postgresJsDriver(sql), { manifest })

stopOnSignals(worker, { close: () => sql.end() })

On SIGTERM or SIGINT, stopOnSignals stops the worker, closes the database client, and exits the process. In a process that also serves your application, call stop from its shutdown instead.

A job whose handler returns is done, and a job whose handler throws runs again later. Running Workers and the pages after it describe handlers, retries, leases, and stopping, and Monitoring describes how to watch workers and jobs in production.