Operations
How to run Steady in production: when to tick, how leases behave, scaling out, keeping the tables small, watching it with SQL, and locking it down with the optional role.
Tick cadence
Nothing happens without tick(): sleeps do not end, schedules do not fire, retries do not run,
signalled runs do not continue. Call it on a fixed cadence from one or more places.
- Every minute is the usual choice and matches cron resolution. Sleeps, retry backoffs and wait timeouts resolve on the first tick at or after their time, so a one-minute cadence means “up to a minute late”.
- A tick returns when no due run is left (or after
maxRunsruns). A busy tick can last longer than the interval; overlapping ticks are safe, because leases keep each run in one place. concurrency(default 4) is the number of runs one tick executes in parallel within the process. Raise it when steps mostly wait on I/O; keep it low when they use CPU or when your connection pool is small (each concurrent run sends its own statements through the pool).- To continue a run right after an event (a signal from a handler), call
tick({ maxRuns: 1 })in that handler; the regular cadence picks up anything else.
Where to call it:
| Host | Pattern |
|---|---|
| Vercel, Netlify, Cloudflare | a cron-triggered route that authenticates the cron (for example Authorization: Bearer $CRON_SECRET) and calls tick() |
| Container, VM | setInterval(() => steady.tick().catch(log), 60_000) in the app or a small worker process |
| AWS | an EventBridge schedule invoking a Lambda that calls tick() |
| Local | the same loop in your dev server |
On serverless, bound a tick by the function’s time limit: set maxRuns, and keep individual step
bodies well under the limit. A function killed mid-step loses its lease after leaseMs; the run is
then resumed by a later tick and the interrupted step body runs again (at-least-once). The killed
attempt counts against the step’s maxAttempts (each attempt is recorded on the run before its
body starts, one extra write per step attempt), so a step that always outlives the function limit
dead-letters instead of being retried forever.
Leases
tick({ leaseMs })(default 60,000) is how long a claimed run is reserved for its runner.- While a run executes, the runner extends the lease every
leaseMs / 3(at most once a second). Once a lease has expired or been taken over, the old runner cannot write anything for that run: its next write is refused and the tick reports the run aslost. - If a runner dies, its runs stay
runninguntil the lease expires. The next tick anywhere releases them (TickResult.swept) and executes them again from the journal. - Choose
leaseMslarger than the longest pause you expect in a healthy runner (garbage collection, event loop blocked by CPU work), and short enough that a dead runner’s work resumes soon enough. One to five minutes suits most workloads. - Lease times use the runner’s clock, not the database clock. Run NTP on every runner host; a runner whose clock is minutes off can claim runs early or treat live leases as expired.
Running many runners
Any number of processes may tick against the same database:
- Claims use
FOR UPDATE SKIP LOCKEDinside a single statement, so runners never wait on each other’s locks and never get the same run. The claim order is served by the partial indexsteady_runs_due, which covers live runs only (pending, sleeping, waiting, running), so it stays small however many finished runs the table keeps.migrate()creates it; on an existing database, runsql/steady.sqlagain (every statement isIF NOT EXISTS). - A runner only claims runs and fires schedules of flows it has defined. Deploy the same flow
definitions to every runner, or use this on purpose to route flows to dedicated workers (a worker
that defines only
video-transcodenever touches other runs). - During a rolling deploy, old and new code tick side by side. If a deploy changes a flow’s steps,
a run resumed by new code after old code recorded steps may hit
ReplayMismatchError. Keep step names and order stable for in-flight runs, or add a new flow name for the new shape and let old runs finish. - Every runner should have a distinct
owner(the default is a random id per instance) so leases can tell them apart. - Per-tenant runners: an instance only serves its tenant. To serve many tenants from one process,
create one instance per tenant, or one cross-tenant instance (
tenant: "*",allowCrossTenant: true) whosetick()serves all of them.
Retention
Steady never deletes anything. Completed runs, their steps and signals stay until you remove them.
Deleting a run deletes its steps and signals (ON DELETE CASCADE).
Before you delete, know what a row still does:
- A run with an idempotency key blocks a second
startwith that key. Delete it and the key is free again. once(key)claims are rows insteady_runswithflow = '$once'and statuscompleted. Deleting them makesoncereturntrueagain for those keys. Exclude them unless that is what you want.
Without the hardening script, a periodic delete is enough:
DELETE FROM steady_runs
WHERE status IN ('completed', 'cancelled')
AND flow <> '$once'
AND completed_at < now() - interval '90 days';
With sql/rls.sql installed, a trigger refuses UPDATE and DELETE on
steady_steps for every role, the owner included, and that also blocks the cascade. Run retention
as the table owner and switch the trigger off for that transaction only:
BEGIN;
ALTER TABLE steady_steps DISABLE TRIGGER steady_steps_append_only;
DELETE FROM steady_runs
WHERE status IN ('completed', 'cancelled')
AND flow <> '$once'
AND completed_at < now() - interval '90 days';
ALTER TABLE steady_steps ENABLE TRIGGER steady_steps_append_only;
COMMIT;
ALTER TABLE ... DISABLE TRIGGER takes an ACCESS EXCLUSIVE lock on steady_steps until
COMMIT: every runner, every history() and every read of that table waits for the whole delete.
Run it in a maintenance window (or with ticks paused), and delete in batches, one short transaction
each (add AND id IN (SELECT id ... LIMIT 5000)), if there is a lot to remove. Keep failed runs longer than completed ones: they are your dead
letters.
Observability
Events
createSteady({ onEvent }) receives run.started, step.started, step.completed,
step.failed, run.parked, run.completed, run.failed and run.cancelled with redacted,
summarized payloads. Forward them to your logger or metrics:
createSteady({
db,
onEvent(event) {
if (event.type === "run.failed") logger.error({ runId: event.runId, flow: event.flow, error: event.error }, "steady run failed")
if (event.type === "step.completed") metrics.histogram("steady.step.ms", event.durationMs, { flow: event.flow, step: event.step })
},
})
The hook is not awaited and a failure in it is ignored, so it cannot slow down or break runs.
Tick results
Log the TickResult of each tick. errors lists store and schedule errors; a steady stream of
lost means leases expire under running steps (raise leaseMs, or find what blocks the event loop).
A non-zero deferred (with DecryptionError entries in errors) means this runner cannot decrypt
the runs it claims: check that every runner has the same encryption.key. Those runs are released
for 5 minutes at a time and fail after 24 hours (onDecryptionError), so fix the key within a day.
Turning on encryption
- Deploy every runner with
encryption: { key, allowPlaintext: true }. - Call
steady.schedule(flow, cron, { key, input, tz })again for every schedule (list them with the “schedules” query below, or from your code). This rewrites each schedule encrypted. Schedules never finish, so without this step they stay plaintext forever. - Wait until no run started before step 1 is live:
SELECT count(*) FROM steady_runs WHERE tenant = 'acme' AND created_at < '<switch time>' AND status NOT IN ('completed', 'failed', 'cancelled'); - Remove
allowPlaintextand deploy again. A schedule that still cannot be decrypted is reported inerrorsasschedule "<key>" (<id>): DecryptionError: ...; callschedule()for it again.
SQL
Steady’s tables are plain tables; query them directly. Replace 'acme' with your tenant. Flows whose
name starts with $ are internal ($once).
Runs by flow and status:
SELECT flow, status, count(*)
FROM steady_runs
WHERE tenant = 'acme' AND flow NOT LIKE '$%'
GROUP BY flow, status
ORDER BY flow, status;
Backlog: runs that are due but not picked up (no runner, or runners cannot keep up):
SELECT flow, count(*) AS overdue, min(coalesce(wake_at, created_at)) AS oldest_due
FROM steady_runs
WHERE tenant = 'acme'
AND status IN ('pending', 'sleeping', 'waiting')
AND coalesce(wake_at, CASE WHEN status = 'pending' THEN created_at END) < now() - interval '5 minutes'
GROUP BY flow;
Runs held by a dead runner (lease expired, not yet swept):
SELECT id, flow, lease_owner, lease_until
FROM steady_runs
WHERE tenant = 'acme' AND status = 'running' AND lease_until < now();
Dead letters of the last day:
SELECT id, flow, "key", error, completed_at
FROM steady_runs
WHERE tenant = 'acme' AND status = 'failed' AND completed_at > now() - interval '1 day'
ORDER BY completed_at DESC;
Slowest steps (completed, last 7 days):
SELECT r.flow, s.name, count(*) AS runs,
percentile_cont(0.5) WITHIN GROUP (ORDER BY extract(epoch FROM s.finished_at - s.started_at)) AS p50_s,
percentile_cont(0.95) WITHIN GROUP (ORDER BY extract(epoch FROM s.finished_at - s.started_at)) AS p95_s
FROM steady_steps s JOIN steady_runs r ON r.id = s.run_id
WHERE s.tenant = 'acme' AND s.status = 'completed' AND s.name NOT LIKE '$%'
AND s.started_at > now() - interval '7 days'
GROUP BY r.flow, s.name
ORDER BY p95_s DESC
LIMIT 20;
Retry hotspots:
SELECT r.flow, s.name, count(*) AS retries
FROM steady_steps s JOIN steady_runs r ON r.id = s.run_id
WHERE s.tenant = 'acme' AND s.status = 'retrying' AND s.started_at > now() - interval '1 day'
GROUP BY r.flow, s.name
ORDER BY retries DESC;
Late signals (arrived after a wait timed out, never consumed):
SELECT g.run_id, r.flow, g.name, g.created_at
FROM steady_signals g JOIN steady_runs r ON r.id = g.run_id
WHERE g.tenant = 'acme' AND g.late AND g.consumed_at IS NULL
ORDER BY g.created_at DESC;
Schedules that should have fired (no runner defines the flow, or no tick runs):
SELECT "key", flow, cron, tz, next_at
FROM steady_schedules
WHERE tenant = 'acme' AND enabled AND next_at < now() - interval '5 minutes';
With encryption on, input, output, result and payload columns hold ciphertext envelopes;
use steady.history(runId) to read values. Status, names, keys, timestamps and errors stay
queryable.
The least-privilege role (sql/rls.sql)
The optional sql/rls.sql script, run once as the table owner after the schema
(it is idempotent), adds:
- Role
steady_app(NOLOGIN) withSELECT,INSERT,UPDATEon the four tables andDELETEonsteady_schedulesonly (unscheduleneeds it). No DDL, noTRUNCATE, no other tables. - Row-level security on the four tables: a row is visible and writable only when its
tenantequals the connection settingsteady.tenant. A connection that has not set it sees nothing and writes nothing. - The append-only trigger on
steady_steps(see Retention).
psql "$DATABASE_URL" -f node_modules/@solustiq/steady/sql/rls.sql
Let your login role use it and set the tenant per connection, to the same value as
createSteady({ tenant }):
GRANT steady_app TO my_app_login;
import { Pool, type PoolClient } from "pg"
import type { SqlAdapter } from "@solustiq/steady"
const pool = new Pool({ connectionString: process.env.DATABASE_URL })
const scoped = new WeakSet<PoolClient>()
// Every statement runs on a connection that is known to be scoped. If scoping fails, the
// connection is destroyed and the statement is not sent (fail closed): an unscoped connection
// of a login role that owns the tables would bypass row-level security.
const db: SqlAdapter = {
async query(text, params) {
const client = await pool.connect()
if (!scoped.has(client)) {
try {
await client.query("SET ROLE steady_app")
await client.query("SELECT set_config('steady.tenant', $1, false)", ["acme"])
scoped.add(client)
} catch (error) {
client.release(error as Error) // destroys the connection
throw error
}
}
try {
return (await client.query(text, params)).rows
} finally {
client.release()
}
},
}
const steady = createSteady({ db, tenant: "acme" })
Other ways to set it: the connection string
(?options=-c%20steady.tenant%3Dacme%20-c%20role%3Dsteady_app, for drivers that pass startup
options), or role defaults (ALTER ROLE acme_worker SET steady.tenant = 'acme'), which is the one
that works with Neon’s HTTP driver (a new session per query). Use session scope
(set_config(..., false)), never SET LOCAL: Steady sends single statements outside explicit
transactions. Run migrate() with the owner role, not steady_app, which cannot create tables.
A cross-tenant instance (tenant: "*") needs a role that bypasses row-level security, such as the
owner; keep it for administration. More detail: sql/README.md.