Trigger child tasks
Create linked work from a task without hiding its lifecycle.
Use context.step.trigger() to create one child per named parent step. Use context.join() when the parent needs the child's result. New children record their source run and inherit the parent's trace carrier unless you override it.
For an existing deployment, follow Upgrade Runlane before using named child steps or joins.
With a local lane, parent and child runs live in dev's memory. Keep runlane dev running for app triggers. Use createTestLane() in in-process tests without dev; the shared runtime below selects it when NODE_ENV=test.
Trigger the child
Keep the related task definitions together in src/tasks/document-tasks.ts:
import { task } from '@runlane/core'
import * as z from 'zod'
const env = z.object({ DOCUMENTS_API_URL: z.url() }).parse(process.env)
export const indexDocument = task({
id: 'documents.index',
schema: z.object({ documentId: z.string() }),
output: z.object({ indexed: z.boolean() }),
async run({ documentId }, context) {
const response = await fetch(new URL(`/documents/${encodeURIComponent(documentId)}/index`, env.DOCUMENTS_API_URL), {
method: 'POST',
signal: context.signal,
})
if (!response.ok) throw new Error(`Documents API returned ${response.status}`)
return { indexed: true }
},
})
export const importDocument = task({
id: 'documents.import',
schema: z.object({ documentId: z.string() }),
async run({ documentId }, context) {
const response = await fetch(
new URL(`/documents/${encodeURIComponent(documentId)}/import`, env.DOCUMENTS_API_URL),
{
method: 'POST',
signal: context.signal,
},
)
if (!response.ok) throw new Error(`Documents API returned ${response.status}`)
await context.step.trigger('index-document', indexDocument, { documentId })
},
})Register both tasks in the shared runtime:
import { createRunlane, RunRetention, queue } from '@runlane/core'
import { createLocalLane, createTestLane } from '@runlane/lane-local'
import { importDocument, indexDocument } from './tasks/document-tasks.js'
const defaultQueue = queue({ name: 'default', default: true })
export const runlane = createRunlane({
retention: {
succeeded: RunRetention.deleteAfter('7d'),
cancelled: RunRetention.deleteAfter('7d'),
failed: RunRetention.deleteAfter('30d'),
expired: RunRetention.deleteAfter('7d'),
},
lane: process.env.NODE_ENV === 'test' ? createTestLane() : createLocalLane(),
queues: [defaultQueue],
tasks: { importDocument, indexDocument },
})Every runtime that can execute either task needs the same catalog.
The child trigger returns after storing the child run. It does not wait for the child handler to finish.
Make replay safe
The parent handler can run again. The stable step key reuses its saved child, including a child that failed, was cancelled, or expired. A retry does not silently create a replacement. Repeated keys are counted across all step methods. Keep each counted call bound to the same task and step kind across attempts. See the replay rule.
Named triggering does not checkpoint work before the trigger. Use saved steps and the downstream service's idempotency support for external effects that may repeat.
Add an idempotencyKey when different parent runs should share the same business operation. An existing child keeps its original source link. For versioned work, include the version in that business key.
Use context.trigger(indexDocument, payload, options?) when you want ordinary trigger semantics without a saved step binding. Its idempotency rules are unchanged. The handler restarts from the top on retries, after a wait resumes, and after lease recovery. Each restart runs a plain context.trigger() again and can create another child. Use context.step.trigger() for replay safety, or pass an idempotencyKey.
To combine pending indexing requests from different parents, use debounce: { key: documentId, delay: '5s', maxDelay: '1m' } instead of business idempotency. The first payload and policy win. A fresh named step can share that pending child; replaying a saved step never extends its window. Pass a stable document ID and read current document state inside the child. See debounce for time bounds and unsupported option combinations.
Wait only when the parent truly depends on the child
In a handler that needs the indexing result:
const child = await context.step.trigger('index-document', indexDocument, { documentId })
const result = await context.join(indexDocument, child)
if (result.ok) return result.output
return { indexed: false, reason: result.error.message }Await join() to suspend while the child runs. This frees the parent's queue slot, including when both tasks share a queue with concurrency one. On resume, the handler starts from the beginning and replays the named trigger.
join(indexDocument, child) applies the task's current output schema to the saved raw output. join(child) returns raw output without that transform. Both return { ok: true, output, run } or { ok: false, error, run } for failure, cancellation, or expiry. result.run is a RunSnapshot, which omits payload. Named replay still works after the child is deleted, including when a step.run() checkpoint saved only its ID and replay skips the trigger callback; see child result retention. Use result.ok before reading output. Cancelling a parent while it waits also cancels unfinished children it created, unless another registered waiter or named binding protects them. See cancellation rules.
For a parent that should fail when indexing does not succeed, combine the calls and unwrap the result:
return context.step.triggerAndWait('index-document', indexDocument, { documentId }).unwrap()The promise has the same result type as a typed join. It counts the key once and reuses the child on replay. .unwrap() throws a non-retryable error that names the child and its stored failure reason.
On first use, triggerAndWait() creates the child and parks the parent in one storage transaction. The commit saves every admitted child, its binding and retention, the first pause’s requested release, and both parent capacity releases. This also applies when sleep, a signal wait, a token wait, or context.release() pauses first. A completion waiter is registered only when the first pause waits for a child. Children become visible with the parent release. Calls admitted before that pause are combined, including siblings in Promise.all(); a slow validator cannot omit one. Calls started after the pause stay parked. On resume, saved bindings replay before new payload validation.
The complete child-and-parent plan must fit the driver's atomic capacity. storage_limit_exceeded creates no missing children and no release; the owned attempt stores a bounded failure. Runlane never splits this invariant. For larger fan-out, use raw chunked batches with explicit joins and business idempotency.
Keep maintenance running. It recovers missed completion notifications without running parent handlers. Named steps preserve completed results across child deletion; see child result retention.
await context.join(childRunId) follows any existing run in the current environment. It uses the same durable registration and completion recovery as joining a child reference. A missing or pruned run fails with run_not_found; self-joins are rejected. Joins have no timeout option. Use context.join(indexDocument, childRunId) to validate the task and parse its successful output.
Several waits inside Promise.all() resume in sequence across attempts. Use a group join when the parent needs every child result.
Trigger and join a group
For a handler receiving documentIds, submit one named item per document and await the terminal results:
const children = await context.step.triggerBatch(
documentIds.map((documentId) => ({
stepKey: `index-${documentId}`,
task: indexDocument,
payload: { documentId },
})),
)
const results = await context.join(indexDocument, children)
return results.map((result) => (result.ok ? result.output : { indexed: false }))Document IDs must yield valid step keys without : or #. Repeated keys are counted in item order. Use stable business identifiers when a list or a check can change between attempts.
To combine the batch and join, use context.step.triggerBatchAndWait(items) or its alias context.step.batch.triggerAndWait(items). Each result is typed by its item's task when that task has an output schema. .unwrap() returns outputs in input order or fails on the first unsuccessful run. You can also pass an array of existing run IDs to join().
You can use context.step.batch.trigger() instead of context.step.triggerBatch(). Both spellings share the same saved bindings and atomic behavior, so changing the spelling between attempts does not create replacement children.
The call returns one TriggerRunResult per input in order. It replays existing bindings, then accepts every missing binding and child in one storage transaction. Validation, binding, ownership-key, and provider-limit failures accept none of the missing children. Existing bindings remain saved. After commit, affected children report deliveryError for failed publication or admission under saved changes and delivery errors. The parent can continue successfully. Named batches have no outer concurrency option. See durable steps for the exact rejection rules.
The parent stays released until all joined children succeed, fail, are cancelled, or expire. Completion progress does not run the parent or consume attempts. The resumed handler still starts from the beginning. For mixed tasks, submit the same item shape with different task values and use context.join(children) to read raw results.
Runlane sets no count cap on named batches or joined lists. A batch that exceeds the driver's atomic capacity fails with storage_limit_exceeded and no partial write. You can submit smaller named batches; each call is atomic for its own missing children. Runlane reads joined results in bounded pages, but the stored wait includes every distinct child ID and must fit the product record limit. See durable steps for the exact contract.
Cancel awaited children
Cancelling a parent parked on join(), step.triggerAndWait(), or step.triggerBatchAndWait() cancels unfinished children the parent created and awaited. This includes all concurrent step.triggerAndWait() siblings admitted together and every member of a group wait. This repeats for children waiting on their own children. Unjoined children keep running, including context.trigger(), context.triggerBatch(), and context.step.trigger() calls without a join. A time, signal, or token pause that wins the same park still cancels admitted named awaited siblings. Cancellation also covers queued, retrying, scheduled, and running parents when they move into cancelled.
A child keeps running if another run is registered on it or another parent has a pending or held named binding to it. A child reused from a different creator through idempotency or debounce also keeps running.
A raw context.join() from a run that did not create the child does not guarantee protection from the creator's cancellation. A group registers one member at a time; later members can still be cancelled. The joiner receives their cancelled results and resumes normally. Use a named step trigger or an idempotent child of your own when you need that guarantee. See the full cancellation rules, including recovery after a restart.
Inspect the relationship
Operator reads can filter by sourceRunId. Both trigger forms link newly created children to their parent. A reused business-idempotent or debounced child keeps its original creation source.
Verify the flow
- Retry the parent and confirm the named step returns the same child.
- Confirm the child has the expected source run id and trace carrier.
- Confirm the parent can finish independently when no join is required.
- Test failed, cancelled, and expired child results, and completion recovery after restarting a worker.
- Test child queue and concurrency policy separately from the parent.
Read wait without failing before adding a child join.
Child triggers follow saved changes and delivery errors. Named batches report real run IDs without a batch ID. With context.step.triggerAndWait() or triggerBatchAndWait(), a first-use child and parent park commit together. A failed immediate child wakeup leaves that committed release intact. The handler stays suspended until child completion, so it has no result on which to read deliveryError during suspension. Logs and the child-and-park span record the failure; maintenance delivers the saved wakeup. Do not replay creation to recover delivery.