Skip to the content.

API reference

Everything exported by @solustiq/steady and its subpaths, version 0.1.0. The TSDoc comments in the source say the same in your editor.

Entry points

Import path Exports
@solustiq/steady everything on this page except the adapters and the Drizzle schema
@solustiq/steady/pg pgAdapter, PgQueryable
@solustiq/steady/postgres postgresAdapter, PostgresJsSql
@solustiq/steady/neon neonAdapter, NeonQueryFunctionLike
@solustiq/steady/drizzle steadyRuns, steadySteps, steadySignals, steadySchedules
@solustiq/steady/sql/steady.sql the schema as a SQL file
@solustiq/steady/sql/rls.sql the optional hardening script

All entry points ship as ESM and CommonJS with type definitions. Node 20 or newer.

createSteady

function createSteady(options: SteadyOptions): Steady

Creates an instance bound to one store and one tenant. Throws TenantAccessError for an invalid tenant or tenant: "*" without allowCrossTenant, and SteadyError for a missing db or an invalid encryption key.

SteadyOptions

Option Type Default Meaning
db StoreAdapter \| SqlAdapter required A SqlAdapter (pgAdapter, postgresAdapter, neonAdapter) is wrapped in the Postgres store, which checks it once with SELECT 1 before its first statement: an adapter whose query does not resolve to an array of rows (a raw pg.Pool passed without pgAdapter) is refused with “wrap a pg Pool with pgAdapter(pool)” before anything is written. A StoreAdapter (such as memoryStore()) is used as is.
tenant string "default" The tenant this instance serves (1 to 200 characters). "*" serves every tenant and requires allowCrossTenant.
allowCrossTenant boolean false Required with tenant: "*". No effect otherwise.
owner string random per instance Lease owner name of this process.
clock () => Date () => new Date() Time source, for tests. Used for leases, wake times and timestamps.
onEvent EventHook none Lifecycle events, see Events. Not awaited; errors are ignored.
redact RedactOptions \| false default patterns Secret redaction before store and emit. See Redaction.
encryption EncryptionOptions none { key, allowPlaintext? }: 32 bytes, base64. Encrypts payload columns at rest with AES-256-GCM. With a key, a stored value that is not encrypted is refused (DecryptionError) unless allowPlaintext: true (migration mode).
onDecryptionError "fail" \| "retry" "retry" A claimed run that cannot be decrypted: "retry" releases it for 5 minutes (attempts untouched, outcome deferred, reported in errors) and fails it after 24 hours; "fail" fails it at once.

The Steady instance

interface Steady {
  readonly tenant: string
  readonly owner: string
  defineFlow<I = void, O = unknown>(name: string, fn: FlowFn<I, O>, options?: DefineFlowOptions): Flow<I, O>
  start<F extends AnyFlow>(flow: F | string, input: FlowInput<F>, options?: StartOptions): Promise<StartedRun>
  signal(target: SignalTarget, name: string, payload?: unknown): Promise<SignalResult>
  schedule<F extends AnyFlow>(flow: F | string, cron: string, options?: ScheduleOptions<FlowInput<F>>): Promise<ScheduleRecord>
  unschedule(key: string, options?: { tenant?: string }): Promise<boolean>
  tick(options?: TickOptions): Promise<TickResult>
  get(runId: string): Promise<RunRecord | null>
  list(options?: ListOptions): Promise<RunPage>
  history(runId: string): Promise<RunHistory | null>
  cancel(runId: string): Promise<RunRecord | null>
  retryNow(runId: string): Promise<RunRecord | null>
  migrate(): Promise<void>
}

The store behind an instance is not part of its public API: it would return sensitive step results decrypted and unmasked. Read runs through get, list and history, which show "[sensitive]" in place of a sensitive result.

defineFlow

defineFlow<I = void, O = unknown>(name: string, fn: FlowFn<I, O>, options?: DefineFlowOptions): Flow<I, O>

Creates and registers a flow. name must match NAME_PATTERN; a different flow with the same name throws FlowDefinitionError. options.retry is the default retry policy of every step in the flow (a step’s own retry overrides it field by field). Type the input with the second parameter of fn: defineFlow("x", async (f, input: { id: string }) => ...).

start

start<F extends AnyFlow>(flow: F | string, input: FlowInput<F>, options?: StartOptions): Promise<StartedRun>

Creates a pending run. input is JSON-normalized, redacted and checked against 64 KB.

StartOptions Type Meaning
key string Idempotency key, unique per (tenant, flow), up to 200 characters. An existing run with this key is returned untouched. Keys starting with schedule: are reserved for schedule firings and refused. Keys are stored in plaintext: use an opaque id, not an e-mail address.
tenant string Must equal the instance tenant; required on a cross-tenant instance.
delay Duration Do not run before this span from now, or before this Date.

Returns StartedRun = RunRecord & { created: boolean }. Throws FlowDefinitionError for a flow not defined on this instance, ValidationError for a bad or reserved key or an input with a NUL character (\u0000, which Postgres cannot store), PayloadTooLargeError for oversize input.

signal

signal(target: SignalTarget, name: string, payload?: unknown): Promise<SignalResult>
type SignalTarget = string | { flow: string | AnyFlow; key: string; tenant?: string }
interface SignalResult { runId: string; signalId: string; woke: boolean }

Stores a signal for the run with that id, or for the run of flow with idempotency key. payload defaults to true and is limited to 16 KB. woke is true when the run was waiting for this name and is now due; it continues on the next tick(). Throws RunNotFoundError, FlowDefinitionError (target by flow and key, flow not defined), ValidationError (also for a payload with a NUL character), PayloadTooLargeError, or LimitExceededError (1,000 unconsumed signals already buffered).

schedule

schedule<F extends AnyFlow>(flow: F | string, cron: string, options?: ScheduleOptions<FlowInput<F>>): Promise<ScheduleRecord>

Creates or replaces the schedule with this key in the tenant. If the cron, zone and flow are unchanged, the stored next firing time is kept.

ScheduleOptions Type Default Meaning
tz string "UTC" IANA time zone the expression is read in.
input I null Input of every run it starts (64 KB).
key string the flow name Unique per tenant. Use distinct keys to schedule one flow several times.
tenant string instance tenant Required on a cross-tenant instance.
enabled boolean true A disabled schedule never fires.

Throws InvalidCronError for a bad expression or zone.

unschedule

unschedule(key: string, options?: { tenant?: string }): Promise<boolean>

Deletes the schedule. false when it did not exist. Runs it already started are not affected.

tick

tick(options?: TickOptions): Promise<TickResult>

Releases expired leases, fires due schedules, then claims and executes due runs until none is left. Only runs and schedules of flows defined on this instance are touched. Returns immediately when no flow is defined. Never throws for a run’s failure; problems are reported in the result.

TickOptions Type Default Meaning
concurrency number 4 Runs executed in parallel.
leaseMs number 60000 Lease length. A runner that dies loses its runs after this long.
tenant string \| null instance tenant null serves every tenant (cross-tenant instances only).
owner string instance owner Lease owner for this tick.
maxRuns number no limit Stop after executing this many runs. Each run executes at most once per tick either way.
schedules boolean true Fire due schedules first.
TickResult field Meaning
scheduled runs created by schedules in this tick
swept expired leases released before claiming
claimed runs claimed and executed
completed, failed, parked outcomes of the executed runs
lost runs whose lease was lost during execution; nothing more was written
cancelled runs cancelled while this tick executed them
deferred runs that could not be decrypted and were released for 5 minutes (onDecryptionError: "retry"); each is also in errors
errors Array<{ runId: string \| null; error: string }>: store errors (sweep, schedule lookup, claim), schedule errors (a schedule that cannot be decrypted is reported as schedule "<key>" (<id>): DecryptionError: ... and the other schedules still fire), deferred runs. tick itself does not throw on a store error.
runs ExecutionOutcome[]: { runId, flow, status, error? } per executed run

ExecutionStatus is "completed" | "failed" | "parked" | "lost" | "cancelled" | "deferred" | "error". An error outcome means the store failed; the lease is left to expire and a later tick resumes the run. A write the database refuses as data (SQLSTATE class 22) is not an outage: it fails that run (outcome failed) instead. A stored value that cannot be decrypted (DecryptionError) follows onDecryptionError: by default ("retry") the run is released for 5 minutes with its attempts untouched (outcome deferred), and it fails once it has not been decryptable for 24 hours; with "fail" it fails at once.

get

get(runId: string): Promise<RunRecord | null>

The run, or null when it does not exist in this tenant.

list

list(options?: ListOptions): Promise<RunPage>
interface RunPage { runs: RunRecord[]; nextCursor: string | null }

Runs, newest first (createdAt, then id, descending), with keyset paging.

ListOptions Type Meaning
flow string \| AnyFlow Only this flow.
status RunStatus \| RunStatus[] Only these statuses.
key string Only the run with this idempotency key.
tenant string \| null null lists every tenant (cross-tenant instances only).
limit number Page size, a positive integer. Without it, every matching run is returned in one page.
cursor string The nextCursor of the previous page.

nextCursor is null on the last page. A cursor that was not produced by list throws ValidationError. Keyset paging is stable while new runs are created.

history

history(runId: string): Promise<RunHistory | null>
interface RunHistory {
  run: RunRecord
  timeline: TimelineEntry[]
  steps: StepRecord[]
  signals: SignalRecord[]
}

timeline is time-ordered and summarized to 8 KB per value (see History timeline). steps is the raw step log in insertion order; signals every signal in arrival order, consumed or not. Results of sensitive steps appear as "[sensitive]" in both timeline and steps.

cancel

cancel(runId: string): Promise<RunRecord | null>

Cancels a pending, sleeping, waiting or running run at once. A runner executing it stops at its next write and reports cancelled. Returns the cancelled run, or null when the run is missing or already terminal. Emits run.cancelled.

retryNow

retryNow(runId: string): Promise<RunRecord | null>

For a failed run: back to pending, attempts reset, and when the run failed on a step, the cursor is moved back so that step runs again from attempt one. For a pending, sleeping or waiting run: made due now (a sleep re-parks until its recorded wake time; a wait checks for a signal again). Returns null for completed, cancelled, running or missing runs.

migrate

migrate(): Promise<void>

Creates the tables and indexes if missing. Safe on every boot and from several processes at once.

The flow context f

type FlowFn<I, O> = (f: FlowContext, input: I) => Promise<O> | O

interface FlowContext {
  readonly runId: string
  readonly tenant: string
  readonly flow: string
  readonly key: string | null
  step<T>(name: string, fn: () => Promise<T> | T, options?: StepOptions): Promise<T>
  sleep(duration: Duration): Promise<void>
  waitForSignal<T = unknown>(name: string, options?: WaitOptions): Promise<T | null>
  once(key: string): Promise<boolean>
  log(message: string): Promise<void>
}

Await every call before making the next one. Code outside these calls must be deterministic.

Method Behaviour
step(name, fn, options?) Runs fn once per position and records its JSON result (64 KB, no NUL characters). On replay returns the recorded result. Each attempt is counted on the run before the body runs, so an attempt that never reports back (crash, lost lease, rejected write) counts too. A failure past its retry policy throws StepFailedError into the flow. name: up to 200 characters, not starting with $.
sleep(duration) Parks the run until the time passes (or the Date).
waitForSignal(name, options?) Returns the payload of the oldest eligible signal of that name, parking until one arrives; null after timeout.
once(key) true for the first run in the tenant to claim key, and again for that run on replay; false for every other run.
log(message) Appends a redacted line of up to 1 KB (NUL characters removed) to the history. Not repeated on replay. Line 10,001 of a run fails the run, even if the flow catches errors.

StepOptions:

Field Type Meaning
retry Partial<RetryPolicy> Overrides the flow’s and the default policy, field by field.
sensitive boolean The result is stored only encrypted and is not redacted; history and events show "[sensitive]". Requires encryption; without it the body does not run and the run fails with EncryptionRequiredError.

WaitOptions:

Field Type Meaning
timeout Duration Return null when no signal arrived by then. Only signals created by the deadline count.
acceptLate boolean Also consume a signal flagged late (it arrived after an earlier wait of this name timed out). Default false.

Flow and helpers

interface Flow<I = unknown, O = unknown> { readonly name: string; readonly fn: FlowFn<I, O>; readonly retry?: Partial<RetryPolicy> }
type AnyFlow = Flow<any, any>
type FlowInput<F> = F extends Flow<infer I, any> ? I : never
type FlowOutput<F> = F extends Flow<any, infer O> ? O : never
interface DefineFlowOptions { retry?: Partial<RetryPolicy> }
function createFlow<I, O>(name: string, fn: FlowFn<I, O>, options?: DefineFlowOptions): Flow<I, O>

createFlow builds a frozen flow object without registering it; defineFlow is createFlow plus registration. Registering the same object on two instances is allowed.

Records and statuses

type RunStatus = "pending" | "running" | "sleeping" | "waiting" | "completed" | "failed" | "cancelled"
const TERMINAL_STATUSES: readonly RunStatus[] // ["completed", "failed", "cancelled"]
function isTerminal(status: RunStatus): boolean

type StepStatus = "completed" | "failed" | "retrying" | "parked" | "log"
const JOURNAL_STATUSES: readonly StepStatus[] // ["completed", "failed"]

RunRecord (a steady_runs row): id, tenant, flow, key (or null), status, input, output, error (stored error text of a failed run), cursor (journal entries so far), wakeAt, waitingSignal, leaseUntil, leaseOwner, attempts (attempts started for the step at the cursor, recorded before each body runs; 0 once the step is recorded), lastTimeoutAt (per signal name, the ISO deadline of the last wait of that name that timed out), createdAt, updatedAt, completedAt, scheduleId.

StepRecord (a steady_steps row): id, runId, seq (position, 0 based), name, attempt, status, startedAt, finishedAt, result, error. Internal operations use reserved names: $sleep, $signal:<name>, $once:<key>, $log.

SignalRecord (a steady_signals row): id, runId, name, payload, late, createdAt, consumedAt.

ScheduleRecord (a steady_schedules row): id, tenant, flow, cron, tz, input, key, nextAt, lastRunId, enabled, createdAt, updatedAt.

Events

type EventHook = (event: SteadyEvent) => void | Promise<void>

Every event has type, at (instance clock), tenant, runId and flow. Values are redacted and summarized to 8 KB; errors are the stored Name: message text.

type Interface Extra fields When
run.started RunStartedEvent key, input, scheduleId A run was created by start or a schedule (not when start returned an existing run).
step.started StepStartedEvent step, seq, attempt A step body is about to run (not on replay).
step.completed StepCompletedEvent step, seq, attempt, durationMs, result A result was recorded.
step.failed StepFailedEvent step, seq, attempt, durationMs, error, willRetry, retryAt An attempt failed.
run.parked RunParkedEvent reason (sleep, signal, retry), wakeAt, signal The run released its lease.
run.completed RunCompletedEvent output The flow returned.
run.failed RunFailedEvent error The run failed (dead letter).
run.cancelled RunCancelledEvent none cancel stopped the run.

SteadyEvent is the union of these interfaces. The hook is called synchronously and not awaited; a throw or rejection is swallowed and never affects a run.

History timeline

TimelineEntry = TimelineStep | TimelinePark | TimelineLog | TimelineSignal, ordered by time.

Kind Fields
step op (step, sleep, wait, once), seq, name (step name, signal name, once key, or "sleep"), attempt, status (completed, failed, retrying), at, startedAt, finishedAt, durationMs, result (for a wait { payload, signalId } or { timedOut: true }), error
park seq, reason (sleep, signal), signal, at, until
log seq, at, message
signal id, name, at, payload, late, consumedAt

Errors

All errors extend SteadyError (which extends Error; name is the class name).

Error Thrown when Fields
SteadyError Base class; also bad options (missing db, bad encryption key, invalid retry policy).  
ValidationError A name, key, run id, list limit or cursor is invalid, a key uses the reserved schedule: prefix, or a payload contains a NUL character. Nothing was stored.  
FlowDefinitionError A flow is defined twice, or is not defined on this instance when started, scheduled or signalled by key.  
FlowUsageError The flow started an operation while another was in flight. The run fails.  
ReplayMismatchError The flow code no longer matches the journal. The run fails. seq, expected, actual
StepFailedError Thrown into the flow when a step’s retries are exhausted or the error is non-retryable. step, attempts, errorText, cause (first run only)
FlowCancelledError Reported as the error of a cancelled tick outcome. runId
RunNotFoundError signal found no run for the id or (flow, key). target
TenantAccessError A call named a tenant this instance may not touch, or tenant: "*" lacks allowCrossTenant.  
PayloadTooLargeError A payload is over its limit. Nothing was stored. kind, bytes, limit
LimitExceededError A per-run cap was reached (operations, log lines, buffered signals). kind, limit
InvalidDurationError A duration could not be parsed. input
InvalidCronError A cron expression or time zone is invalid, or never matches.  
DecryptionError Stored data could not be decrypted (wrong or missing key, altered data, a short tag or an IV that is not 12 bytes), or, with a key, a stored value is not encrypted and allowPlaintext is off. In a tick it affects that run only: released for 5 minutes (outcome deferred) or failed, per onDecryptionError.  
EncryptionRequiredError A { sensitive: true } step ran on an instance without encryption. The body did not run; the run fails. step

Limits and validation

const LIMITS: {
  inputBytes: 65536; resultBytes: 65536; signalBytes: 16384; logBytes: 1024; errorBytes: 1024
  summaryBytes: 8192; maxSteps: 10000; maxLogLines: 10000; maxBufferedSignals: 1000
}
const NAME_PATTERN: RegExp // /^[a-z0-9][a-z0-9._-]{0,63}$/, flow and signal names
const MAX_KEY_LENGTH: 200   // keys, once keys, schedule keys, step names, run ids, tenants
function summarize(value: unknown, limit?: number): unknown
interface TruncatedValue { $truncated: true; bytes: number; preview: string }

summarize returns the value when its JSON fits in limit bytes (default 8 KB), otherwise a TruncatedValue whose own JSON fits. It is what history() and onEvent use.

Redaction and encryption

interface RedactOptions { patterns?: RegExp[]; replacement?: string }
const DEFAULT_REDACT_PATTERNS: readonly RegExp[]
// one pattern: the normalized name is, or ends with, a secret word (plural too), unless it ends
// with an entry of DEFAULT_REDACT_ALLOW
const DEFAULT_REDACT_ALLOW: readonly string[]
// ["tokens", "token_count", "input_tokens", "output_tokens", "max_tokens", "cookie_consent", "password_reset_required"]
const REDACTED: "[redacted]"
function createRedactor(options: RedactOptions | false | undefined): Scrubber
interface Scrubber { value(value: unknown): unknown; text(text: string): string }
interface EncryptionOptions {
  key: string              // 32 bytes, base64 (openssl rand -base64 32)
  allowPlaintext?: boolean // migration mode: also read values written before encryption was on
}

Redaction replaces values whose property name matches a pattern, at any depth, in run and schedule inputs, step results, outputs and signal payloads; in texts (errors, log lines) it masks name=value, name: value and "name":"value" pairs with a secret-looking name, and Bearer or Basic credentials. Every pattern is tested against the name as written and against its normalized form: camelCase humps and separators become _, letters lowercase (X-Api-Key and apiKey become x_api_key and api_key). The default matches a name that is, or ends with as its final word(s), password, passwd, secret, token, api key, private key, authorization, cookie or credential (and plurals), so clientSecret, accessToken and set-cookie are redacted while tokenExpiresAt, passengers, passport, keyword, dateKey and turkeyHotels are kept. Names ending with an entry of DEFAULT_REDACT_ALLOW (inputTokens, max_tokens, tokenCount, cookieConsent, …) are kept too. See the table in Security. patterns replaces the default list (spread DEFAULT_REDACT_PATTERNS to extend it). It runs before storage, so the flow receives the redacted value too. createRedactor is the function the instance uses; call it to preview what will be stored.

Encryption covers run input and output, step results, signal payloads and schedule inputs, with a fresh IV per value and associated data binding each value to its row and column. Names, keys, statuses, timestamps and error texts stay plaintext (redacted). See Security.

Durations, retries, cron

type Duration = string | number | Date
function parseDuration(input: string | number): number           // milliseconds
function resolveInstant(duration: Duration, now: Date): Date      // a Date is returned as is

interface RetryPolicy {
  maxAttempts: number      // total attempts including the first; 1 means no retry
  backoffMs: number        // delay before the second attempt, doubling after that
  maxBackoffMs: number     // cap
  nonRetryable?: (error: unknown) => boolean
}
const DEFAULT_RETRY_POLICY: Readonly<RetryPolicy> // { maxAttempts: 3, backoffMs: 1000, maxBackoffMs: 300000 }
function resolveRetryPolicy(...layers: Array<Partial<RetryPolicy> | undefined>): RetryPolicy
function backoffDelay(policy: RetryPolicy, failedAttempt: number): number // backoffMs * 2^(n-1), capped

function parseCron(expression: string): CronExpression
function nextAt(cron: string | CronExpression, from: Date, tz?: string): Date // strictly after `from`
interface CronExpression { readonly source: string; /* parsed fields */ }

Duration strings: "500ms", "30s", "20m", "2h", "2d", "1w", combinations ("1h30m", "1d 2h"), or digits only (milliseconds). Cron: five fields, *, values, ranges, lists, steps, JAN-DEC, SUN-SAT (0 and 7 are Sunday), macros @yearly, @annually, @monthly, @weekly, @daily, @midnight, @hourly. When both day of month and day of week are restricted, a day matches if either matches (classic cron).

Storage

interface SqlAdapter { query<T = Record<string, unknown>>(sql: string, params: unknown[]): Promise<T[]> }
function postgresStore(db: SqlAdapter): StoreAdapter
function migrate(db: SqlAdapter | StoreAdapter): Promise<void>
const MIGRATION_STATEMENTS: readonly string[] // one idempotent statement per entry
const STEADY_SQL: string                      // the same, as one text (equals sql/steady.sql)
function memoryStore(options?: MemoryStoreOptions): MemoryStore
interface MemoryStoreOptions { yieldEachCall?: boolean } // yield to the event loop per call, default true
interface MemoryStore extends StoreAdapter { reset(): void }
const ONCE_FLOW: "$once"

SqlAdapter.query runs one statement with $1, $2, ... placeholders and returns plain row objects. Steady never sends more than one statement per call and never needs a transaction.

memoryStore() keeps everything in process memory. It is for tests, examples and local experiments; data is gone when the process exits.

StoreAdapter is the storage contract the engine uses (one atomic operation per method): migrate, createRun, getRun, findRunByKey, listRuns, updateRun, claimDue, sweepExpired, heartbeat, commit, listSteps, addSignal, findSignal, listSignals, claimOnce, upsertSchedule, getSchedule, listSchedules, deleteSchedule, dueSchedules, advanceSchedule. Its parameter types are exported too: NewRun, NewStep, NewSignal, RunPatch, CommitWrite, FindSignalOptions, RunFilter, SweepOptions, ClaimOptions, ScheduleUpsert. Every method takes the tenant and must touch only that tenant’s rows. Writing your own store is possible but rarely needed; the contract tests in src/store/contract.ts show what it must do.

Adapters and Drizzle

import { pgAdapter } from "@solustiq/steady/pg"            // pgAdapter(pool: PgQueryable): SqlAdapter
import { postgresAdapter } from "@solustiq/steady/postgres" // postgresAdapter(sql: PostgresJsSql): SqlAdapter
import { neonAdapter } from "@solustiq/steady/neon"         // neonAdapter(urlOrNeonFn: string | NeonQueryFunctionLike): SqlAdapter

None of them imports a driver at load time; the drivers are optional peer dependencies.

@solustiq/steady/drizzle exports the four tables as Drizzle pgTable definitions (steadyRuns, steadySteps, steadySignals, steadySchedules) mirroring sql/steady.sql, for projects that manage migrations with drizzle-kit (export * from "@solustiq/steady/drizzle" in your schema file). Requires drizzle-orm.