Suspend and Resume in Workflows
Complex workflows often need to pause execution while waiting for external input or resources.
Mastra’s suspend and resume features let you pause workflow execution at any step, persist the workflow state, and continue when ready.
When to Use Suspend/Resume
Common scenarios for suspending workflows include:
- Waiting for human approval or input
- Pausing until external API resources become available
- Collecting additional data needed for later steps
- Rate limiting or throttling expensive operations
Basic Suspend Example
Here’s a simple workflow that suspends when a value is too low and resumes when given a higher value:
const stepTwo = new Step({
id: "stepTwo",
outputSchema: z.object({
incrementedValue: z.number(),
}),
execute: async ({ context, suspend }) => {
if (context.steps.stepOne.status !== "success") {
return { incrementedValue: 0 };
}
const currentValue = context.steps.stepOne.output.doubledValue;
if (currentValue < 100) {
await suspend();
return { incrementedValue: 0 };
}
return { incrementedValue: currentValue + 1 };
},
});
Watching and Resuming
To handle suspended workflows, use the watch
method to monitor workflow status and resume
to continue execution:
import { mastra } from "./index";
// Get the workflow
const myWorkflow = mastra.getWorkflow('myWorkflow');
const { runId, start } = myWorkflow.createRun();
// Start watching the workflow before executing it
myWorkflow.watch(async ({ context, activePaths }) => {
for (const _path of activePaths) {
const stepTwoStatus = context.steps?.stepTwo?.status;
if (stepTwoStatus === 'suspended') {
console.log("Workflow suspended, resuming with new value");
// Resume the workflow with new context
await myWorkflow.resume({
runId,
stepId: 'stepTwo',
context: { secondValue: 100 },
});
}
}
})
// Start the workflow execution
await start({ triggerData: { inputValue: 45 } });
Related Resources
- See the Suspend and Resume Example for a complete working example
- Check the Step Class Reference for suspend/resume API details
- Review Workflow Observability for monitoring suspended workflows