Run Workflows with Sanity Functions
Run Workflows on Sanity Functions by generating them from your workflow definitions, or write your own Functions that drain effects, start autonomous workflows, and tick on a bounded heartbeat.
Early access
Workflows is in early access, built in public. Read How early access works before you rely on it.
To run Workflows on Sanity Functions, generate the Functions from your workflow definitions. npx @sanity/workflows-cli blueprints generate writes the Functions your definitions need: effect drains, start watchers, and a heartbeat. To generate, deploy, and check them, follow Generate Functions from your workflow definitions.
A workflow that only moves when editors act needs no Functions.
Write your own Functions
Write the Functions yourself only when you must own their code. Your Functions replace everything the generator writes, so they must do every job in the following list. To compare your code with the generated Functions, run npx @sanity/workflows-cli blueprints generate in a scratch copy of your project and read what it writes.
These terms come up in the list:
- Document Function: runs when a document changes, filtered by a GROQ expression.
- Scheduled Function: runs on a schedule, so it can call
tick()and the engine rechecks time conditions. - Effect: outside work declared on an action. The engine queues it when the action commits, and a Function that calls
drainEffects()with the matching handler runs it.
Your Functions must do these jobs:
- Drain effects with claims. A Document Function calls
drainEffects({instanceId, names})for the instance in its event, withnamesset to the effects this Function handles, and registers handlers for those effects. Withoutnames, the call also considers effects it has no handler for, and with the defaultmissingHandler: 'fail'it throwsMissingHandlerErrorwhen it reaches one.- Trigger it on instance documents in your partition, when an instance is created or its
pendingEffectschange. Fire only while an unclaimed effect it handles is pending. - One call runs the named effects until none of them can be claimed. Don’t add an outer loop or a
tick()call after it. - When an effect fails, fail the invocation, so the platform records the failure.
- A handler can receive the same effect more than once. Use
ctx.effectKeyas the idempotency key for any external write.
- Trigger it on instance documents in your partition, when an instance is created or its
The generated drain for the notify-reviewer effect in the dev partition uses this trigger filter:
_type == "sanity.workflow.instance" && tag == "dev" &&
(delta::operation() == "create" || delta::changedAny(pendingEffects)) &&
count(pendingEffects[!defined(claim) && name in ["notify-reviewer"]]) > 0- Sweep stale claims. If a handler stops before it records an outcome, its claim stays in place. On a schedule, call
sweepStaleClaims()for every instance in your partition that has a pending effect your drains handle.- Include completed instances. Reaching a final stage doesn’t discard queued effects.
- The sweep releases expired claims. It also re-queues an effect that no drain picked up within five minutes, which wakes the drain again.
- Start autonomous workflows. A definition with
start.kind: 'autonomous'starts only when something callsstartInstance(). Add a Document Function that watches the content documents the workflow can start on. Watch the workflow dataset and every dataset alias. The Function finds the matching definitions withdefinitionsForDocument()and starts each one.- Fire it on the write that makes
start.filtertrue, not on every matching write. Otherwise, one document gets a new instance on every write. - Build the
instanceIdwithinstanceDocId(), from the definition, the dataset, the document_id, and its_rev. Then a redelivered event resumes the same start instead of starting another instance. - A trigger that fires only on create never sees documents that already exist. Start those yourself.
- Predict when generated triggers run lists which start filters a trigger can evaluate.
- Fire it on the write that makes
- Tick on a bounded heartbeat. A Scheduled Function calls
tick()on the in-flight instances of the workflows your Functions host. Leave other workflows alone, because another runtime may host them.- Limit the work in each run. The generated heartbeat has a 60-second timeout. Each run sweeps at most 30 instances and ticks at most 30, oldest start first. When it also starts documents on the clock, it sweeps, ticks, and starts at most 20 each. Later runs take other slices, so every instance gets its turn.
- Handle each instance on its own. Run the sweep and the tick as separate steps, so a failure in one doesn’t skip the other. Fail the run if any instance failed.
- The generated heartbeat asks to run once a minute. How often it actually runs depends on your plan. See Plan for heartbeat recovery.
- Use one partition everywhere. Every engine your Functions create uses the same
partition. Every trigger filter and query matches it on the stored instance fieldtag, for exampletag == "dev". - Split the stacks. The platform accepts a Scheduled Function only on an organization-scoped stack. So deploy to two stacks, each with its own robot token:
- The drains and start watchers go on a project-scoped stack, deployed with a token that can deploy to the project.
- The heartbeat goes alone on an organization-scoped stack, deployed with an organization deploy token. A Scheduled Function gets no project, no dataset, and no automatic token in its event context. So the heartbeat must name the workflow resource and bind its robot token.
- Each organization-scoped stack counts toward your organization’s stack limit (10 by default). Deploy definitions and Functions shows the generated layout.
Schedule ticks outside Functions
Time passing doesn’t advance an instance until something calls tick(). A tick() result can include nextEvaluationAt: the earliest future time when a time-based condition on the instance can change. The value is absent on a finished instance. It’s also absent when the engine can’t work out such a time. So a missing value doesn’t mean an active instance has nothing left to wait for.
Time-based conditions must read $now, or dateTime($now) for datetime comparisons. Definition validation rejects now() and dateTime::now().
Outside Functions, a long-running worker can schedule its own ticks. This function takes a configured engine, such as the engine that scripts/engine.ts exports, and an existing instance ID. It waits until nextEvaluationAt or one minute, whichever comes first:
import type {Engine} from '@sanity/workflows'
export async function tickOnSchedule(engine: Engine, instanceId: string) {
while (true) {
const result = await engine.tick({instanceId})
if (result.instance.completedAt) return
const untilNext = result.nextEvaluationAt
? Date.parse(result.nextEvaluationAt) - Date.now()
: 60_000
const delay = Math.max(1, Math.min(untilNext, 60_000))
await new Promise<void>((resolve) => setTimeout(resolve, delay))
}
}Call await tickOnSchedule(engine, instanceId) from a long-running worker. It stops when the instance completes or is aborted. If a tick fails, the call rejects, and your worker must handle the failure.
The one-minute fallback also catches data changes, and time conditions that report no nextEvaluationAt. The timer lasts only while the process runs. Workflows hosted on Functions use the heartbeat instead.
Test and deploy
- Use Testing functions locally to exercise each Function with representative payloads and credentials. Invoke each effect handler more than once with the same
ctx.effectKeyand confirm that it does not repeat the external write. - Test each document trigger locally with
sanity functions test. The generated filters use GROQ delta functions such asafter()anddelta::changedAny(). These only work when you pass both versions of the document: use--event updatewith--data-beforeand--data-after. With a single document,before()andafter()are empty and the trigger doesn’t fire. Then deploy to a non-production stack and check that each trigger fires only on the writes it should. - Check the recovery paths:
- New work invokes the drain.
- Claim and completion writes don’t start an invocation loop.
- After a handler is interrupted, its expired claim becomes available again. Include a completed instance with pending effects in this test.
- A redelivered write to a watched document starts no second instance.
- A scheduled tick that changes no state doesn’t write.
npx sanity blueprints deploypnpm dlx sanity blueprints deployyarn dlx sanity blueprints deploybunx sanity blueprints deployUse the Functions cheat sheet for deployment and log commands.
Was this page helpful?
Feedback submitted, thanks for helping us improve the docs. Have you tried these alternatives?