Skip to Content
Runlane
Build providers

Provider overview

See how storage and delivery providers become a Runlane lane.

This section is for people adding a database, broker, or native worker integration to Runlane. If you only want to deploy Runlane, use choose a lane.

Start with the lane

A lane connects Runlane to infrastructure:

storage + delivery = lane

Every lane has storage. Delivery has two forms:

+--------- lane ---------+
| Storage                |
| - run state            |
| - atomic changes       |
|                        |
| Delivery               |
| - poll storage         |
| - transport wakeups    |
+------------------------+

Polling is a delivery mode, not a transport. A Postgres polling lane needs only Postgres. A Postgres and SQS lane uses Postgres for state and SQS for wakeups.

Provider combinations

memory + polling
  -> lane-local

Postgres + polling
  -> lane-postgres-polling

Postgres + SQS
  -> lane-postgres-sqs

Redis / Valkey + polling
  -> lane-redis-polling

Redis / Valkey + Streams
  -> lane-redis-streams

Redis / Valkey + SQS
  -> lane-redis-sqs

These packages use the @runlane/ scope. Runlane supplies Postgres and Redis/Valkey storage, plus SQS, Redis Streams and HTTP transport.

Lane partBuilt-in providersA custom provider could target
StorageProcess memory, Postgres, Redis/ValkeyAnother database that meets the storage contract
DeliveryStorage polling, SQS, Redis Streams, HTTPAnother broker that can publish, deliver, and settle wakeups

The Redis storage driver keeps each namespace in one Cluster slot. Use redisPollingLane(), redisStreamsLane(), or redisSqsLane().

Another broker can be a transport provider if it can publish Runlane's bytes and deliver them to a Runlane worker. The broker never becomes the source of truth.

Decide what you are building

You want to addBuildMain contract
A database or durable key-value storeStorage providerStorageDriver
Run search and event historyOptional read modelOperatorReadDriver
A broker or queueTransport publisherTransportDriver
A broker-native worker or handlerDelivery adapterProviderDeliverySurface
A ready-to-use combinationLane packagecreateLane()

Most provider packages own one infrastructure boundary. A lane package wires compatible pieces together:

storage ----+
            +--> lane --> createRunlane()
delivery ---+

Keep provider code mechanical

Providers store records, run transactions, publish bytes, receive messages, and map native failures. Runlane core decides whether a run should start, retry, wait, cancel, or finish.

Import public contracts, schemas, codecs, enums, and defaults from @runlane/contracts. Do not copy stable values into the provider.

Share transaction write rules

Keep one createStorageMutationStaging() instance per transaction attempt. It checks phase order, unchanged returned records, conditional creates, and key collisions. It also owns snapshots of staged writes. Reads, clocks, retries, and atomic commit remain the provider's job.

This excerpt shows point reads and writes. Pass each read result to observe() and return the object it gives back. Staging keeps the record you pass as its unchanged baseline and hands the callback a copy, so never expose or change the record you passed. The copy is always mutable, even when your record is frozen, because the conformance suite edits returned records. If your driver already made the callback's copy, pass it as the third argument, observe(key, baseline, copy), so staging does not copy again. Pass the same encodedKey you used to read the record; staging does not re-encode it. Cache reads in the provider so repeated keys return the first observed value.

import {
  createStorageMutationStaging,
  parseGetRecordsCommand,
  storageRecordKeyCodec,
  type AppendRecordsCommand,
  type GetRecordsCommand,
  type NewStorageRecord,
  type StorageDriver,
  type StoredRecord,
} from '@runlane/contracts'

class ProviderTransaction {
  readonly staging = createStorageMutationStaging()

  constructor(private readonly source: Pick<StorageDriver, 'get'>) {}

  async get(command: GetRecordsCommand) {
    this.staging.beginRead('get')
    const parsed = parseGetRecordsCommand(command)
    const { records } = await this.source.get(parsed)
    return {
      records: parsed.keys.map((key, index) => this.staging.observe(storageRecordKeyCodec.encode(key), records[index])),
    }
  }

  create(record: NewStorageRecord) {
    this.staging.create(record)
  }

  replace(current: StoredRecord, replacement: NewStorageRecord) {
    this.staging.replace(current, replacement)
  }

  delete(current: StoredRecord) {
    this.staging.delete(current)
  }

  append(command: AppendRecordsCommand) {
    this.staging.append(command)
  }
}

Call staging.beginRead('queryCandidates') before candidate discovery. Call staging.seal() when now() ends reads, then return the provider's attempt-local timestamp. Call staging.close() as soon as the callback finishes or fails. Wait for admitted reads and any pending now() call before validation, commit, rollback, or connection release. Already admitted reads can still call observe() while settling. If the callback fails and cleanup succeeds, preserve the callback's error.

At commit, read transaction.staging.readVersions, transaction.staging.mutations, and transaction.staging.appendCommand. Validate observed versions and expected absence, then apply every mutation and the append atomically. A conflict must abort the whole attempt. Start any replay with a new staging instance. Staging does not perform these storage operations.

Pass the unchanged object returned by this attempt to replace() or delete(). Copies and records from other attempts are rejected. Changing its document, indexes, key, or version also makes it invalid. Each key permits one mutation; an appended stream partition cannot also be point-read or written in the attempt.

Build in this order

  1. Choose storage or delivery. Do not build both at once unless the infrastructure requires it.
  2. Implement the smallest public contract.
  3. Declare real durability, ordering, and clock guarantees. Handle storage capacity or transport size limits at the provider boundary.
  4. Add startup, shutdown, and native error mapping.
  5. Run the shared conformance tests.
  6. Test the real service, including failure and shutdown.
  7. Compose the tested provider into a lane.

Version-aware storage must preserve immutable run baselines, started worker identities, and atomic patch markers. Implement RunPatches, RunPatchesByRun, and RunsByVersion from the current catalog. See patch storage rules.

Worker shutdown

On worker close(), stop acquisition immediately and keep active deliveries and their visibility or leases alive through shutdownGrace. When grace ends, abort each active delivery's signal with createWorkerShutdownError() from @runlane/contracts. Use the same reason when the worker's external signal requests an immediate stop. This factory returns a retryable RunlaneError with code task_interrupted. Core treats a handler error as an interruption when the delivery signal aborted after claim and before the error, regardless of the reason. Providers use the shutdown reason so handlers can identify why work stopped. Wait for handlers and settlement before closing provider resources. RunReleaseType.Shutdown is the release event category.

Supply the broker's receive count through DeliveryAttempt.deliveryCount when available. See delivery counts for the contract and retry policy.

A delivery Retry can carry an optional positive retryAfterMs hint from core. Omission keeps native retry backoff. Providers must not infer prompt retries from failure codes. See retry timing for receipt fencing, native limits, and platform behavior.

Terminal hook wakeups

Delivery envelopes use version 3 and a type tag: run_wakeup, run_hooks_wakeup, or schedule_wakeup. Run messages carry runId; schedule hints carry scheduleId and fireAt. Schedule hints publish directly, outside the run-owned outbox. Storage providers add ScheduleOccurrencesDue over armed records, partitioned by environment and sorted by (fireAt, scheduleId). Delivery intents and decoded messages retain this type. Providers carry the canonical opaque bytes and apply ordinary dispositions; core owns hook selection and execution. A worker missing the task acknowledges hook wakeups with reason hook_handler_missing; delivery recovery republishes them for a registered worker. Older envelope versions are rejected. Storage providers implement the sparse RunsHooksPending and RunsHooksPendingByQueue indexes on terminal runs with unfinished hook work. Hook claims use an independent token and expiry on the run row, with exact-token settlement and tombstone fencing.

Stream command identity

Core computes stream append digests from RFC 8785 canonical JSON before persistence. Providers store the supplied digest and member identities unchanged; they do not recompute them from database JSON output. Core rejects lone UTF-16 surrogates in chunk strings and keys before appending them. See stream input rules.

Optional run hints

A lane may provide runSignal.wait({ environment, runId, signal, timeoutMs }): Promise<void>. It resolves when a run may have changed, when the listener becomes ready or reconnects, when the timeout expires, or when the signal aborts. Register interest before reading storage. Await only when the read is empty, then read storage again. Cancel the pending interest when data is already available.

Register the waiter synchronously. If network setup is still pending, resolve existing waits when registration finishes so callers repeat any earlier read. Bound every wait by timeoutMs. Waits must never reject; report failures through storage.observeBackgroundFailures(). Core observes a rejected wait as adapter_contract_violation and preserves its original cause internally. After close, an already pending wait may resolve immediately, but new waits must retain the polling timeout or reject with a structured error so other owners cannot spin. Lost and duplicate hints must only affect latency; a missed hint costs at most streams.pollInterval while storage and the event loop remain available. Without this surface, core retains polling.

Publish hints after the source transaction commits. Include only a bounded run identity, with no log, stream, metadata, or output values. Notify for committed run events, stream records, and logs. Reconnect with backoff and route detached failures through storage.observeBackgroundFailures(); do not reject a committed write. Keep the listener lifecycle with the composed lane and release waiters on close.

Prepare storage-polling work hints

A lane may supply workSignal.start(environment): Promise<void> alongside workSignal.wait(options). Core awaits this optional hook before starting a long-running storage-polling worker. A failure rejects createDeliveryWorker(). Share concurrent starts, confirm listener readiness, and release failed clients so worker creation can retry. Existing providers without this hook keep their current behavior.

Core does not call this hook for producers, maintenance, or drain(). Keep these processes free of worker-only connections. Hints remain best-effort: workers must always check storage for due work.

Storage providers must preserve saved idempotency results after automatic run deletion and support IdempotencyFinalRunExpiry. Follow the saved idempotency requirements.

On this page