Workflows

Spawn and coordinate subworkflows

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

Early access

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 starts one translate-article child per locale listed on the article, and the review can only finish once every translation is done. You define the child, deploy both definitions, drive the children with the CLI, and watch the parent continue.

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

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/workflow-engine/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').

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
  ],
})

fan-out declares when: 'true', so the engine fires it as soon as the instance enters review. $fields.subject is the loaded article, so forEach reads its locales without a separate query. source rebuilds the {id, type} reference from the loaded document. The activity filter skips the activity for an article with no locales; coalesce keeps the filter decidable when locales is missing, because an undecidable filter keeps the activity in scope.

Each row needs a unique identity: an object’s _key, then its _id, then a reference’s id, or a scalar’s string value. Duplicate or missing identities reject the spawn, for example produced two rows with the same identity "de". Re-entering the stage adopts matching live children instead of spawning duplicates. A forEach that contains * runs as a Content Lake query instead of reading the evaluation snapshot; use it to fan out over documents the instance does not already reference.

Wait for every child to finish

Spawning and waiting are separate actions. One spawn commit creates the whole group of children, called a cohort. all-done resolves the activity once the current cohort is non-empty and no child in it is still active. Because translations stays active until then, the default to-approved transition waits too.

Each child is one row in $subworkflows. current selects children from the open stage visit, and status is active, done, or aborted. Both done and aborted count as finished, so test status == 'done' when the parent must continue only after every child succeeds. A parent transition can also gate on $subworkflows directly instead of an activity. Cohort row lists every row property.

After a child action or effect completion, the engine re-evaluates the parent in the same call and continues up the ancestor chain, so the parent reacts as soon as its last child finishes. A generated heartbeat also periodically re-evaluates function-hosted parents that spawn children.

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/workflow-engine'
import {defineWorkflowConfig} from '@sanity/workflow-engine/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 deploy

Deploy checks the parent-to-child contract. Deploying the parent without the child fails with 1 unresolved reference: article-review → translate-article (neither in batch nor deployed). Every key in spawn.with must name a child field whose initial value comes from input; otherwise deploy rejects every invalid contract together with SpawnContractsInvalidError, 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:

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

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

npx sanity-workflows list
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:

npx sanity-workflows fire-action INSTANCE_ID --activity sign-off --action approve
✔ Fired approve on sign-off — now at review

ops applied:
  ℹ status.set

Finish each translation, using the child IDs from list:

npx 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:

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)

The parent’s subworkflows array, visible with show INSTANCE_ID --json, holds one entry per child with its rowKey (de, fr) and a reference to the child instance. From code, engine.children({instanceId}) returns the child instances.

Spawn when someone fires the action

Remove when from fan-out and the spawn waits for a caller: nothing happens at stage entry, and 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 the caller fires, the cohort is empty, an empty cohort has no active child, and without the clause the activity resolves before anything spawns.

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

If the stage exits while children are still running, onExit on the spawn decides their fate. 'detach', the default, lets them finish on their own. 'abort' aborts them, and their own children too. Aborting the parent instance always aborts its children.

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

Visiting agent?

Was this page helpful?

Sanity logosanity.ioAll Systems Operational© Sanity 2026
Change site theme