Skip to Content
Runlane
Build with RunlaneBuild tasks

Define and trigger tasks

Define a typed task, register it, trigger a run, and read the result.

Use this guide when your app needs to start background work without waiting for the task handler to finish. The task, runtime, trigger, and local inspection code live in separate modules.

Define the task and its data

Create src/tasks/generate-invoice.ts:

src/tasks/generate-invoice.ts
import { task } from '@runlane/core'
import * as z from 'zod'

const env = z.object({ INVOICE_API_URL: z.url() }).parse(process.env)
const invoiceSchema = z.object({ id: z.string() })

export const generateInvoice = task({
  id: 'invoice.generate',
  output: z.object({ invoiceId: z.string() }),
  schema: z.object({ accountId: z.string().min(1) }),
  async run({ accountId }, context) {
    const response = await fetch(env.INVOICE_API_URL, {
      body: JSON.stringify({ accountId }),
      headers: { 'content-type': 'application/json' },
      method: 'POST',
      signal: context.signal,
    })
    if (!response.ok) throw new Error(`Invoice API returned ${response.status}`)

    const invoice = invoiceSchema.parse(await response.json())
    return { invoiceId: invoice.id }
  },
})

An executable task combines a stable id, a Standard Schema-compatible payload schema, and a handler. This task calls the invoice API inside run().

If the producer must not import handler code or worker-only environment settings, use a shared producer definition. Define the schema and defaults once without run, then add the handler in the worker module.

Runlane validates and transforms the payload before creation, then stores the schema output. Every attempt uses that run's saved payload without applying the input schema again. A rejected trigger leaves no partial run.

Original inputs are not retained separately. Keep handlers compatible with saved payloads when deploying a new task definition; changing an input schema does not rewrite existing runs.

When output is present, TypeScript checks the handler return. Runlane validates it before marking the run successful.

Register the task

Create src/runlane.ts and add the task to its named catalog:

src/runlane.ts
import { createRunlane, RunRetention, queue } from '@runlane/core'
import { createLocalLane, createTestLane } from '@runlane/lane-local'

import { generateInvoice } from './tasks/generate-invoice.js'

const defaultQueue = queue({ name: 'default', default: true })

export const runlane = createRunlane({
  retention: {
    succeeded: RunRetention.deleteAfter('7d'),
    cancelled: RunRetention.deleteAfter('7d'),
    failed: RunRetention.deleteAfter('30d'),
    expired: RunRetention.deleteAfter('7d'),
  },
  lane: process.env.NODE_ENV === 'test' ? createTestLane() : createLocalLane(),
  queues: [defaultQueue],
  tasks: { generateInvoice },
})

For app triggers, start runlane dev. It owns local runs; without it, the trigger fails with storage_unavailable. Start dev and retry without restarting the app.

Use the catalog handle at trigger sites. It keeps payload inference tied to the registered definition.

In the application module that accepts the request, import the shared runtime and trigger the registered task:

src/invoices/start-invoice.ts
import { runlane } from '../runlane.js'

export async function triggerInvoice(accountId: string) {
  return runlane.trigger(runlane.tasks.generateInvoice, { accountId })
}

export async function generateInvoiceNow(accountId: string) {
  return runlane.runNow(runlane.tasks.generateInvoice, { accountId })
}

trigger() returns after storing the run and its first delivery request. The returned run normally starts as queued; a worker or delivered wakeup executes it later. outcome is created for new work, or returned_existing when an existing run ID, idempotency owner, debounce window, or same-task singleton holder was returned. See prevent duplicate runs.

To start a run for every committed database write, even after a crash, see trigger after a database write.

Keep producers separate from workers

Runlane copies retry, maxAttemptDuration, and maxInterruptions from the triggering runtime into the run. Put these policies in the shared definition. Worker-only policy changes do not affect accepted runs. A worker logs worker_task_policy_mismatch once per task per process when its retry or duration policy differs, naming the fields.

Put schemas and task defaults in a shared module without run. Producers can register these definitions without importing handler modules, worker-only dependencies, or worker settings.

src/tasks/invoice-definition.ts
import { task } from '@runlane/core'
import * as z from 'zod'

export const generateInvoice = task({
  id: 'invoice.generate',
  schema: z.object({ accountId: z.string().min(1) }),
  output: z.object({ invoiceId: z.string() }),
})

The worker's task module imports this definition and adds run. Keep its API clients and settings in that worker module. Register the shared definition in the producer runtime and the executable task in the worker runtime:

src/producer.ts
import { createRunlane, RunRetention } from '@runlane/core'
import { lane, queues } from './delivery.js'
import { generateInvoice } from './tasks/invoice-definition.js'

export const producer = createRunlane({
  retention: {
    succeeded: RunRetention.deleteAfter('7d'),
    cancelled: RunRetention.deleteAfter('7d'),
    failed: RunRetention.deleteAfter('30d'),
    expired: RunRetention.deleteAfter('7d'),
  },
  lane,
  queues,
  tasks: { generateInvoice },
})
src/worker.ts
import { createRunlane, RunRetention } from '@runlane/core'
import { lane, queues } from './delivery.js'
import { generateInvoice } from './tasks/generate-invoice.js'

export const worker = createRunlane({
  retention: {
    succeeded: RunRetention.deleteAfter('7d'),
    cancelled: RunRetention.deleteAfter('7d'),
    failed: RunRetention.deleteAfter('30d'),
    expired: RunRetention.deleteAfter('7d'),
  },
  lane,
  queues,
  tasks: { generateInvoice },
})

Here delivery.ts is your app's lane and queue configuration. Both runtimes must select the same storage, environment, and queue policies. The worker task should spread the shared definition and add its handler, as shown in producer definitions.

Use the producer for trigger(), batch submission, and operator reads. Workers, runNow(), and hook delivery require executable tasks. Maintenance can run on a producer-only runtime: outbox publication, recovery, and cleanup do not need handlers. Schedule materialization needs the target task definition registered, with matching schedule declarations when used; it does not need run. Maintenance can request hook delivery, but an executable worker must invoke the callbacks.

Choose queued or inline execution

MethodUse it whenWhat it does
trigger()A worker should execute the task laterStores a queued run and returns
runNow()This process should execute one attempt nowStores, claims, and runs one attempt inline

runNow() does not keep retrying or waiting in the same call. Its returned run may be succeeded, failed, retrying, released, or queued again after an interruption. Normal workers and maintenance continue any later work.

If the queue is paused, runNow() rejects with queue_paused (retryable: false). If its total or per-key pool is full, it rejects with queue_at_capacity (retryable: true). Neither refusal saves a run or a key owner. Use queues.resume() to resume the queue, temporarily raise its limit with queues.setLimit(queue, { total, perKey, expiresAt }), or retry after capacity is free. To prefer inline execution but accept queued work, catch only the capacity refusal:

import { ErrorCode, RunlaneError } from '@runlane/core'
import { runlane } from './runlane.js'
import { generateInvoice } from './tasks/generate-invoice.js'

const payload = { accountId: 'account-123' }
try {
  const run = await runlane.runNow(generateInvoice, payload)
  process.stdout.write(`Inline result: ${run.status}\n`)
} catch (error) {
  if (!(error instanceof RunlaneError) || error.code !== ErrorCode.QueueAtCapacity) throw error
  const { run } = await runlane.trigger(generateInvoice, payload)
  process.stdout.write(`Queued: ${run.id}\n`)
}

To queue and wait for a worker instead, call trigger() and then runs.watch(generateInvoice, run.id, { signal }). Iterate the watch to read updates; pass an abort signal to bound the wait.

For urgent queued work, configure a bounded queue's priorityBoost and pass priority: RunPriority.High when triggering. Read the priority contract and upgrade requirements first. This changes selection among due runs; it does not interrupt running tasks or apply to runNow().

Execute the run and read its result

For an in-process test script, set NODE_ENV=test to select the shared runtime's createTestLane(). Drain currently due work, then read the stored run:

scripts/try-invoice-locally.ts
import { runlane } from '../src/runlane.js'

const { run } = await runlane.trigger(runlane.tasks.generateInvoice, {
  accountId: 'account-123',
})
await runlane.drain()

const storedRun = await runlane.runs.get(runlane.tasks.generateInvoice, run.id)
process.stdout.write(`${storedRun?.output?.invoiceId ?? 'No invoice created'}\n`)

await runlane.close()

Passing the task handle to runs.get() makes the read typed. Runlane checks the task id and parses stored JSON with the current output schema.

Use runs.get(run.id) for a task-agnostic operator read. Its output is JsonValue | undefined.

In an application, keep the long-running worker or transport consumer in the process entry point rather than starting one per trigger.

Check the result

A successful integration has one stored run. Its taskId matches the task, its status becomes succeeded, and its output matches the handler result.

If triggering fails with validation_failed, compare the payload with the task schema. Runlane has not created a partial run. If runs stay queued and workers log worker_task_missing, register an implementation with run for that task ID on the worker; a producer-only definition cannot execute work.

Next, run workers for the execution path.

On this page