Workflow SDK
Run the Workflow SDK on Supabase with a World over Postgres and Supabase Queues, and start runs, resume hooks and protect routes as the signed-in user.
The Workflow SDK (workflow) needs a World: the storage and queue its runs,
steps, hooks and events live in. better-supabase/workflow-sdk/world is a
World on your Supabase database. Its tables sit in a workflow schema that
only the service role reads, its messages wait in a
jobs queue, and every run is copied into the
workflows block's workflow_runs, so members
list and follow runs through RLS. better-supabase/workflow-sdk has the
helpers that start runs and resume hooks as the signed-in user.
better-supabase add workflow-sdk # adds workflows and jobs as well
pnpm add workflow @workflow/world @workflow/world-postgres pgThe world entry imports pg and Node built-ins, so it runs on Node, not on
edge runtimes. The helpers in better-supabase/workflow-sdk import only
workflow.
Selecting the World
import { withWorkflow } from "workflow/next";
export default withWorkflow(nextConfig);WORKFLOW_TARGET_WORLD=better-supabase/workflow-sdk/world
SUPABASE_DB_URL=postgresql://postgres:postgres@127.0.0.1:54322/postgresThe entry's default export is createWorld(), which reads its options from
the environment, so the SDK and tools that select a World by package name
load it without code. To build one yourself, call createSupabaseWorld:
import { createSupabaseWorld } from "better-supabase/workflow-sdk/world";
export const world = createSupabaseWorld({
connectionString: process.env.SUPABASE_DB_URL,
delivery: "pg_net",
});| Variable | Option | Default |
|---|---|---|
WORKFLOW_POSTGRES_URL, SUPABASE_DB_URL, DATABASE_URL | connectionString | the first one set |
WORKFLOW_DELIVERY | delivery | poll |
WORKFLOW_FLOW_URL | flowUrl | WORKFLOW_LOCAL_BASE_URL or http://localhost:$PORT, plus /.well-known/workflow/v1/flow |
WORKFLOW_DELIVERY_SECRET | deliverySecret | the Vault secret workflow_delivery_secret |
WORKFLOW_ENCRYPTION_KEYS | encryptionKeys | the Vault secret workflow_encryption_keys (see Encryption) |
WORKFLOW_POSTGRES_CONNECTION | connection | transaction on port 6543, else session |
WORKFLOW_ENCRYPTION_KEY | encryptionKey | the Vault secret workflow_encryption_key |
WORKFLOW_DELIVERY_HEADERS | deliveryHeaders | the Vault secret workflow_delivery_headers, else none |
WORKFLOW_RECOVER_AFTER_SECONDS | recoverAfter | 300 |
WORKFLOW_POSTGRES_SKIP_WORKERS (1 or true) | skipWorkers | off |
WORKFLOW_DELIVERY_QUEUE | queue | workflow_deliveries |
WORKFLOW_QUEUE_NAMESPACE | namespace | none |
WORKFLOW_POSTGRES_WORKER_CONCURRENCY | concurrency | 50 |
WORKFLOW_POSTGRES_POLL_INTERVAL_MS | pollInterval | 250 |
WORKFLOW_POSTGRES_MAX_POOL_SIZE, WORKFLOW_POSTGRES_MAX_CONNECTIONS | maxConnections | 10 |
WORKFLOW_POSTGRES_CONNECTION_TIMEOUT_MS | connectionTimeout | 30000 |
WORKFLOW_POSTGRES_IDLE_TIMEOUT_MS | idleTimeout | 10000 |
WORKFLOW_POSTGRES_STATEMENT_TIMEOUT_MS | statementTimeout | 30000 |
WORKFLOW_POSTGRES_IDLE_IN_TRANSACTION_TIMEOUT_MS | idleInTransactionTimeout | 15000 |
The pool holds at most maxConnections connections. A delivery that finds
them all busy waits up to connectionTimeout for one, so a burst queues
instead of failing. statementTimeout ends a query that runs longer, and
idleInTransactionTimeout ends a transaction left open with no query, so a
stuck worker can't hold row locks. Pass events (betterSupabase.events)
or a logger to see errors of idle pooled connections; without either, the
World logs them to the console. They never throw, so a dropped connection
can't crash the process.
WORKFLOW_POSTGRES_MAX_POOL_SIZE is the name @workflow/world-postgres
reads, and wins when both are set. The base World's job queue variables
(WORKFLOW_POSTGRES_JOB_PREFIX and the graphile settings) are ignored,
because this World runs its own queue. GRAPHILE_WORKER_SCHEMA is the one
exception: the World sets it to workflow when it is unset, so the purge
backstops of zero-retention runs reach workflow.add_job (see
Retention), and warns when it names another schema.
skipWorkers starts the World without delivering: it queues messages but
never claims or posts one, starts no poller, and start() recovers nothing.
Use it for a process that only starts runs and reads them, next to at least
one process that delivers. One message takes at most 73
deliveries before the World gives up on it, the same budget as
@workflow/world-postgres (49 attempts plus 24 retries of the final
write).
The World speaks the @workflow/world protocol in
WORKFLOW_WORLD_PROTOCOL (5.3.0 for workflow 5.7) and stores its tables
in the shape of the @workflow/world-postgres version in
WORLD_POSTGRES_VERSION. It passes the @workflow/world-testing suite.
The conformance job in .github/workflows/verify.yml runs that suite
against the lowest and highest supported peer versions and uploads the
report as an artifact.
Options added with World 5.1
| Option or variable | What it does |
|---|---|
onDeadLetter(letter) | Runs once when a message used up its 73 deliveries and moved to the dead-letter state. |
enableInvoke / WORKFLOW_POSTGRES_ENABLE_INVOKE | Turns on the experimental invoke() delivery of @workflow/world-postgres. Off by default. |
streamFlushIntervalMs / WORKFLOW_POSTGRES_STREAM_FLUSH_INTERVAL_MS | Sets the milliseconds between flushes of buffered stream writes (20 by default, 0 flushes at once). |
createWorld() returns one World per process, so two calls share a pool and
a poller. On a serverless platform (Vercel, AWS Lambda, Netlify) the pool
holds 2 connections by default instead of 10.
Connection modes
The World runs in one of two modes, set with connection or
WORKFLOW_POSTGRES_CONNECTION. A connection string on port 6543 (the
Supabase transaction pooler) selects transaction, anything else selects
session.
| Mode | Streams | Run status and run event feeds |
|---|---|---|
session | LISTEN and NOTIFY wake readers at once | LISTEN, with a 1 second backstop |
transaction | readers poll workflow_stream_chunks every streamPollInterval milliseconds (100 by default) | the runtime polls |
The transaction pooler accepts LISTEN without delivering a notification, so
transaction mode never relies on it. Stream readers keep the same offsets
in both modes: a positive start index skips chunks, a negative one counts
back from the chunks present at the first read. Setting connection: "session" on a pooled URL logs a warning, because streams would hang. In
transaction mode the underlying World still holds one idle LISTEN
connection that nothing waits on.
Messages carry the
x-vqs-message-delivery-count and x-vqs-message-created-at headers that
@workflow/world-postgres sends, and queueBatch writes a batch in one
statement. world.start() calls assertWorldMigrations(), which compares
the installed drizzle migrations with the hashes in
WORLD_POSTGRES_MIGRATIONS and throws a MigrationDrift error when they
differ.
openHooks() returns each hook's metadata decoded from metadata_cbor
when the run key can open it, and falls back to the metadata column
otherwise. Payloads sealed for another recipient stay closed.
Rolling out 5.1
Upgrade the SQL module first (workflow-sdk version 4 converts the World
timestamps to timestamptz), then deploy the app. Runs started on
workflow 5.2 with protocol 5.0 keep running; new runs use spec version 8. Don't run old and new app
versions against the same database for longer than one deploy.
Rolling out 5.7
workflow 5.7 and eve 1.2 need @workflow/world 5.3 and
@workflow/world-postgres 5.4. Upgrade the SQL module first
(better-supabase upgrade), then deploy the app. workflow-sdk version 6 adds
workflow.workflow_run_delivery_leases (world-postgres migration 0031) and
workflow_runs.wake_pending (migration 0032). Runs that exist before the
upgrade start with wake_pending set, so startup recovery lets their next
completed delivery decide; new runs start clear. assertWorldMigrations
throws on a @workflow/world-postgres older than 5.4.0.
better-supabase/workflow-sdk/world/package.json is a stub manifest that
carries the @workflow/world range. eve's startup check reads it to compare
the Workflow line it bundles with the World's, so a mismatch fails at startup
instead of at the first run.
Rolling out 5.7.1
workflow 5.7.1 and eve 1.3 come with @workflow/world-postgres 5.4.1,
which adds no table but writes a purge backstop when a zero-retention run
ends. Upgrade the SQL module first (workflow-sdk version 9 adds
workflow.workflow_purge_backstops, workflow.add_job and
workflow_purge_backstops()), then deploy the app. A 5.4.1 World on a
version 8 database fails the terminal write of a zero-retention run, because
workflow.add_job does not exist yet.
Rolling out 5.2
workflow 5.5 needs @workflow/world and @workflow/world-postgres 5.2.
Upgrade the SQL module first (workflow-sdk version 5 adds the
workflow.workflow_job_lock_holders table of world-postgres migration 0030,
closed to the API roles), then deploy the app. The World declares
queueAuthMode: "skip": the flow route checks the HMAC signature of every
delivery itself, so the runtime adds no queue key check. The World
creates spec 8 runs and ignores WORKFLOW_SPEC_VERSION=9: the pgmq queue
runs a run's messages in parallel and takes no run delivery lease, so it
declares neither capabilities.maxConcurrency nor capabilities.inBandFence
(ADR 1106).
Delivery
The SDK hands each step and each workflow turn to the queue, and the queue
posts it to the flow route that withWorkflow adds.
| Mode | Who posts | Use it on |
|---|---|---|
poll (default) | the World, in the process that queues: it claims jobs and posts them | a server, a container, next dev |
pg_net | dispatch_workflow_deliveries() on a pg_cron schedule, through pg_net | serverless hosts with no long-running process |
vercel-queue | Vercel Queues, which call the flow route on Vercel | an app on Vercel, where pg_net can't reach the route |
For pg_net, set blocks["workflow-sdk"].options.delivery to
pg_net (the data file then schedules the dispatcher every
options.schedule, 1 seconds by default) and store the route and a
secret in Vault:
select vault.create_secret('https://app.example.com/.well-known/workflow/v1/flow', 'workflow_flow_url');
select vault.create_secret(encode(extensions.gen_random_bytes(32), 'hex'), 'workflow_delivery_secret');In poll mode, the first message a process queues starts its poller, and
world.start() also queues the runs that were active when the last
process stopped. Call it once at startup, for example from
instrumentation.ts, and only where a process stays up: on a serverless
host every instance would start a poller, so use pg_net there and call
start() in next dev only.
Extra headers
A host in front of the flow route may need a header on every delivery, for
example Vercel's x-vercel-protection-bypass. Pass deliveryHeaders (or a
JSON object in WORKFLOW_DELIVERY_HEADERS), or store the JSON object in the
Vault secret workflow_delivery_headers. Poll mode and the pg_net
dispatcher both add these headers and never replace x-bsb-signature or the
other headers the World sets. A secret that is not a JSON object makes the
dispatcher fail with the hint WORKFLOW_DELIVERY_UNCONFIGURED.
A route may sit below a path prefix: registerRoute and the default routes
keep the part of flowUrl that comes before /.well-known/workflow/v1/flow.
Delivery on Vercel
pg_net posts from the database, which can't reach a Vercel deployment that
sits behind protection or has no stable URL. Set delivery: "vercel-queue"
(or WORKFLOW_DELIVERY=vercel-queue) to send each message with
@vercel/queue instead, and install it as an optional peer. The World then
claims no jobs and starts no poller, and the cron job is not scheduled.
export const world = createSupabaseWorld({ delivery: "vercel-queue" });- A message goes to the topic that matches its queue name, with every
character outside
A-Za-z0-9_-replaced by-. The Workflow SDK builders write the consumer trigger for the topics__wkf_workflow_*(steps share the workflow topic sinceworkflow5), so no extra configuration is needed. - The message id is the idempotency key, so a retried send doesn't queue a second copy. A continuation (the flow asked to wait) is a new message with no key, because Vercel drops a send whose key it saw in the last 24 hours. A delay over 23 hours is split into hops: each hop is delivered, sees the delay that remains, and sends the message on without running the flow.
- The flow route answers Vercel's callback. A non-2xx response retries after
the backoff, clamped to 5 to 900 seconds. The 73rd delivery is
acknowledged and the message is dead-lettered through
onDeadLetter, as in the other modes. A flow response that asks to wait sends the message again with that delay and a higher attempt. - Vercel authenticates the callback, so there is no
x-bsb-signaturecheck in this mode. - A run whose wake-up is still owed after
recoverAfterseconds (300 by default) gets a new wake-up. In every mode the World clearsworkflow_runs.wake_pendingwhen an orchestrator delivery completes, andstart()and the poller sweep for runs that stay flagged. queuefails when the send fails, so the Workflow SDK sees the error instead of losing the message.
The Vercel side of this mode, that is handleCallback authentication, the
wildcard topic trigger, deployment pinning and the function timeout, is
covered by unit tests with a fake client and has not been run on Vercel yet.
Routing a queue prefix
world.registerRoute(prefix, path) posts the messages whose queue name
starts with prefix to another route of the same app, and
world.registerHandler(prefix, handler) runs them in the polling process
without an HTTP call. The SDK registers its own prefixes this way; use them
for a queue of your own that shares the World's tables:
world.registerRoute("__jobs_", "/api/jobs/queue");
world.registerHandler("__audit_", async (message) => {
await recordAudit(message);
});A route is a path on the flow route's origin, never an absolute URL. Poll
delivery reads both maps; pg_net delivery posts every message to the flow
route.
Each delivery is signed with the secret (x-bsb-signature, an HMAC-SHA256
over the time, the job and the body). The World's queue handler refuses an
unsigned or stale request with a 401 Problem Details response, and
completes or fails the job itself, so a delivery whose response is lost runs
again after its lease. Leave the flow route out of your proxy's matcher: the
World checks the signature, not a session.
Poll mode needs the secret too, unless NODE_ENV is development or
test: without one, the flow route answers every delivery with 401. Store
it in Vault as above or set WORKFLOW_DELIVERY_SECRET. A secret or key that
isn't in Vault counts as not set; a Vault read that fails is not cached, so
the next delivery reads again, and until then the route answers 503 and run
data can't be read or written.
A poll delivery that the flow route doesn't answer within deliveryTimeout
seconds (300 by default, at least lease) is aborted and retried. The
poller extends the job's lease only while the request is open.
Encryption
With a 32-byte master key (base64 or hex) in encryptionKey or the Vault
secret workflow_encryption_key, the World derives an AES-256 key per run
with HKDF-SHA256, and the SDK stores the run's inputs, outputs and step
data encrypted. Without one, they are stored as JSON in the workflow
schema, and world.start() logs a warning outside development and test.
When Vault can't be read, the World doesn't fall back to unencrypted data:
the read fails, and the next one tries Vault again. Run attributes such as
$eve.title stay plain text.
Rotating the master key
encryptionKeys (or WORKFLOW_ENCRYPTION_KEYS, or the Vault secret
workflow_encryption_keys) takes a JSON ring of master keys:
[
{ "id": "2026-01", "key": "<base64>", "from": 0 },
{ "id": "2026-11", "key": "<base64>", "from": "2026-11-20T00:00:00Z" }
]A run uses the last entry whose from is at or before the run's creation
time, which the World reads from the run id (wrun_<ULID>). To rotate,
append a key with a from in the future. Existing runs keep opening with
their old key, and new runs after that moment use the new one. The first
entry must have from set to 0, and entries are in ascending order.
When the ring has more than one key, the World also stamps the key's id
on each new run as the attribute $bsb.key_id, and reads that id before it
falls back to the dates. Moving a from later doesn't change which key a
stamped run opens with. Runs created before the ring had a second key carry
no stamp and are matched by date. Keep every key until no run uses it: a
stamped run whose key is gone falls back to the date and fails to decrypt.
To see which keys are in use, run
select attributes->>'$bsb.key_id', count(*) from workflow.workflow_runs group by 1.
Run attributes, including $eve.title and $bsb.key_id, are stored as
plain text. The eve World suite (tests/eve-world) runs a session with a
key and scans every table of the workflow schema, as text and as the hex
of bytea columns, for a message sent in the session; it finds nothing.
The same scan without a key finds the message, so the scan can see it.
Resumable streams
A run's getWritable() stream is stored chunk by chunk, so a client that
drops its connection can read on from where it stopped.
resumeStreamResponse(run, { startIndex }) returns the stream from
startIndex and sets the x-workflow-stream-tail-index header to the index
of the last chunk written so far:
import { resumeStreamResponse } from "better-supabase/workflow-sdk";
export async function GET(request: Request, { params }) {
const { id } = await params;
const from = new URL(request.url).searchParams.get("from");
return resumeStreamResponse(id, {
startIndex: from === null ? 0 : Number(from),
});
}A negative startIndex reads the last N chunks, and namespace picks a
named stream (getWritable({ namespace })). Pass sse: true to answer as
text/event-stream, and transform to pipe the chunks through a
TransformStream that frames them. Check that the caller may read the run
first, for example through workflow_runs under RLS.
Approvals with hooks
import type { RequestContext } from "better-supabase";
import { hookMetadata } from "better-supabase/workflow-sdk";
import { createHook } from "workflow";
export async function approveInvoice(invoiceId: string, ctx: RequestContext) {
"use workflow";
const hook = createHook<{ approved: boolean }>({
metadata: hookMetadata(ctx, "invoice.approve"),
});
const { approved } = await hook;
// ...
}import { authorizeHook } from "better-supabase/workflow-sdk";
import { resumeHook } from "workflow/api";
export async function POST(request: Request, { params }) {
const { token } = await params;
const ctx = await server.context(request);
await authorizeHook(token, ctx, {
can: (tenant, permission) => canInTenant(ctx, tenant, permission),
});
await resumeHook(token, await request.json());
return new Response(null, { status: 204 });
}A hook token in a link or an email is not enough to resume the run:
authorizeHook also checks who is asking. can is your permission check,
for example a call to member_can(auth.uid(), tenant, permission).
Approvals that expire
approvalWaiter waits on an approval by a token you choose, such as the
approval request's id, until a deadline. wait runs inside the workflow
and races a hook against sleep; expiresAt is a Temporal.Instant or
an RFC 3339 timestamp, since workflow arguments are serialized.
import { approvalWaiter } from "better-supabase/workflow-sdk";
export async function approveInvoice(approvalId: string, expiresAt: string) {
"use workflow";
const outcome = await approvalWaiter.wait<{ approved: boolean }>(approvalId, {
expiresAt,
});
if (outcome.status === "expired") return "expired";
// outcome.payload.approved
}To register the hook before the workflow does other steps, call
approvalWaiter.create(approvalId) and wait on the returned handle later,
so a wake in between is not missed.
The code that records the decision wakes the run once it has checked the approver:
await approvalWaiter.wake(approvalId, { approved: true });With the approvals block, use the request's id as
the token and let wakeOnApproval(event) do the waking from your outbox
consumer: it resumes the run for approval.approved, approval.rejected,
approval.expired and approval.cancelled with { approved, status, requestId }, and ignores a request no run waits on.
wake retries a missing hook up to four times, with a short pause, because an
approver can decide before the run reaches createHook; after that it throws
HookNotFoundError, which wakeOnApproval ignores.
wait resolves { status: "resumed", payload } or { status: "expired" },
and returns expired at once for a deadline that has passed. wake
sends null when you pass no payload.
Webhooks that resume a hook
A third party that calls back when it finishes (a payment, a signature, a long export) can resume the run directly. Create the hook with a token you can put in the callback URL, then verify the callback and resume:
import { resumeHookFromWebhook } from "better-supabase/workflow-sdk";
export async function POST(request: Request, { params }) {
const { token } = await params;
return resumeHookFromWebhook(request, token, {
provider: "standard-webhooks",
secrets: process.env.CALLBACK_SIGNING_SECRET!,
});
}provider is stripe for the Stripe-Signature header or
standard-webhooks for Standard Webhooks and Svix senders. The response is
202 once the run resumes with the JSON body, 401 for a bad signature, and
404 when no run waits on the token. Pass seen to refuse a replayed
delivery (409), as for inbound webhooks.
Hooks a run waits on
world.openHooks({ tenantId, workflowName, limit }) lists the hooks of
pending and running runs, newest first, with the run's workflow, tenant,
actor and the hook's metadata, such as hookMetadata(ctx, permission). It
leaves the token out. Use it for an inbox of what is waiting on someone.
Tool approvals in durable turns
The AI SDK signs tool approval requests when the agent has
experimental_toolApprovalSecret, so a client can't approve a tool call
the model never made. Pass the secret to the WorkflowAgent your
durable turn runs, from a server-only env key.
Graph workflows
better-supabase/workflow-sdk/builder runs the graphs of the
workflow builder on the Workflow SDK.
compileGraph turns a graph into dynamic workflow source: each step node
calls its own step, sleep nodes call sleep and approval nodes wait on
createHook. Pass it as compile, and graphStarter as start, to
createWorkflowEditor.
A graph with an approval node needs approval on graphStarter (and
requestApproval on the static executor's runtime): a step that files an
approvals request for the node and returns its id. The node waits on that
id, and wakeOnApproval resumes it once an eligible approver decides.
graphStarter refuses to start a live run of such a graph without
approval, because a token derived from the run key could be guessed.
import { createApprovals } from "better-supabase/blocks/approvals";
import type { GraphApprovalCall } from "better-supabase/blocks/workflow-editor";
export async function requestApproval(call: GraphApprovalCall) {
"use step";
const claims = await serviceBuilder.versions.runAs(call.version).orThrow();
const approvals = createApprovals({
transport: serviceTransport,
tenant: String(claims.tenant_id),
});
const request = await approvals
.request(
{ type: "workflow_run", id: call.runKey },
{
action:
typeof call.config.action === "string"
? call.config.action
: "approve",
payload: { node: call.node },
},
)
.orThrow();
return request.id;
}import {
executeGraph,
graphRunFields,
type GraphStepCall,
type WorkflowGraph,
} from "better-supabase/blocks/workflow-editor";
import { createHook, sleep } from "workflow";
import { requestApproval } from "./approval";
import { steps } from "./steps";
export async function graphExecutor(
graph: WorkflowGraph,
input: unknown,
meta: unknown,
) {
"use workflow";
return executeGraph(graph, input, {
...graphRunFields(meta),
step: (call: GraphStepCall) => steps[call.step](call),
sleep: (ms) => sleep(ms),
requestApproval: (call) => requestApproval(call),
approval: (token) => createHook({ token }),
});
}graphRunFields(meta) passes the run key, version, tenant, subject, start
trigger node and, for a test run, the stubs. Pass executorRunsTests: true
to graphStarter once your executor spreads it; test runs on the static
executor are refused without it.
The executor imports executeGraph from the block rather than from
workflow-sdk/builder, so the workflow bundle doesn't load workflow/api,
which the workflow sandbox can't run.
import {
nodeRunReporter,
type GraphStepCall,
} from "better-supabase/workflow-sdk/builder";
const report = nodeRunReporter(serviceBuilder.nodeRuns);
export async function sendEmail(call: GraphStepCall) {
"use step";
return report(call, () => email.send(call.config));
}
export const steps = { "email.send": sendEmail };The app's own node kinds (defineNodeKind)
run as steps too. Pass the kinds as nodeKinds and one step per kind as
nodes; a dynamic start binds each custom node to its kind's step, and
refuses a graph with a kind it has no step for. The static executor passes
the same kinds and a node function to executeGraph:
export async function notify(call: GraphNodeCall) {
"use step";
return slack.post(String(call.config["channel"]), call.input);
}
export const start = graphStarter({
steps,
nodeKinds: NODE_KINDS,
nodes: { notify },
dynamic: true,
});Dynamic workflows are experimental in the Workflow SDK. With
WORKFLOW_EXPERIMENTAL_DYNAMIC_WORKFLOWS=1, graphStarter compiles the
published version's graph again on every start and runs that source; it
never runs the compiled form stored with the version. Source over 128 KiB
fails to publish. Node ids are 1 to 100 letters, digits, underscores or
hyphens, in validateGraph and in validate_workflow_graph. Without it, graphStarter starts executor, a static
"use workflow" function that walks the stored graph with executeGraph
and takes the same branches. Either way a run carries bsb.definition,
bsb.version, bsb.tenant, bsb.actor and bsb.key, and a start with a key
that already ran returns the first run.
nodeRunReporter records each step node's status, output and error in
workflow_node_runs for the canvas. A record that fails never fails the
step.
Start options and bulk cancel
startFor forwards three SDK start options. retention: 0 deletes the run's data as soon as
it ends, deploymentId pins the run to a deployment ("latest" picks the newest one in the
environment) on a World with immutable deployments such as Vercel, and hook creates a hook
with the run so the start is idempotent on its token. The Supabase World ignores deploymentId
and logs a warning, because it has one deployment.
const run = await startFor(context, importWorkflow, [file.id], {
retention: 0,
hook: { token: `import:${file.id}`, minRetentionMs: 3_600_000 },
});A second start with the same token creates no run and resolves to the run that owns the token,
and resumeHook(token) reaches the run at once. Use idempotencyKey when the World has no
atomic start hooks. The hook needs a World that supports them, and minRetentionMs needs hook
retention.
cancelTenantRuns cancels every pending or running run of a tenant, for an offboarded or
suspended organization. It lists the runs through world.analytics, then cancels them in
batches of 100 with runs.cancelMany when the World has it and one run at a time otherwise
(the Supabase World has no cancelMany, so the SDK's own fallback applies). It returns a
Result and never throws for a World error: run ids that failed come back in failed, and
calling it again is safe.
import { cancelTenantRuns } from "better-supabase/workflow-sdk";
const { requested, cancelled, settled, failed } = await cancelTenantRuns(
organizationId,
{ reason: "organization suspended" },
).orThrow();Analytics
world.analytics lists runs (by workflow name, status, attributes and a
time window), their steps, events, hooks and waits, and the attribute keys
in use. Pages hold at most 100 runs or 1000 steps and events. Each page
continues after the last row of the previous one (created_at, then the
id), so runs started while you page don't shift it. Pass back the cursor
the previous page returned. startFor uses it to find a run by its
idempotency key.
Retention
Runs, their events, steps, waits, stream chunks and hooks stay in the
workflow schema until you delete them. Set retention to delete ended
runs every hour with pg_cron:
blocks: {
"workflow-sdk": { options: { retention: "30 days" } },
},retention takes a number of days or hours. Without pg_cron, run
workflows prune on a schedule, or call
world.purgeRuns({ olderThan: "30 days" }). Each deletes completed, failed
and cancelled runs (statuses narrows it) that ended longer ago than the
cutoff, 500 runs per statement until none are left. A hook whose token
retention has not passed is kept. The copies in workflow_runs follow the
workflows block's own retention.
Zero-retention runs
A run started with a retention of 0 (the $retention attribute '0') keeps
no data after it ends: @workflow/world-postgres clears its input, output,
errors, event payloads, hook metadata and stream chunks right after the
terminal write. Since 5.4.1 the same transaction adds a backstop, due 60
seconds later, through Graphile Worker's add_job. This World runs no
Graphile Worker, so workflow.add_job records the backstop in
workflow.workflow_purge_backstops and rejects any other task with
WORKFLOW_GRAPHILE_UNSUPPORTED.
workflow_purge_backstops() takes the due backstops and clears the data of
each run that still has it (expired_at is null), in the same transaction
that marks the run expired. A run whose purge finished is skipped. Who runs
it depends on the delivery mode:
| Mode | Runs workflow_purge_backstops() |
|---|---|
poll | the World, on each poll and deliverOnce |
pg_net, vercel-queue | pg_cron, every minute |
Without pg_cron, call world.purgeBackstops() on a schedule. It runs the
function in batches of 100 ({ batch } changes it) until none are due, and
returns how many runs it purged. purgeRuns also deletes the backstop of
each run it deletes.
Last updated on