Skip to Content
Runlane
Run in production

Deploy with Postgres polling

Keep runs in Postgres and let long-running or scheduled workers poll for work.

Choose this lane when you want durable Postgres storage with polling workers. Queries can use a transaction pooler; set preparedStatements: false if it cannot track named statements. Listeners need a direct or session-mode connection. See PgBouncer setup.

Deployment shape

producer    -- writes runs ----------> Postgres
worker      -- polls and claims -----> Postgres
Postgres    -- best-effort signal ---> worker
maintenance -- advances due work ----> Postgres

Postgres stores the truth. Workers claim work there directly: a claim records which worker owns the run for a limited time. The signal helps an idle worker wake sooner, but losing a signal does not lose the run.

Run workers on a schedule

Export a timer handler from your shared runtime:

src/scheduled-worker.ts
import { runlane } from './runlane.js'

export const handler = runlane.createDeliveryHandler({ maxDuration: '50s' })

One invocation starts the runtime if needed, runs one maintenance pass, then drains due runs. It returns { drain, maintenance }; drain.runsExecuted counts attempts, and maintenance contains the tick result. Lambda event and context arguments are ignored, so you can export the handler directly for a scheduled Lambda.

Use a cron timer, a cloud scheduler, or an event scheduler. Work waits for the next invocation, so start latency follows the timer interval. Choose Postgres + SQS to avoid waiting for a scheduled polling drain, or when you need native SQS-triggered Lambda delivery. Delivery and worker capacity still affect start latency.

maxDuration is required and must not exceed 2,147,483,647 milliseconds (about 24.8 days). Its clock starts at handler entry and covers startup, maintenance, and draining. Set it below the platform timeout, leaving room for handler cleanup and result writes. If maintenance consumes the budget, the handler returns a drain count of zero. It still waits for the maintenance pass to finish.

When no run is due, the drain returns, unless an armed scheduled fire is due before the handoff time. Then it waits for that fire, starts it, and also picks up runs that become due while it waits. The wait counts toward maxDuration. At the handoff time, the drain stops starting runs, including scheduled fires. Queued runs and fires due after handoff wait for the next invocation. Active attempts keep running.

At the deadline, Runlane stops new acquisition and immediately aborts active attempts' context.signal, skipping shutdownGrace. Handlers must honor the signal and settle promptly. An error after this abort interrupts the attempt without spending a retry. See Stop crash loops for how a late start affects the interruption allowance and queue position. A successful return still succeeds. Settlement can continue after the deadline; the budget is cooperative, not a hard process timeout.

Set maxRuns to cap the number of attempts started. It does not bound elapsed time. Worker and execution options such as queues, concurrency, and leaseDuration are accepted; signal is owned by the handler's budget. The handler checks its options and queue names when you create it, so a bad setting fails at deploy time instead of after a maintenance pass.

export const handler = runlane.createDeliveryHandler({
  maxDuration: '50s',
  maxRuns: 50,
  concurrency: 4,
})

Overlapping invocations use storage leases to avoid owning the same attempt. Make external effects safe to repeat: a crash or an expired lease can still cause another attempt.

Maintenance runs by default to advance schedules and recover interrupted work. Set maintenance: false only when another process owns those passes. You can also pass tick options, such as maintenance: { scheduleLookahead: '5m' }, to match your timer interval. When skipped, the result's maintenance is undefined.

For a fetch route, call the handler without forwarding the HTTP request:

app/api/worker/route.ts
import { runlane } from './runlane.js'

const handler = runlane.createDeliveryHandler({ maxDuration: '50s', maxRuns: 50 })

export async function GET() {
  return Response.json(await handler())
}

Protect the route so only your scheduler can invoke it.

Keep the runtime outside the handler so warm instances reuse the storage pool. Do not call close() after each invocation: a closed runtime cannot restart. A one-shot process should close its runtime in finally before exiting.

Configure postgresPollingLane({ connectionString, schema, runHints: false }) for scheduled workers. This skips the dedicated run-progress connection. A scheduled drain does not open the separate worker wake-up connection.

shutdownGrace still applies when closing a worker or runtime. Set grace below the platform's termination window and leave time for cleanup and storage writes. A hard kill cannot run cleanup. A later drain recovers the attempt after its lease expires, subject to the task's interruption limit.

How idle workers wake

With workHints enabled, createDeliveryWorker() opens and confirms the worker wake-up listener before it resolves. Listener startup failure rejects worker creation and can be retried. Workers on the same lane share that listener until the lane closes. start(), producers, maintenance, and drain() do not open it.

After a commit makes a run deliverable, the storage driver sends a separate pg_notify statement. It sends the first hint immediately and combines nearby commits into one trailing hint per environment and queue. The data transaction does not send notifications. A notification is only a hint; storage-format compatibility follows the upgrade procedure.

One hint wakes one waiting slot in each listening process. If that slot's claim scan sees additional due candidates, it wakes one idle sibling in the same worker. Each sibling repeats this while it sees more work. An empty scan wakes nobody. A single run does not trigger a sibling wake. While siblings are idle, the scan may read one extra candidate without locking unused work; ordinary claims still enforce queue capacity, priority, and lease ownership.

workHints defaults to contractDefaults.delivery.workHints (true). Set workHints: false on postgresPollingLane() when workers cannot keep a LISTEN connection. This stops work publications and removes the work listener and its delivery check. Commits in the same runtime still wake idle workers immediately. Work from other runtimes waits for polling with idle backoff. Disable runHints too when run readers cannot keep a listener.

Hints only lower latency. Polling guarantees progress while storage and worker capacity are available. Delays, retries, schedules, and lease expiry always depend on polling and maintenance.

Follow Upgrade Runlane when changing packages or stored formats.

Hints are best effort. If a producer dies after commit but before sending its hint, or a hint query fails, ordinary polling still finds the run. Hint failures cannot fail the committed operation. Closing the driver drops pending trailing hints and waits for hint statements already sent.

emptyPollDelay sets the first delay after an empty scan. Further empty scans use random backoff up to the larger of emptyPollDelay and contractDefaults.delivery.storagePollingMaximumEmptyPollDelay; see the polling defaults. If you set emptyPollDelay above that default maximum, every idle delay uses your configured value. These delays bound an idle slot's polling wait when a hint is lost. They do not bound storage latency, time waiting for a free slot, or the time needed to make future work runnable. Delayed work also needs polling or maintenance to discover that it is due.

Both listeners use directConnectionString, which defaults to connectionString. The query pool keeps using connectionString. After each listener connects, a background check sends a private notification through the query pool. Missing delivery reports configuration_invalid through observeBackgroundFailures, with operation work_listener or run_listener; startup and polling continue. See PgBouncer troubleshooting.

Budget subscription connections

Each lane process opens one dedicated run-listener connection, shared by all runs.subscribe() and CLI follow readers. Budget this in addition to the query pool and the polling-worker work listener: a lane can use the pool maximum plus two dedicated connections. Run hints and work hints have separate purposes and channels. With a transaction pooler, budget the pool connections on the pooled URL and up to two listeners on the direct URL separately.

Run hints carry only run identity. Readers always reread storage and fall back to streams.pollInterval after a missed hint or listener loss. The listener reconnects with backoff. A run without subscription interest adds no run-hint SQL. See run subscription hints for interest leases, error reporting, and custom composition.

Install the packages

npm install @runlane/core @runlane/lane-postgres-polling @runlane/postgres-storage zod

The files below use one practical layout:

src/
├── tasks/send-email.ts
├── runlane.ts
├── worker.ts
└── maintenance.ts
scripts/
└── migrate-runlane.ts

Rename the paths to fit your app, but keep the worker and maintenance entry points out of request handlers.

Put task code in its own module

Create src/tasks/send-email.ts. Producers import the task definition for its schema and id. Only workers execute run() and therefore need EMAIL_API_URL.

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

const envSchema = z.object({ EMAIL_API_URL: z.url() })

export const sendEmail = task({
  id: 'email.send',
  schema: z.object({ to: z.email() }),
  async run({ to }, context) {
    const { EMAIL_API_URL } = envSchema.parse(process.env)
    const response = await fetch(EMAIL_API_URL, {
      body: JSON.stringify({ to }),
      headers: { 'content-type': 'application/json' },
      method: 'POST',
      signal: context.signal,
    })
    if (!response.ok) throw new Error(`Email API returned ${response.status}`)
  },
})

Create one runtime module

Create src/runlane.ts. Producers, workers, and maintenance import this module so they use the same environment, task catalog, queue definition, and Postgres lane.

Set DATABASE_URL before this module loads:

src/runlane.ts
import { createRunlane, RunRetention, queue } from '@runlane/core'
import { postgresPollingLane } from '@runlane/lane-postgres-polling'
import * as z from 'zod'

import { sendEmail } from './tasks/send-email.js'

const { DATABASE_URL } = z.object({ DATABASE_URL: z.string().min(1) }).parse(process.env)

export const emailQueue = queue({ name: 'email', default: true })

export const runlane = createRunlane({
  retention: {
    succeeded: RunRetention.deleteAfter('7d'),
    cancelled: RunRetention.deleteAfter('7d'),
    failed: RunRetention.deleteAfter('30d'),
    expired: RunRetention.deleteAfter('7d'),
  },
  lane: postgresPollingLane({ connectionString: DATABASE_URL, schema: 'runlane' }),
  queues: [emailQueue],
  tasks: { sendEmail },
})

Apply migrations before startup

Create scripts/migrate-runlane.ts and run it as a release or deployment step before the new application starts. Do not call it from a request handler or worker startup.

scripts/migrate-runlane.ts
import { applyPostgresStorageMigrations } from '@runlane/postgres-storage'
import * as z from 'zod'

const { DATABASE_URL } = z.object({ DATABASE_URL: z.string().min(1) }).parse(process.env)

await applyPostgresStorageMigrations({ connectionString: DATABASE_URL, schema: 'runlane' })

Apply and validate migrations before starting the new app version. Runtime startup does not inspect or change the schema. Behind PgBouncer, run migrations with a direct database URL; see run behind PgBouncer. The package migration runner holds a schema-scoped advisory lock, so concurrent deploy jobs settle on one owner.

Apply the complete migration history shipped with the installed provider. Check the storage compatibility rules before selecting a retained schema.

The Postgres storage driver documents the migration contract, physical records, and rollback policy.

Start a worker

Create src/worker.ts and use it as the worker service's process entry point. It runs the worker and maintenance in one process:

src/worker.ts
import { emailQueue, runlane } from './runlane.js'

const worker = await runlane.createDeliveryWorker({
  handleSignals: true,
  concurrency: 8,
  queues: [emailQueue.name],
})

try {
  await worker.waitUntilClosed()
} finally {
  await runlane.close()
}

The entry point handles cooperative SIGTERM and SIGINT shutdown. Your process supervisor should restart it when waitUntilClosed() rejects.

If you run workers with the CLI instead, runlane work does the same: it starts maintenance through start({ maintenance }) and calls runtime close() on the first signal. Close stops acquisition and rejects new external producer calls at once. Maintenance and running attempts drain concurrently. Attempts can still trigger children and use their task context during grace. Close waits for admitted producer calls and gives committed observers their bounded storage-read window before closing lane resources.

The runtime automatically batches independent lifecycle writes and concurrent point reads. Handler concurrency still controls how many tasks can execute at once; it does not require the same number of simultaneous database transactions. Unbounded queues can also share acquisition batches. Bounded queue capacity remains enforced in storage, and worker shutdown waits for pending lifecycle writes.

Recover from worker crashes

A crashed worker's running task becomes available again when its lease expires. Polling workers can reclaim it on a later storage scan without waiting for maintenance. If the attempt's time limit has also expired, maintenance records the timeout instead.

The crash budget bounds repeated worker interruptions.

Set ownership duration through the runtime execution options. The worker guide shows runtime, per-worker, and CLI overrides. Shorter leases recover faster, but a worker that cannot refresh in time loses ownership. One failed renewal does not stop an attempt: a retry whose planned slot is at or before the renewal deadline is sent even if its timer wakes late. Confirmation must arrive before the last confirmed send plus the full lease duration. Make external effects safe to repeat.

Run maintenance

Maintenance runs by default in createDeliveryWorker() and runlane work. Set maintenance: false or --no-maintenance only when another service runs it. The worker above already runs it. You can run it in several worker processes. Postgres coordinates maintenance owners, and another process with the same scheduled tasks can take over if a schedule owner stops.

Processes that register the same declared schedule IDs share one schedule owner. Processes with different scheduled tasks each create runs for their own schedules. Due scans preserve armed declarations absent from the local catalog and continue to known schedules within a bounded scan. Shared schedules still create one run per occurrence. Keep maintenance running for every scheduled task.

To run maintenance as its own service instead, set maintenance: false on createDeliveryWorker() in the worker and create src/maintenance.ts:

src/maintenance.ts
import { runlane } from './runlane.js'

await runlane.start({ maintenance: true })
process.once('SIGTERM', () => {
  void runlane.close().catch((error: Error) => {
    process.stderr.write(`${error.message}\n`)
    process.exitCode = 1
  })
})

Maintenance owns schedules, due retries, waits, token timeouts, expired attempts, cancellation cleanup, delivery recovery, and outbox publishing. See run maintenance for bounded scheduled calls and operational checks.

Check the deployment

In an isolated environment:

  1. Confirm all migrations from the installed provider version have been applied.
  2. Start src/worker.ts. If you run maintenance as its own service, start src/maintenance.ts too.
  3. Trigger one task from an application process that imports runlane from src/runlane.ts.
  4. Confirm the worker stores the terminal result.
  5. Complete a token-backed wait and confirm maintenance makes the task runnable again.
  6. Stop a worker during a leased attempt and confirm lease recovery works.
  7. Stop a worker during a side effect and confirm the next attempt does not repeat it. See make side effects safe to repeat.

A missing or incompatible schema fails on the first operation that needs it. Fix the deployment migration step rather than handling that failure in application code.

If storage is healthy but a run stays queued, check the worker's queue filter, environment, and task catalog. Use process supervision for repeated database failures.

Deploy compatible task catalogs

First pick the right tool in change tasks safely. Runlane does not pin runs to worker builds.

The overlap advice below assumes both releases can read the same storage format. For the stored execution-policy upgrade, stop old runtimes before new ones create runs, even on separate queues.

A polling worker only claims runs whose task it can execute. A run for a task that an older worker lacks stays queued until a worker with that task claims it. The older worker skips it and logs worker_task_missing, at most once a minute for each task. So producers and workers can deploy in any order.

Keep old task definitions and their queues available until queued, retrying, released, and waiting runs have drained. If a task id remains unchanged, its handler and saved payload, task-output, and step-output shapes must remain compatible with runs created by the previous release. Upgrade the maintenance owner before enabling schedules that exist only in the new task catalog.

Next, give maintenance a production owner.

Run progress hints

runHints defaults to contractDefaults.realtime.runHints (true) on this lane and the raw driver. Set runHints: false on Lambda and other serverless consumers to avoid one extra LISTEN connection per container. Run subscribers watching work executed by a consumer with hints disabled fall back to streams.pollInterval. Keep hints enabled on long-running processes when prompt updates matter. These hints are separate from worker delivery signals.

Allow time for worker shutdown

Set the platform's termination window above the worker's shutdownGrace, with time left for handler cleanup and result writes. Configure Kubernetes terminationGracePeriodSeconds or ECS stopTimeout. The worker guide describes grace and immediate abort.

Reserve time for handoff

Set handoffBefore in createDeliveryHandler() options beside maxDuration. It hands work to a fresh invocation at the next step boundary after that much time remains. Saved steps are replayed rather than run again. The reserve gives the current step time to finish and Runlane time to save progress and arrange continuation before the host deadline.

When unset, Runlane reserves 25% of the invocation budget (contractDefaults.delivery.handoffReserveFraction). A duration such as handoffBefore: '30s' reserves that much time instead. Choose a positive duration that covers your longest step plus storage and continuation time. handoffBefore must be shorter than maxDuration; equal or longer values are rejected when the handler is created. Handoff still requires a new saved step in this attempt: handlers without saved steps never stop early for handoff.

Set handoffBefore: false to turn off step-boundary handoff. Work then runs until completion, a caller or task deadline, or the platform time limit. This does not extend the host's execution budget.

On this page