Skip to Content
Runlane
Build with RunlaneDevelop and test

Run workers

Start a long-running worker or execute a bounded batch and exit.

Workers claim stored runs and execute task handlers. Create them from a process entry point, not from each request handler. The examples import an existing runtime from src/runlane.ts.

Run a local development worker

Run runlane dev in one terminal and your app in another. Dev owns the in-memory store. App and worker processes reach it over the authenticated loopback bridge. Apps discover the nearest default config while searching upward from their working directory; see local discovery and restart behavior.

Without dev, the first local storage operation fails with storage_unavailable. Start dev and retry; the app needs no restart. A separate runlane work also needs dev for local storage. Use createTestLane() with drain() or executeNext() in tests. Dev restarts erase local runs. The local lane is for Node.js development, not serverless or edge hosting.

runlane dev watches the config and every local module it imports, including task helpers. It ignores node_modules. Files read at runtime with fs and .env files are not watched; restart dev after changing those files. Use --no-watch to disable reloads. runlane work and dev --once do not watch.

On a save, dev reloads task code in a new child worker while running attempts finish on the old code, and app triggers stay accepted. See Reload task code for the full sequence and the dev_reloading event.

Start a long-running worker

Create src/worker.ts and deploy it as a long-running process:

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

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

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

createDeliveryWorker() runs maintenance by default. Automatic maintenance drains when the last maintenance-enabled worker closes. Explicitly started services remain alive until runtime close. Storage leases elect one owner per maintenance band, so several workers can safely run it. Set maintenance: false or use runlane work --no-maintenance when maintenance runs elsewhere. The SQS Lambda delivery handler never runs maintenance in-handler.

createDeliveryWorker() starts the runtime and the lane's delivery path. The exact path depends on the lane:

LaneWorker behavior
LocalScans dev-owned storage over the loopback bridge
Postgres pollingScans durable Postgres state
Postgres and SQSReceives native SQS deliveries
Redis pollingScans Redis or Valkey state
Redis StreamsReads queued wakeups from Redis Streams
Redis and SQSReceives native SQS deliveries
HTTP pushNot supported; mount createDeliveryHandler() as a route in your app

The queues option contains registered logical queue names. concurrency limits in-flight work in this process. A queue concurrency is the separate durable limit shared across workers.

waitUntilClosed() observes the worker without stopping it. It rejects when a worker slot fails, allowing process supervision to restart the service.

Route tasks to different worker pools

A worker pool is a group of processes deployed for the same kind of work. Use a separate logical queue for each pool. For example, an email pool can use small machines while a report pool uses machines with more memory.

Define each queue once in a shared module. Register it in the producer and worker runtimes. Set a task's queue for its usual destination, or choose a registered queue for one trigger:

await runlane.trigger(generateReport, payload, { queue: reportQueue })

Start the report worker with queues: [reportQueue.name], following the worker entry point above. Give every pool an explicit queue filter; omitting it allows the worker to consume every registered queue. A pool skips runs for tasks it has no handler for. Those runs wait for a pool that has one. Producers can use shared definitions without handlers.

The run keeps its accepted queue through automatic retries and releases. A later idempotent trigger or named child replay does not move it to another pool. Queue capacity limits apply per logical queue and concurrency key, not across separate queues. Keep maintenance aware of all queues, including ones without active workers.

For Postgres and Redis polling, pools share storage and use queue filters. Local development processes share memory only through runlane dev. For SQS, bind different pools to different physical queues. Competing consumers on one physical queue do not provide pool isolation. Outbox publishers and maintenance must know every binding before producers use it. See compatible task catalogs.

Set CPU, memory, architecture, and scaling in the deployment that hosts each pool. Runlane selects work; it does not provision machines or change their size per run. Moving a run to another queue is not deployment pinning. Verify placement by triggering a run for each queue and checking that only its selected pool executes it.

Deploy compatible task code

See change tasks safely for which tool fits each kind of change. Runlane does not pin runs to an application build or keep old worker code available. Each attempt uses the task handler registered in the worker that claims it. The stored execution policy preserves retry and duration settings, not handler code or schemas.

Choose one approach before replacing task code:

  • Keep the new code compatible with existing runs. Retain task IDs and support saved payloads, step names and meanings, and stored step and child results.
  • Before a breaking change, stop new external triggers and scheduled creation for the affected work. Keep its workers and recovery maintenance running until existing runs and their children finish. Resolve outstanding waits before removing the old code.

Check stored run state, not just active attempts or queue depth. Delayed, retrying, released, waiting, and cancellation-requested runs are not finished. A return from drain() does not prove they are finished; it only processes currently due work within its limits.

Do not retry or rerun old runs after a breaking change unless the new handler supports their saved payloads.

Your deployment owns which build consumes each queue and how long old workers stay available. If incompatible builds must overlap, follow the isolation rules for Postgres polling or SQS. Runlane does not manage build selection or retirement. Separate queues do not make incompatible storage formats safe to mix; follow the coordinated package upgrade instructions.

Drain currently due work

For a bounded command, create a script such as scripts/drain-runlane.ts:

scripts/drain-runlane.ts
import { runlane } from '../src/runlane.js'

const { runsExecuted } = await runlane.drain({ maxRuns: 100 })
await runlane.close()

process.stdout.write(`Executed ${runsExecuted} runs\n`)

Use drain() with createTestLane() for in-process tests. It also works on other storage-polling lanes, including a dev-connected local lane. A local drain still needs dev running; leases prevent it and dev's worker from owning the same attempt. The example prints the number of attempts it executed.

It returns when:

  • no work is currently due;
  • it reaches the end of the scan it started;
  • maxRuns has been executed; or
  • its abort signal is cancelled.

A drain can stop at the end of its current scan while other work is due. An ordinary scan keeps the storage time from when it began, so work that becomes due during the drain, such as a child run or a parent resumed by its child, waits for the next drain() call. Queues with priorityBoost refresh that time after each run, so they may include such work. To finish a parent-and-child workflow, check that the runs you need are terminal, call drain() again, or run a worker. Future schedules, retries, and releases do not keep drain() open. Transport lanes do not expose it because one consumer cannot prove a broker is globally empty.

Storage scans use cursors to move past stale candidates. Scan-only pages do not spend the maxRuns budget.

Shut down cleanly

Set handleSignals: true to handle SIGTERM and SIGINT. The first signal closes gracefully with the resolved shutdownGrace; a later signal outside the shared 250 ms duplicate window aborts immediately. Launcher duplicates inside that window count as one signal. Handlers are removed when the worker closes. This option defaults to false; library workers install no process handlers unless asked.

worker.close() stops new claims and new receives immediately. Storage polling stops pending scans and queued claim batches before acquiring more work. A claim already committing when close() starts may still start its run inside the grace period. Running attempts keep their lease and continue without an abort for the runtime’s resolved shutdownGrace (see defaults). Set shutdownGrace on createDeliveryWorker() to change that worker's grace period.

Set shutdownGrace: 'unlimited' to stop acquisition and wait for running attempts with no abort timer. Omitted worker grace inherits the runtime’s resolved shutdownGrace. The worker signal still aborts immediately. In production, use unlimited only when the platform stop timeout allows the full drain; otherwise it kills the process and lease expiry recovers unfinished runs.

SQS graceful close lets in-flight receives finish and releases their unstarted messages by setting visibility to zero. Polls drain in parallel with attempt grace. Closing an idle consumer can therefore take up to waitTimeSeconds, plus request and release time, even when no tasks are running. Set sqs.waitTimeSeconds in postgresSqsLane() to shorten the wait for every queue consumer. The default remains 20 seconds; shorter waits increase empty receives and SQS request costs. See SQS polling options for the configuration contract. Lambda handlers do not poll and are unaffected. Aborting the worker's signal, or pressing Ctrl+C a second time in the CLI, aborts receives immediately. Immediate stop gives up pending responses; a message already assigned by SQS may remain hidden until its visibility timeout.

When grace ends, context.signal aborts with the RunlaneError returned by createWorkerShutdownError() from @runlane/contracts with code task_interrupted and retryable: true. context.signal.throwIfAborted() and signal-aware I/O reject with an error that has a name, message, and stack. An attempt that then ends in an error is released and queued immediately, without a task failure or retry cost. A caller abort through executeNext(), runNow(), or executeDelivery() follows the same release path. Work that succeeds after the abort still succeeds. The handler error is kept on the released attempt in runs.attempts(). Lambda and HTTP time limits can affect the interruption allowance. See Stop crash loops.

Close waits for every attempt and its saved outcome. It cannot forcibly stop JavaScript or undo an external side effect. A handler that ignores the signal can delay close indefinitely. If the process is killed, lease expiry provides recovery instead.

Task handlers should:

  • pass context.signal to I/O;
  • stop starting new work after cancellation;
  • return before shutdown can fully finish;
  • use external idempotency for repeatable effects.

After lease ownership is lost, middleware cleanup gets the attempt’s worker or drain shutdownGrace. Direct calls use the runtime’s resolved shutdownGrace. When that budget ends, Runlane frees the slot while cleanup continues detached. With unlimited grace, Runlane waits for cleanup to finish.

Repeated close() calls are safe. Abort the worker's existing signal to skip grace. Runtime close() owns maintenance and worker shutdown. Each worker’s grace governs its drain, even when longer than runtime grace; close waits for the longest active worker grace. It also waits for committed observations, within the runtime shutdownGrace deadline, before closing lane resources.

For example, handle SIGTERM by calling close(), wait for the worker to stop, then close the runtime. runlane.close() also closes any worker still running, so cleanup runs even when a worker fails:

const worker = await runlane.createDeliveryWorker({ shutdownGrace: '20s' })
const stop = () => void worker.close()
process.once('SIGTERM', stop)
try {
  await worker.waitUntilClosed()
} finally {
  process.off('SIGTERM', stop)
  await runlane.close()
}

With runlane work or runlane dev, the first SIGINT or SIGTERM calls runtime close(), stops maintenance, and drains the worker and its output observers. Press Ctrl+C again to abort running attempts immediately. Use --shutdown-grace 20s to override the grace period, or --shutdown-grace unlimited to wait without a timer. Config-backed dev workers use unlimited grace; the CLI owns the separate Ctrl+C timer. A deliberate second signal still aborts immediately. Launcher signals within 250 ms count as one request. JSON mode emits worker_shutting_down with shutdownGrace and runningAttempts. Local dev uses the same close path; its in-memory store is lost when the dev process exits.

Recover from worker crashes

A crashed worker's running task becomes available again when its lease expires. Set the default once in your shared runtime module, alongside its existing lane and queues:

const runlane = createRunlane({ lane, queues, lease: { duration: '1m' } })

Shorter leases recover faster. A worker that cannot refresh in time loses the run, and another worker may run it again. Make external effects safe to repeat.

Override the default for one worker with runlane.createDeliveryWorker({ leaseDuration: '30s' }), or run runlane work --lease-duration 30s. The execution options describe the full precedence.

Storage-polling workers find expired leases in their own scans. Transport lanes need maintenance to request another delivery. Maintenance also records timeouts when a task's attempt deadline has expired. Keep maintenance running.

Troubleshoot a queued run

Check, in order:

  1. The worker registered the task id.
  2. Its queue filter includes the run's logical queue.
  3. Producer and worker use the same Runlane environment.
  4. The lane points to the same storage and, for transport lanes, the same transport resources.
  5. Queue capacity is not held by live leases or reservations.
  6. Maintenance is moving due retries, waits, and delivery work.

Use limit concurrency for durable capacity and run maintenance for deferred work.

Interruptions and durable progress

See Stop crash loops for the interruption allowance and Invocation handoff for how Runlane yields before a time limit.

On this page