Spawn and coordinate subworkflows
Spawn child workflow cohorts from an action, pass input values, and wait for child instances to settle.
Early access
Workflows is in early access, built in public. Read How early access works 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:
workflows/article-review.tsdeployed through thedevdeployment insanity.workflow.ts, and the_idof the published article you started it with. - A
localesarray 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.
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:
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.
// 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:
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'onfan-out: the engine fires the action in the call that moves the instance intoreview. No one has to click anything.forEach: returns the article’slocalesarray.$fields.subjectis 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.$rowis the current locale.sourcerebuilds the{id, type}reference to the article.filter: skips the activity when the article has no locales. Withoutcoalesce, a missinglocalesfield would make the filter evaluate tonull. A filter that evaluates tonullkeeps the activity, socoalesceturns 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:truefor children spawned during the current visit to the stage.status:active,done, oraborted.
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 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 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.
Deploy both definitions
Add the child to the dev deployment in sanity.workflow.ts, beside articleReview:
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]})npx sanity-workflows deploypnpm dlx sanity-workflows deployyarn dlx sanity-workflows deploybunx sanity-workflows deployDeploy 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.withkey doesn’t match a child input field: every key must name a child field whoseinitialValueis{type: 'input'}. Otherwise deploy throwsSpawnContractsInvalidErrorand lists every mismatch, for examplespawn.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:
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 submitpnpm 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 submityarn 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 submitbunx 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 submitEntering review spawned the children. List in-flight instances to find their IDs:
npx sanity-workflows listpnpm dlx sanity-workflows listyarn dlx sanity-workflows listbunx sanity-workflows listinstance 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 nowApprove the review on the parent. It stays in review, because translations is still active:
npx sanity-workflows fire-action INSTANCE_ID --activity sign-off --action approvepnpm dlx sanity-workflows fire-action INSTANCE_ID --activity sign-off --action approveyarn dlx sanity-workflows fire-action INSTANCE_ID --activity sign-off --action approvebunx sanity-workflows fire-action INSTANCE_ID --activity sign-off --action approve✔ Fired approve on sign-off — now at review
ops applied:
ℹ status.setFinish each translation, using the child IDs from list:
npx sanity-workflows fire-action CHILD_INSTANCE_ID --activity translate --action finishpnpm dlx sanity-workflows fire-action CHILD_INSTANCE_ID --activity translate --action finishyarn dlx sanity-workflows fire-action CHILD_INSTANCE_ID --activity translate --action finishbunx sanity-workflows fire-action CHILD_INSTANCE_ID --activity translate --action finishVerify 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:
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.
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.
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.
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.
- Gate transitions on
$subworkflowsand other state in Write GROQ conditions. - Review how actions carry spawns, operations, and statuses in Define activities and actions.
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.
Was this page helpful?
Feedback submitted, thanks for helping us improve the docs. Have you tried these alternatives?