Skip to Content
Runlane
Build providers

Storage provider

Connect Runlane to a database through the StorageDriver contract.

A storage provider lets Runlane keep run state in a database. Core owns the records and workflow rules. The provider makes the database behave like StorageDriver.

Runlane core
    |
    | get, query, transact
    v
StorageDriver
    |
    v
your database

Import StorageDriver and its supporting contracts from @runlane/contracts. For runtime tests, createTestLane() provides in-process memory without dev. createLocalLane() instead connects to the dev-owned store and fails if dev is absent.

Check the database first

The database must support the behavior Runlane needs:

  • atomic changes across all records in one transition;
  • version checks that stop stale writers;
  • ordered index queries with stable pagination;
  • the shared record size and atomic capacity floors;
  • one stable time value during a transaction attempt.

If the database cannot commit the full transition atomically, it cannot be a conforming storage provider. Do not split one transition into several commits.

Implement three operations

OperationWhat it does
get()Reads any list of exact keys, chunking internally
query()Reads a bounded page from a named Runlane index
withTransaction()Reads, checks, and changes records in one atomic commit

get() accepts any key count and returns one position for every requested key, including repeated keys and missing records. Chunk native reads internally. Return copies so callers cannot mutate stored objects, dates, or bytes.

query() and transaction queryCandidates() accept any positive safe-integer limit. They may return a smaller page, but must return a cursor whenever more records may exist. These discovery operations never throw a storage-limit error.

Make transactions safe to replay

A storage_conflict rejection means the transaction committed nothing. If the commit outcome is unknown, reject with storage_unavailable and do not replay the transaction callback. A lost commit response may follow a successful write.

withTransaction() carries most of the contract:

read records
     |
query index candidates
     |
call now() and seal reads
     |
stage create, replace, or delete
     |
validate versions and commit everything
     |
retry the whole callback after a supported conflict

The callback can run more than once. Do not call external APIs, run user code, generate random ids, or emit meaningful logs inside it.

Important rules:

  • now() returns one frozen time for the current attempt.
  • Reads stop after now() or the first mutation.
  • create() succeeds only while the key is absent.
  • replace() and delete() use the exact version read by that attempt.
  • A failed condition rolls back the whole attempt.

The storage contract details page contains every transaction rule and edge case.

Optimize storage mechanics without moving workflow rules

Two optional transaction features let a provider reduce contention:

  • append(command) allocates and persists an ordered batch of opaque values in the same commit as the point writes. Core uses it for observations; providers without it keep the existing point-write path.
  • queryCandidates(command, { mode: StorageCandidateMode.Exclusive }) owns returned candidates until the attempt ends and skips busy candidates. Advertise profile.exclusiveCandidates: true only when the provider guarantees that behavior across instances.

Core continues to own claims, completion, retries, leases, and queue capacity. These features change storage mechanics without adding workflow methods or changing application APIs. Follow the ordered append and exclusive selection rules before enabling them.

The transaction is already a bounded write batch. create(), replace(), and delete() stage records; they do not require a database request per call. A provider can group those writes by collection and operation, validate all conditions, and commit them together. A failed condition must abort the entire attempt, even if some groups have already executed. Do not introduce provider-specific lifecycle commands to obtain bulk writes.

Core can combine independent worker lifecycle transitions into one transaction and concurrent point reads into one get() call. It keeps completion pending until commit and splits its own batches after storage_limit_exceeded. Providers must handle complete batches; a transaction may concern several runs. Core never splits a user-atomic transition or replays a transport publish to fit storage.

Treat index rows as candidates

Runlane owns a closed set of StorageIndexName values. Map each name to a native index; do not expose arbitrary provider queries through StorageDriver.

Sort by the encoded sort value, then the encoded record key. Use Runlane's cursor codec. A cursor is valid only for the same index, partition, range, and direction.

An eventually consistent index may return stale rows or miss recent rows. Core handles that by reading a useful candidate again by its exact key before making a write decision.

Store Runlane documents unchanged

Runlane sends a key, an opaque versioned JSON document, and its complete index entries. Use the public storage codecs for keys, tuples, dates, cursors, and unsigned integers.

Do not create another editable schema for runs, events, steps, schedules, leases, outbox messages, or wait tokens. Core owns those document shapes.

Report what the provider can guarantee

The storage profile declares:

  • contract version: contractVersion: 2;
  • durability: process memory or durable storage;
  • clock authority: client, server-sampled, or transaction-authoritative;
  • index consistency: strong or eventual;
  • optional exclusive candidate selection.

Runlane validates the profile when constructing the runtime. Missing or unsupported contract versions fail before the runtime accepts work. Logical documents use schemaVersion: 2.

Physical limits belong to the driver, outside its profile. Reject an attempt you cannot commit with createStorageLimitError(), with no durable effect or callback replay for that error. Its non-retryable storage_limit_exceeded error carries meta: { actual, limit } in one unit.

Every driver must commit the capacity floors from contractDefaults.storage. Core checks the shared record size when staging creates, replacements, and appends.

Report detached failures

A driver with background effects can implement observeBackgroundFailures(listener). It returns an idempotent unsubscribe function. Each registration is independent, including repeated registrations of the same callback.

Report only failures of detached work after a successful caller operation. StorageBackgroundFailure contains an operation name, a structured RunlaneError, and an optional environment. Transaction failures still reject the caller. Catch listener exceptions and rejected promises; neither may fail committed work or trigger another report through that listener.

Core subscribes before starting lane resources and unsubscribes after close drains detached work. Each runtime receives matching-environment and unscoped failures through observability.telemetry.logger and metrics. Use short operation names with lowercase letters, digits, and underscores; core replaces invalid or overlong labels with unknown. Error messages, causes, and metadata are excluded from telemetry.

Drivers without background effects can omit the hook. See the telemetry reference for the log and metric names.

Add operator reads only when needed

OperatorReadDriver provides exact run lookup, filtered run lists, and event history. It is optional. A lane can execute tasks without it.

If you add it, update its projections in the same commit as the raw records. Tombstoned runs and events must disappear from operator reads immediately.

A separate read contract does not require separate document storage. Keep canonical payloads once where practical, and derive only the metadata needed for indexed filtering and ordering. PostgreSQL stores that metadata beside its canonical run and event records and reads them directly with bounded SELECTs. Other providers may use different physical layouts while returning the same records and cursor behavior.

Plan the atomic boundary for each database

SQL providers can group statements inside a native transaction. The read-set validation must still protect missing keys and blind creates, not only rows returned by a locking read. MySQL's locking reads and SKIP LOCKED are mechanisms to evaluate against those guarantees; skipping busy candidates does not replace validation of the full transition.

Redis needs an atomic boundary covering the complete read set, records, indexes, and optional stream allocation. Redis transactions do not roll back commands that fail during execution. A pipeline or MULTI wrapper alone therefore does not prove Runlane's all-or-nothing contract. Validate the complete batch before mutation and test failure paths against the actual implementation. The Redis provider uses one prevalidated Lua commit for this boundary. Runlane does not ship a MySQL provider.

Redis needs special care

Before choosing Redis Cluster, check that every Runlane transaction can commit atomically across all affected keys. See the Redis Cluster limit for design options.

Prove the provider

Run the shared storage conformance suite before composing the driver into a lane. Then test the real database under conflicts, failures, restarts, and shutdown.

Continue with test a provider and the exact storage values. Use the Postgres driver or Redis driver as a production reference. createLocalStorageDriver() from @runlane/local-adapters is the smaller executable reference.

Queue admissions strongly read QueueControls, including missing rows, before storage time is sealed. Preserve exact QueueCapacityPools counts and both pool-tagged QueueCapacitySlots atomically with the run. Map the advisory RunsDispatchHeadByKey index too. See queue admission controls and pools for identities, fencing, and creation-time head membership.

Custom drivers must support optional saved idempotency results and IdempotencyFinalRunExpiry. See saved idempotency requirements for atomic writes, expiry fences, size holds, and sparse index layout.

On this page