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

# Spawn and coordinate subworkflows

Spawn child workflow cohorts from an action, pass input values, and wait for child instances to settle.

> [!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.



A subworkflow is a workflow instance created by another workflow. Reach for one when a parent process has to run the same smaller process over several items, then wait for those children to finish.

This guide adds translations to the quick start’s `article-review` workflow. When an article enters `review`, the parent workflow starts one `translate-article` child for each locale listed on the article. The review can finish only after every translation is done. You define the child workflow, deploy both definitions, move the children forward with the CLI, and check that the parent continues.

The children are ordinary instances, with their own stages, activities, and fields. What makes them children is that a parent spawned them and waits on them.

## Prerequisites

- The finished [quick start](https://www.sanity.io/docs/workflows/getting-started): `workflows/article-review.ts` deployed through the `dev` deployment in `sanity.workflow.ts`, and the `_id` of the published article you started it with.
- A `locales` array of strings on the article, for example `["de", "fr"]`. Add the field to your article schema or set it on the document. Each locale must be unique.
- Familiarity with triggered actions (actions with `when`) from [Define activities and actions](https://www.sanity.io/docs/workflows/activities-and-actions).

## Define the child workflow

Create `workflows/translate-article.ts`. The parent passes each child a `source` reference and a `locale`, so the child declares both as input fields:

**workflows/translate-article.ts**

```typescript
import {
  defineAction,
  defineActivity,
  defineField,
  defineStage,
  defineTransition,
  defineWorkflow,
} from '@sanity/workflows/define'

export const translateArticle = defineWorkflow({
  name: 'translate-article',
  title: 'Translate article',
  description: 'Translates one article into one locale. Spawned by article-review.',
  lifecycle: 'child',
  initialStage: 'translating',
  fields: [
    defineField({
      type: 'doc.ref',
      name: 'source',
      title: 'Source article',
      required: true,
      initialValue: {type: 'input'},
    }),
    defineField({
      type: 'string',
      name: 'locale',
      title: 'Locale',
      required: true,
      initialValue: {type: 'input'},
    }),
  ],
  stages: [
    defineStage({
      name: 'translating',
      title: 'Translating',
      activities: [
        defineActivity({
          name: 'translate',
          title: 'Translate the article',
          actions: [defineAction({name: 'finish', title: 'Finish translation', status: 'done'})],
        }),
      ],
      transitions: [defineTransition({name: 'to-translated', title: 'Finish', to: 'translated'})],
    }),
    defineStage({name: 'translated', title: 'Translated'}),
  ],
})
```

`lifecycle: 'child'` marks the definition as spawn-only. The CLI refuses to start it on its own with `definition is spawn-only (lifecycle: 'child')`.

A parent can spawn any deployed definition, not only one marked `lifecycle: 'child'`. The spawn finds the definition by name and uses its highest deployed version unless the spawn pins one. `lifecycle: 'child'` only makes a definition spawn-only: start pickers hide it, the CLI refuses to start it, and it can’t declare `start`. Leave `lifecycle` out, and the same definition can be started on its own and spawned by a parent. A spawn skips the child’s start requirements and start roles; the child starts when the parent’s action fires.

**Without lifecycle: started on its own, or spawned**

```typescript
// On its own: npx sanity-workflows start translate-article --field locale=de --field source='{...}'
spawn: {forEach: '$fields.subject.locales', definition: {name: 'translate-article'}, with: {/* ... */}},
```

## Spawn a child for each locale

A spawn belongs to an action. Its `forEach` expression returns one row per child, and `with` maps values from each row into the child’s input fields. Add a `translations` activity to the `review` stage in `workflows/article-review.ts`:

**workflows/article-review.ts**

```typescript
export const articleReview = defineWorkflow({
  // ...
  stages: [
    // drafting is unchanged
    defineStage({
      name: 'review',
      // ...
      activities: [
        defineActivity({
          name: 'translations',
          title: 'Translate the article',
          filter: 'count(coalesce($fields.subject.locales, [])) > 0',
          actions: [
            defineAction({
              name: 'fan-out',
              title: 'Start one translation per locale',
              when: 'true',
              spawn: {
                forEach: '$fields.subject.locales',
                definition: {name: 'translate-article'},
                with: {
                  locale: '$row',
                  source: '{"id": $fields.subject._id, "type": $fields.subject._type}',
                },
              },
            }),
            defineAction({
              name: 'all-done',
              title: 'All translations finished',
              when:
                "count($subworkflows[activity == 'translations' && current]) > 0 && " +
                "count($subworkflows[activity == 'translations' && current && status == 'active']) == 0",
              status: 'done',
            }),
          ],
        }),
        defineActivity({
          name: 'sign-off',
          // ...
        }),
      ],
      // ...
    }),
    // approved is unchanged
  ],
})
```

Here is what each part of the `translations` activity does:

- `when: 'true'` on `fan-out`: the engine fires the action in the call that moves the instance into `review`. No one has to click anything.
- `forEach`: returns the article’s `locales` array. `$fields.subject` is the loaded article document, so no separate query is needed. Each locale becomes one row, and each row becomes one child.
- `with`: sets the child’s input fields. `$row` is the current locale. `source` rebuilds the `{id, type}` reference to the article.
- `filter`: skips the activity when the article has no locales. Without `coalesce`, a missing `locales` field would make the filter evaluate to `null`. A filter that evaluates to `null` keeps the activity, so `coalesce` turns a missing field into an empty array.
- `all-done`: resolves the activity once every child has finished. The next section explains its condition.

The engine gives each row an identity, and the identity must be unique. It uses the first of these that the row has: an object’s `_key`, its `_id`, a reference’s `id`, or a scalar’s string value. If two rows share an identity, or a row has none, the spawn fails. For example, a `locales` array of `["de", "de"]` fails with an error that includes `produced two rows with the same identity "de"`.

The identity also prevents duplicate children. If the instance leaves `review` and later re-enters it, the engine reuses the running children whose identities match, instead of spawning new ones.

By default, `forEach` reads data the instance has already loaded. A `forEach` expression that contains `*` runs as a Content Lake query instead. Use that form to fan out over documents the instance doesn’t already reference.

## Wait for every child to finish

Spawning and waiting are separate actions. `fan-out` creates all the children in one commit. That group of children is called a cohort. `all-done` resolves the `translations` activity when both of these are true:

- The current cohort has at least one child.
- No child in the current cohort is still active.

Until then, `translations` stays active. The `to-approved` transition uses the default condition, which waits for every activity, so the parent stays in `review`.

`all-done` reads `$subworkflows`, which holds one row per child. Two row properties matter here:

- `current`: `true` for children spawned during the current visit to the stage.
- `status`: `active`, `done`, or `aborted`.

Both `done` and `aborted` count as finished. To continue only when every child succeeded, test `status == 'done'`. A parent transition can also read `$subworkflows` in its own `when`, without an activity. [Cohort row](https://www.sanity.io/docs/workflows/workflow-authoring-reference) lists every row property.

The engine re-evaluates the parent in the call that finishes its last child. When a child action or effect completes, the engine re-evaluates the parent in that call, then the parent’s parent, and so on up the chain. For function-hosted parents that spawn children, a [generated heartbeat](https://www.sanity.io/docs/workflows/generate-functions) also re-evaluates the parent on a schedule.

The diagram shows the full sequence for this definition. The engine creates the child cohort in one commit, child actions update their own instances, and each child commit carries back to the parent until the completion trigger resolves the activity.

![A parent caller fires a spawning action through the engine. The engine identifies child rows and commits the child instances and parent cohort registry together. Independent child callers act through the engine; child commits propagate until the parent completion trigger resolves the activity.](https://cdn.sanity.io/images/3do82whm/next/54de31ffe08e6b331b1fe1318978f862d0591c96-2800x1548.png)

## Deploy both definitions

Add the child to the `dev` deployment in `sanity.workflow.ts`, beside `articleReview`:

**sanity.workflow.ts**

```typescript
import type {WorkflowDeploymentInput} from '@sanity/workflows'
import {defineWorkflowConfig} from '@sanity/workflows/define'

import {articleReview} from './workflows/article-review'
import {translateArticle} from './workflows/translate-article'

export const dev = {
  name: 'dev',
  partition: 'dev',
  expectedMinReaderModel: 10,
  workflowResource: {type: 'dataset', id: 'PROJECT_ID.DATASET_NAME'},
  definitions: [articleReview, translateArticle],
} satisfies WorkflowDeploymentInput

export default defineWorkflowConfig({deployments: [dev]})
```

**npm**

```shell
npx sanity-workflows deploy
```

**pnpm**

```shell
pnpm dlx sanity-workflows deploy
```

**yarn**

```shell
yarn dlx sanity-workflows deploy
```

**bun**

```shell
bunx sanity-workflows deploy
```

Deploy checks that the parent and child fit together. It reports two kinds of failure:

- The child definition is missing: deploying the parent without the child fails with `1 unresolved reference: article-review → translate-article (neither in batch nor deployed)`.
- A `spawn.with` key doesn’t match a child input field: every key must name a child field whose `initialValue` is `{type: 'input'}`. Otherwise deploy throws `SpawnContractsInvalidError` and lists every mismatch, for example `spawn.with["locale"] cannot be consumed — the child field is literal-sourced, not input-sourced`.

## Run the parent and its children

Start the parent against an article with `locales`, and submit it:

**npm**

```shell
npx sanity-workflows start article-review \
  --field subject='{"id":"dataset:PROJECT_ID:DATASET_NAME:DOCUMENT_ID","type":"article"}'
npx sanity-workflows fire-action INSTANCE_ID --activity write --action submit
```

**pnpm**

```shell
pnpm dlx sanity-workflows start article-review \
  --field subject='{"id":"dataset:PROJECT_ID:DATASET_NAME:DOCUMENT_ID","type":"article"}'
pnpm dlx sanity-workflows fire-action INSTANCE_ID --activity write --action submit
```

**yarn**

```shell
yarn dlx sanity-workflows start article-review \
  --field subject='{"id":"dataset:PROJECT_ID:DATASET_NAME:DOCUMENT_ID","type":"article"}'
yarn dlx sanity-workflows fire-action INSTANCE_ID --activity write --action submit
```

**bun**

```shell
bunx sanity-workflows start article-review \
  --field subject='{"id":"dataset:PROJECT_ID:DATASET_NAME:DOCUMENT_ID","type":"article"}'
bunx sanity-workflows fire-action INSTANCE_ID --activity write --action submit
```

Entering `review` spawned the children. List in-flight instances to find their IDs:

**npm**

```shell
npx sanity-workflows list
```

**pnpm**

```shell
pnpm dlx sanity-workflows list
```

**yarn**

```shell
yarn dlx sanity-workflows list
```

**bun**

```shell
bunx sanity-workflows list
```

**CLI**

```text
instance                       workflow            partition   stage         status      updated
dev.wf-instance.7d14f056e959   translate-article   dev         translating   in-flight   just now
dev.wf-instance.581c5ef24ee8   translate-article   dev         translating   in-flight   just now
dev.wf-instance.69cd78547e1d   article-review      dev         review        in-flight   just now
```

Approve the review on the parent. It stays in `review`, because `translations` is still active:

**npm**

```shell
npx sanity-workflows fire-action INSTANCE_ID --activity sign-off --action approve
```

**pnpm**

```shell
pnpm dlx sanity-workflows fire-action INSTANCE_ID --activity sign-off --action approve
```

**yarn**

```shell
yarn dlx sanity-workflows fire-action INSTANCE_ID --activity sign-off --action approve
```

**bun**

```shell
bunx sanity-workflows fire-action INSTANCE_ID --activity sign-off --action approve
```

**CLI**

```text
✔ Fired approve on sign-off — now at review

ops applied:
  ℹ status.set
```

Finish each translation, using the child IDs from `list`:

**npm**

```shell
npx sanity-workflows fire-action CHILD_INSTANCE_ID --activity translate --action finish
```

**pnpm**

```shell
pnpm dlx sanity-workflows fire-action CHILD_INSTANCE_ID --activity translate --action finish
```

**yarn**

```shell
yarn dlx sanity-workflows fire-action CHILD_INSTANCE_ID --activity translate --action finish
```

**bun**

```shell
bunx sanity-workflows fire-action CHILD_INSTANCE_ID --activity translate --action finish
```

## Verify the parent continued

When the last child reaches `translated`, the parent resolves `translations` and moves on in the same call. Run `npx sanity-workflows show INSTANCE_ID` on the parent:

**CLI**

```text
Stage history:
  • drafting (exited 2026-10-26 18:10:33)
      ✔ write  [done]
  • review (exited 2026-10-26 18:10:33)
      ✔ translations  [done]
      ✔ sign-off  [done]
  • approved (current)
```

To see the parent’s record of its children, run `show INSTANCE_ID --json`. The parent’s `subworkflows` array holds one entry per child, with its `rowKey` (`de` or `fr`) and a reference to the child instance.

From code, `engine.children({instanceId})` returns the child instances. It reads through a GROQ query, so it can miss a commit made in the last second or so. For details, see [commit visibility](https://www.sanity.io/docs/workflows/engine).

## Spawn when someone fires the action

To spawn only when someone asks, remove `when` from `fan-out`. Nothing happens when the instance enters the stage. Instead, the cohort is created when someone fires the action, for example with `npx sanity-workflows fire-action INSTANCE_ID --activity translations --action fan-out`.

Keep the `count(...) > 0` clause in `all-done`. Before anyone fires `fan-out`, the cohort is empty, so no child is active. Without the clause, `all-done` would resolve the activity before any child exists.

**workflows/article-review.ts**

```typescript
defineAction({
  name: 'fan-out',
  title: 'Start one translation per locale',
  // No when: a caller fires this action.
  spawn: {
    forEach: '$fields.subject.locales',
    definition: {name: 'translate-article'},
    with: {
      locale: '$row',
      source: '{"id": $fields.subject._id, "type": $fields.subject._type}',
    },
  },
}),
```

## Stop children when the stage exits

The stage can exit while children are still running, for example when a reviewer sends the article back. The spawn’s `onExit` setting tells the engine what to do with those children:

- `'detach'` (the default): the children stay active and finish independently of the parent.
- `'abort'`: the engine aborts the children, and their own children too.

Aborting the parent instance always aborts its children, whatever `onExit` says.

**workflows/article-review.ts**

```typescript
spawn: {
  forEach: '$fields.subject.locales',
  definition: {name: 'translate-article'},
  with: {
    locale: '$row',
    source: '{"id": $fields.subject._id, "type": $fields.subject._type}',
  },
  onExit: 'abort',
},
```

## Next steps

- Look up the spawn declaration, expression scope, and cohort row in [Subworkflow spawn declaration](https://www.sanity.io/docs/workflows/workflow-authoring-reference).
- Gate transitions on `$subworkflows` and other state in [Write GROQ conditions](https://www.sanity.io/docs/workflows/conditions).
- Review how actions carry spawns, operations, and statuses in [Define activities and actions](https://www.sanity.io/docs/workflows/activities-and-actions).

> [!NOTE]
> Visiting agent?
> Workflows has MCP tools that let an agent inspect, operate, author, validate, and deploy workflows. An agent host embeds these tools. Ask the person you work for whether your host [includes the Workflows tools](https://www.sanity.io/docs/workflows/mcp).



