Skip to Content
Runlane
Build providers

Postgres storage driver

Apply migrations and understand the PostgreSQL provider's guarantees.

@runlane/postgres-storage implements durable StorageDriver records and the optional OperatorReadDriver projection. Most applications should use it through a ready-made Postgres lane.

Apply migrations

Run migrations as a deployment step, before application processes start. Migrations must run from the installed @runlane/postgres-storage package because bundled code cannot load its migration files:

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' })

The package's schema declarations are the source of truth. Release tooling generates immutable SQL and an ordered journal; explicit migration commands apply that history and validate the installed version, ordering, and ledger hashes. Missing schema, table, function, or column errors report configuration_invalid with migration instructions and the required storage schema version. The driver neither applies nor inspects migrations at application startup, so deployment must complete migration validation before starting application processes.

If migration files cannot be read, Runlane reports configuration_invalid with instructions to run migrations from the installed package, such as runlane adapter postgres migrate. If temporary files cannot be prepared, the error tells you to check that the temporary directory is writable. Other unclassified failures report whether applying or inspecting migrations failed. Original causes stay on the error for local diagnostics.

If a runtime operation finds a missing schema, table, or function, it reports configuration_invalid and names the required storage schema version. Before starting Runlane, run runlane adapter postgres migrate or call applyPostgresStorageMigrations() in a script. A missing database reports that the database must be created or the connection string corrected. These errors are not retryable.

Read the current schema version from postgresStorageSchemaVersion, derived from the package migration journal. 0000_initial.sql creates the baseline tables, operator indexes, run payload storage, native event sequencing, version sequence, and required functions. The additive 0001_native_string_order.sql rebuilds three operator run-list indexes with explicit COLLATE "C" ID ties. 0002_retention_sweeps.sql adds the retention checkpoint table and replaces the record-lock function to support it. 0003_run_retention_deadlines.sql adds retention, child-result, cancellation, idempotency-result, schedule-fire, and pending-hook queue indexes. It clears old per-fire schedule occurrence rows; it does not backfill run rows. Runlane records each migration in <schema>.runlane_migrations.

Matching published baseline schemas upgrade in place. Never change an applied migration. A 0.4 ledger or a modified development baseline is unrecognized; use a fresh dedicated schema and the storage replacement procedure. Stop old processes while applying the Unicode order change and restart list pagination without old cursors.

Run payloads live in record_payload, separate from changing lifecycle metadata; reads reconstruct the same logical document. Unchanged payloads retain their PostgreSQL TOAST storage during status updates. Canonical run and event rows own their indexed operator metadata, without duplicate run or event documents. A canonical event's UUID is its record_id; typed run_id and sequence columns provide the native RunEventsBySequence path without duplicating its encoded partition and sort columns.

When one atomic creation writes an exact canonical run and its initial Created event with the same payload, PostgreSQL stores that payload only on the run. The event carries a durable reference marker, and raw and operator reads reconstruct the complete event. Before either record changes in a way that would break that relationship, the same transaction copies the payload into the event and clears the marker. Opaque, copied, or independently written events retain their inline payloads.

The migration account must be able to create runlane_assert_record_write, runlane_lock_record_versions, and runlane_read_queue_controls; runtime accounts must be able to execute all three. The assertion function aborts an entire write statement when a conditional mutation or append check fails. The version-read function locks dependencies before checking them with static queries and fresh snapshots; it accepts record keys and collection names, never SQL text. See transaction internals for these checks and the implicit-commit path.

The migration runner rejects mismatched ledgers. There are no down migrations. Rollback restores the old database or schema with its matching old application version; see rollback.

Create the driver

src/runlane/storage.ts
import { createPostgresStorageDriver } from '@runlane/postgres-storage'

export async function openPostgresDriver(connectionString: string) {
  const driver = createPostgresStorageDriver({
    connectionString,
    schema: 'runlane',
  })

  await driver.start?.()
  return driver
}

The caller owns driver.close() after it is finished.

OptionDefaultPurpose
connectionStringRequiredPostgres URL for the query pool. Transaction-mode poolers need statement tracking unless preparedStatements is false.
directConnectionStringconnectionStringDirect Postgres or session-mode URL for both dedicated listeners and migrations: CLI migrate and status, applyPostgresStorageMigrations(), and inspectPostgresStorageMigrations(). Must reach the same database.
preparedStatementscontractDefaults.postgres.preparedStatements (true)Reuse named protocol-level statements. Set false for transaction poolers without statement tracking; SQL values remain parameterized.
schemaURL schema parameter, otherwise publicStorage schema; an explicit option wins. The direct URL does not select another schema.
lockTimeout'2s'Duration bounding transaction replay and stream append lock waits. Maximum: 2,147,483,647 ms (PostgreSQL platform limit).
maxTransactionAttempts8Bound on transaction replay attempts.
workHintscontractDefaults.delivery.workHintsPublish work hints after delivery-ready commits and enable the worker listener.
runHintscontractDefaults.realtime.runHintsStart the run-interest listener at driver startup.

Both URLs use the same Postgres URL validation. resolvePostgresStorageConfig() resolves the direct URL default and strips URL schema parameters. Both first-party lanes forward the option; Postgres/SQS takes it inside postgres. See PgBouncer setup.

preparedStatements applies to pooled reads and writes, transaction helpers, stream appends, and notification publishing. Both first-party lanes forward it; Postgres/SQS takes it inside postgres. It does not change listener or migration session requirements. See using a pooler without statement tracking.

The provider maps SQLSTATE 42P05 and 26000 to non-retryable configuration_invalid, preserving the cause. The message explains the pooler's statement-tracking requirement, gives PgBouncer 1.21 or later with max_prepared_statements above 0 as an example, and offers preparedStatements: false, a session-mode pool, or a direct connection. It does not disable named statements or replay a failed operation automatically.

The provider uses READ COMMITTED, optimistic validation, advisory locks, and atomic transactions. maxTransactionAttempts defaults to 8. Exhaustion returns a retryable storage conflict. An eligible point-read-only attempt validates its read-set versions after the callback without opening a transaction block or taking new locks. Exclusive candidate selection and replay admission may already hold locks, and those paths keep them. A changed version replays the callback. An empty-read-set tx.now() can sample the clock in one statement without a transaction block.

A dropped connection or a client query timeout (query_timeout) reports retryable storage_unavailable and preserves the original cause internally. A write may already have committed when its response is lost or delayed. The driver returns the error without replaying the transaction callback. Reconcile stored state before retrying an operation that could repeat an effect.

If rollback fails, the driver discards the connection and preserves both the original failure and the rollback failure internally.

Worker wake-up hints

For custom storage-polling lanes, pass driver.workSignal to createLane({ workSignal: driver.workSignal, ... }), as you pass driver.runSignal for run hints. The driver owns and closes both resources. Its worker listener stays closed until workSignal.start(environment) or workSignal.wait(...) is called. Driver startup, producers, scheduled drains, and the Postgres/SQS lane never open it. Runtime worker creation awaits workSignal.start(), so LISTEN is ready before a worker starts, for custom lanes too. One notification wakes one matching local slot.

workHints defaults to contractDefaults.delivery.workHints (true). After a delivery-ready commit succeeds, the driver sends a separate pg_notify hint for the Postgres polling lane. The first hint goes out immediately. Nearby commits share a trailing hint per channel and payload. The driver keeps at most one hint query in flight for each pair. The data transaction contains no notification. This keeps PostgreSQL's shared notification lock out of data commits and their write-ahead log (WAL) flushes. The unchanged notification format does not make old and new stored readers compatible; follow the upgrade procedure above.

A failed hint query cannot fail the committed data operation. If a process dies between commit and hint, ordinary polling finds the run. Idle poll delays bound that wait, subject to storage and worker-capacity delays; see how idle workers wake. Failed hint queries report StorageBackgroundFailure with operation: 'work_hint' and the affected environment. Runtime subscriptions route them through observability.telemetry.logger and metrics. Without a listener, the driver emits a process warning containing the structured RunlaneError. Listener failures are contained and do not reject committed work. Closing drops pending trailing hints and drains statements already sent before ending the pool. The trailing timer does not keep the process alive.

Set workHints: false when polling workers cannot keep a LISTEN connection. This stops work publications and removes the work listener and its delivery check. The driver exposes an empty workSignal, with no start or wait, so core uses local commit wakes and polling. The Postgres/SQS lane forces it off and rejects the option because SQS delivers work.

Hints only lower latency. Polling with idle backoff guarantees progress while storage and worker capacity are available. Delays, retries, schedules, and lease expiry always depend on polling and maintenance. See Postgres polling for worker fan-out and idle delay behavior.

Listener delivery checks

After initial readiness and each reconnect, each listener subscribes to a unique private check channel and sends a nonce through the driver's query pool. Sending from a separate connection detects transaction poolers that silently lose notifications. The five-second internal timeout starts after the notify query finishes. A passing check removes the channel with UNLISTEN. A failed or cancelled check keeps it until the connection ends, so a cleanup failure can't hide the diagnosis.

The check never delays or rejects startup or worker creation. A timeout reports non-retryable configuration_invalid once per listener connection through observeBackgroundFailures, using operation work_listener or run_listener. Its message recommends directConnectionString. If the check's own notify query fails, the mapped storage error is reported under the same operation. Reports use the same telemetry and structured warning path as hint failures. The listener stays active and polling continues. Close cancels the wait and drains SQL and observer work already started before ending the pool.

Run subscription hints

The raw driver and both first-party Postgres lanes use contractDefaults.realtime.runHints (true), independently of worker work hints. Set runHints: false for Lambda/serverless consumers to avoid one extra connection per container. Subscribers watching work executed there rely on streams.pollInterval. For a custom lane, pass driver.runSignal to createLane(). Driver start() opens the run listener unless runHints is false.

One dedicated LISTEN connection serves every run subscriber on that driver. This is one connection in addition to the query pool and any polling-worker listener. Subscription and CLI follow reads register interest before reading. Every wake, listener readiness, reconnect, or timeout leads to another authoritative read. Lost hints fall back to streams.pollInterval, subject to storage and event-loop availability.

An in-memory interest registry is shared between driver processes through schema-scoped notifications. Active readers renew a short lease. Each renewal echoes to its local subscriber and forces one extra authoritative read per active run every 10 seconds. That read closes the window before remote producers learn the interest. Producers send coalesced run hints only for leased interests; runs with no interest add zero SQL statements, record writes, or index entries. Expired interests are removed. A stopped reader can leave a lease briefly active, so its former run can still produce hints until that lease expires. A producer that has not yet learned an interest can miss a hint; polling covers that window.

Hint payloads contain only a fixed-size hash of the environment and run identity. They contain no source values. Data commits never contain notifications. Hint send and listener failures use StorageBackgroundFailure with operation: 'run_hint'. The runtime routes these failures through its existing telemetry logger and metrics; standalone drivers retain the structured warning fallback. Listener failure wakes readers immediately, retries with capped exponential backoff, reports once per outage, and preserves polling. A successful LISTEN resets the outage report gate. Closing the driver releases waits and drains detached work before ending the pool.

The driver supports ordered append and exclusive candidate selection with FOR UPDATE SKIP LOCKED. A claim gives the worker time-limited ownership. An advisory lookahead may find more due work without locking unused rows; core retains queue ordering and rechecks storage state before another claim.

Observation positions are allocated at the end of a transaction to shorten lock time on the shared environment head. The head remains durable state shared by all processes.

Use alongside Prisma

Keep Runlane tables out of schema.prisma. Run runlane adapter postgres migrate for Runlane, then prisma migrate deploy for application tables. The two histories may target the same PostgreSQL schema because they own distinct tables and ledgers; separate schemas remain easier for local prisma migrate dev drift checks.

Know what is stored

Postgres uses normalized tables for the closed logical collection catalog. Important groups are:

DataRelations
Runs and historyrunlane_runs, runlane_record_run_events
Steps and ownersrunlane_record_run_steps, runlane_record_run_step_token_owners
Deliveryrunlane_record_outbox_messages
Schedulingrunlane_record_schedule_occurrences
Idempotency and singleton ownershiprunlane_record_idempotency_owners, runlane_record_singleton_owners
Debounce ownershiprunlane_record_debounce_owners
Queue capacityrunlane_record_queue_controls, runlane_record_queue_capacity_pools, runlane_record_queue_capacity_slots
Observationshead, record, and checkpoint relations
Maintenancerunlane_record_maintenance_leases
Pruningrunlane_record_run_tombstones
Wait tokenstoken, idempotency-owner, and run-link relations

Documents remain opaque jsonb. Core's codecs own their shape. Provider columns project only contract-owned keys and named indexes.

One non-cycling bigint sequence assigns record versions across every table. Each session caches 64 values, so rollbacks, closed sessions, and concurrent sessions leave gaps and out-of-order values. A version is an opaque fence: an equality check rejects a stale write. Do not use versions as counters or compare their order.

Validate stored strings

Use a database with server_encoding set to UTF8; C collation then matches Unicode code-point order.

Identifiers and index strings use the shared storage string rule. Queries use native UTF-8 byte order under COLLATE "C", including operator run and event ID ties. The driver does not re-sort returned records in JavaScript.

The contracts JSON boundary rejects NUL and lone surrogates in strings and object keys in every lane. A trigger() payload containing either rejects with validation_failed before any Postgres write and persists no run. Leading U+FEFF remains legal in JSON. SQLSTATE 22P05 and 22021 still map to non-retryable validation_failed errors as a database error safeguard. The original cause stays internal; client-facing errors contain no SQL or native database message.

Understand operator reads

0000_initial.sql creates a GIN index on the canonical document's tag array, restricted to visible runs with at least one tag. listRuns({ filter: { environment, tag } }) uses an exact, case-sensitive match and binds the tag into its pagination cursor. PostgreSQL maintains membership atomically as the document changes; there is no separate tag table or backfill. Common tags can still need substantial matching and sorting work. The index stores entries only for tagged runs, but PostgreSQL still checks its filter when a run changes. See tag contracts.

Build indexes on the fresh schema before starting application processes; see apply migrations.

Sorting runs by RunSortField.RunAt orders on the generated runnable_available_at column. No index serves that order: PostgreSQL scans the environment's visible runs and keeps the requested page with a bounded top-N sort. runlane_runs_operator_run_at_idx serves filter.runAt ranges, so a narrow range keeps that sort small.

Canonical run and event rows update their indexed operator metadata in the same transaction as their documents. getRun() and listRuns() read runlane_runs directly. listRunEvents() pages indexed event metadata first, checks each candidate's visible parent by the run primary key, and fetches an event document by its primary key only when that parent exists. Hidden orphan metadata still advances the keyset cursor, so filtering cannot stall or skip later visible events and orphan documents are not returned.

A malformed or non-canonical raw document remains point-readable as an opaque record but does not populate operator columns. Tombstoning hides a run and its events immediately, even while bounded cleanup removes child rows. Run and event rows deliberately have no foreign key: deleting a raw run retains its event rows until explicit child cleanup. The retained canonical event's (environment_key, record_id) primary key continues to reserve its event UUID during that interval.

Understand transaction time

The provider reports transaction_authoritative clock semantics:

  1. Point reads record present and absent dependencies. Exclusive candidate selection or replay admission may already hold locks.
  2. When the attempt needs tx.now(), the driver validates the complete read set under its locks before freezing storage time. An empty read set with no existing locks can use one clock statement without a transaction block.
  3. Mutations and derived projections commit atomically. A read-only attempt instead validates its snapshot after the callback, retaining any locks already held.

See transaction internals for lock ordering, implicit commits, and replay.

Busy blocking admission has a two-second server-side lock timeout. A changed dependency, busy lock, serialization failure, or deadlock consumes a bounded replay attempt.

Do not open another storage transaction inside the callback. Do not perform external effects there. The callback may run again.

Read pages and atomic capacity

PostgreSQL chunks point reads into groups of 1,000 keys and caps named-index pages at 1,000 rows. Larger query limits return a capped page with a cursor whenever more records may exist. There is no transaction record-count limit.

Physical limits belong to the driver and are not configurable through a limits option. Core checks the shared record size from storage defaults; applications cannot raise it through provider configuration. Keep payloads much smaller than that boundary to leave room for record metadata and indexes.

Verify a provider change

After changing migrations, mappings, SQL, locks, clocks, or error handling, run:

pnpm --filter @runlane/postgres-storage test:postgres:local

The live suite covers fresh setup, tamper detection, conformance, operator-column rollback, contention, clock-after-lock behavior, and operator-query parity.

See Postgres storage internals for the exact physical mappings and replay algorithm. The generic rules are in build a storage provider, and stable names are in storage contract values.

Keyed waits store their saved outcome in the existing step records. The event, checkpoint, token owner, count, and optional observation are written in the transaction that resumes or claims the run. Upgrade the handler API and all record readers together; see keyed wait contracts.

A composed lane owns and closes its storage driver. Do not share a driver between independently closed runtimes. A wait on a closed hint signal retains its timeout so accidental sharing cannot create a hot read loop.

Driver start() waits for the first run-listener attempt, up to the listener health-check timeout, so a producer hears readers' interest as soon as start() returns. An unresponsive listener cannot hold startup longer than that; readers fall back to storage while it reconnects. Connection attempts use the listener health-check timeout and retry with the existing backoff. Closing the driver destroys a pending listener handshake.

On this page