> For AI agents: the complete Sanity documentation index is available at [https://www.sanity.io/docs/llms.txt](https://www.sanity.io/docs/llms.txt).

# 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.

> [!WARNING]
> Early access
> Workflows is in early access, built in public. Read [How early access works](https://www.sanity.io/docs/workflows/prerelease) before you rely on it.



To run Workflows on [Sanity Functions](https://www.sanity.io/docs/functions/functions-introduction), 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](https://www.sanity.io/docs/workflows/generate-functions).

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](https://www.sanity.io/docs/functions/function-quickstart): runs when a document changes, filtered by a [GROQ](https://www.sanity.io/docs/content-lake/groq-introduction) expression.
- [Scheduled Function](https://www.sanity.io/docs/functions/scheduled-function-quickstart): runs on a schedule, so it can call `tick()` and the engine rechecks time conditions.
- [Effect](https://www.sanity.io/docs/workflows/effects-and-runtimes): 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, with `names` set to the effects this Function handles, and registers handlers for those effects. Without `names`, the call also considers effects it has no handler for, and with the default `missingHandler: 'fail'` it throws `MissingHandlerError` when it reaches one.- Trigger it on instance documents in your partition, when an instance is created or its `pendingEffects` change. 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.effectKey` as the idempotency key for any external write.



The generated drain for the `notify-reviewer` effect in the `dev` partition uses this trigger filter:

```groq
_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 calls `startInstance()`. 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 with `definitionsForDocument()` and starts each one.- Fire it on the write that makes `start.filter` true, not on every matching write. Otherwise, one document gets a new instance on every write.
- Build the `instanceId` with `instanceDocId()`, 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](https://www.sanity.io/docs/workflows/generate-functions) lists which start filters a trigger can evaluate.


- **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](https://www.sanity.io/docs/workflows/generate-functions).


- **Use one partition everywhere.** Every engine your Functions create uses the same `partition`. Every trigger filter and query matches it on the stored instance field `tag`, for example `tag == "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](https://www.sanity.io/docs/blueprints/manage-stacks) (10 by default). [Deploy definitions and Functions](https://www.sanity.io/docs/workflows/generate-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](https://www.sanity.io/docs/workflows/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:

**scripts/tick-on-schedule.ts**

```typescript
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

1. Use [Testing functions locally](https://www.sanity.io/docs/functions/functions-local-testing) to exercise each Function with representative payloads and credentials. Invoke each effect handler more than once with the same `ctx.effectKey` and confirm that it does not repeat the external write.
2. Test each document trigger locally with `sanity functions test`. The generated filters use GROQ delta functions such as `after()` and `delta::changedAny()`. These only work when you pass both versions of the document: use `--event update` with `--data-before` and `--data-after`. With a single document, `before()` and `after()` 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.
3. 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.



**npm**

```shell
npx sanity blueprints deploy
```

**pnpm**

```shell
pnpm dlx sanity blueprints deploy
```

**yarn**

```shell
yarn dlx sanity blueprints deploy
```

**bun**

```shell
bunx sanity blueprints deploy
```

Use the [Functions cheat sheet](https://www.sanity.io/docs/functions/functions-cheatsheet) for deployment and log commands.

