mastra-workflow-suspend-resume
Skill2 starsChanged 29 days agoApache-2.0View on GitHub
Pause and continue Mastra workflow runs: suspend() inside a step, resumeSchema and suspendSchema, run.resume and resumeStream, human-in-the-loop approvals with bail for rejection, resuming by run ID after a restart, foreach iteration resume, workflow snapshots in storage, the workflow state reader, run statuses, restart of active runs, and time travel to re-run from any step. Use this skill whenever a workflow must wait for a person, a webhook, an external job, or a timer, or when the user needs to recover, inspect, retry, or debug a stored run. Triggers on suspend, resume, resumeData, suspendData, suspendPayload, result.suspended, run.resume, resumeStream, forEachIndex, resumeLabel, createWorkflowStateReader, getWorkflowRunById, loadWorkflowSnapshot, workflow_snapshots, timeTravel, timeTravelStream, restart, WORKFLOW_RESUME_ALREADY_CLAIMED, approval step, human approval in a workflow. Also triggers for long-running or multi-day processes built with Mastra workflows.
In this repository46 other files it gives its agents.
- mastra-a2a-acpSkill
- mastra-agent-approval-hitlSkill
- mastra-agentic-uiSkill
- mastra-agent-skillsSkill
- mastra-agentsSkill
- mastra-authSkill
- mastra-browserSkill
- mastra-build-playbookSkill
- mastra-channelsSkill
- mastra-classifierSkill
- mastra-cli-apiSkill
- mastra-client-sdkSkill
- mastra-datasets-experimentsSkill
- mastra-deploymentSkill
- mastra-evalsSkill
- mastra-file-based-agentsSkill
- mastra-framework-integrationSkill
- mastra-guideSkill
- mastra-harnessSkill
- mastra-knowledgeSkill
- mastra-mcpSkill
- mastra-memorySkill
- mastra-migrationsSkill
- mastra-modelsSkill
- mastra-multi-agentSkill
- mastra-observabilitySkill
- mastra-observational-memorySkill
- mastra-platformSkill
- mastra-processors-guardrailsSkill
- mastra-project-setupSkill
- mastra-ragSkill
- mastra-schedulesSkill
- mastra-semantic-recallSkill
- mastra-serverSkill
- mastra-signalsSkill
- mastra-storageSkill
- mastra-streamingSkill
- mastra-structured-outputSkill
- mastra-studio-editorSkill
- mastra-tool-integrationsSkill
- mastra-toolsSkill
- mastra-troubleshootingSkill
- mastra-vector-storesSkill
- mastra-voiceSkill
- mastra-workflowsSkill
- mastra-workspace-sandboxSkill
The file
We split this skill into the rules it gives an agent
5 rules. About 0 are common, 0 are distinctive, and 5 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈0
Distinctive · estimate
This author's own choices. Worth a look.
5
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 113
Verify the API: If node_modules/@mastra/ exists, read node_modules/@mastra/core/dist/docs/ and the installed Run types.
- Very specific: line 114
Configure storage: Add a persistent adapter to new Mastra({ storage }) (for example LibSQLStore with url: 'file:./mastra.db').
- Very specific: line 115
Design the pause: Write suspendSchema (what the reviewer sees) and resumeSchema (what they send back).
- Very specific: line 116
Write the suspend condition: Read resumeData ?? {}. Handle rejection first (bail()), then suspend when input is missing, then continue.
- Very specific: line 119
Recover and inspect: Use workflow.getWorkflowRunById(runId) with createWorkflowStateReader() to find suspended steps and resume labels.
≈ “Common” is an estimate: at least 1 in 5 of the 408,460 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Mastra Workflow Suspend and Resume
Pause a workflow inside a step, persist its snapshot, and continue it later with typed resume data. Use the same snapshots to recover runs, inspect them, and re-execute from any step with time travel.
When to use
- A step needs a human decision (approve, reject, edit) before continuing
- A step waits for an external event: webhook, payment callback, batch job, file upload
- Multi-stage approvals where each stage suspends in turn
- Resuming a run from an HTTP handler or a different process using only its
runId - Approving
.foreach()items one at a time - Inspecting a stored run, finding which step is suspended, and why
- Re-running a failed step with corrected input (time travel)
- Restarting runs that were active when a server died
When NOT to use
- Building the workflow graph, schemas, and control flow (use
mastra-workflows) - Approving an agent's tool calls, or agent-level human-in-the-loop (use
mastra-agent-approval-hitl) - Choosing and configuring a storage adapter (use
mastra-storage) - Fixed delays without a step context (
.sleep()and.sleepUntil()are covered inmastra-workflows) - Durable agents and background tasks (use
mastra-harness) - Resuming runs from a frontend over HTTP (use
mastra-client-sdk)
Required inputs
- Which step pauses and what it waits for
- The payload shown to whoever resumes it (
suspendSchema) - The data needed to continue (
resumeSchema) - What happens on rejection: bail with success, throw, or branch
- The storage adapter (snapshots must outlive the process in production)
- Who resumes the run and how they get the
runId(UI, webhook, queue)
The framework: suspend, persist, resume
A step suspends by returning suspend(payload). Mastra writes a snapshot to storage and the run returns status: 'suspended'. Later, run.resume({ step, resumeData }) reloads the snapshot and re-executes that step with resumeData set.
// src/mastra/workflows/approval-workflow.ts
import { createStep, createWorkflow } from '@mastra/core/workflows'
import { z } from 'zod'
export const approvalStep = createStep({
id: 'approval-step',
inputSchema: z.object({ requestId: z.string() }),
outputSchema: z.object({ result: z.string() }),
suspendSchema: z.object({ reason: z.string() }),
resumeSchema: z.object({ approved: z.boolean() }),
execute: async ({ inputData, resumeData, suspend, bail }) => {
const { approved } = resumeData ?? {}
if (approved === false) return bail({ result: 'Rejected' })
if (!approved) {
return await suspend({ reason: `Request ${inputData.requestId} needs approval` })
}
return { result: `Request ${inputData.requestId} approved` }
},
})
export const approvalWorkflow = createWorkflow({
id: 'approval-workflow',
inputSchema: z.object({ requestId: z.string() }),
outputSchema: z.object({ result: z.string() }),
})
.then(approvalStep)
.commit()const workflow = mastra.getWorkflow('approvalWorkflow')
const run = await workflow.createRun()
const result = await run.start({ inputData: { requestId: 'r-42' } })
if (result.status === 'suspended') {
const path = result.suspended[0] // e.g. ['approval-step']
console.log(result.steps[path[0]].suspendPayload) // { reason: '...' }
// later, possibly in another process:
const resumed = await run.resume({ step: approvalStep, resumeData: { approved: true } })
}Execute params on resume:
| Param | First run | After resume |
resumeData | undefined | Typed by resumeSchema |
suspendData | undefined | The payload passed to suspend() |
state | Current state | State saved before the suspend |
step accepts a step object (typed resumeData), a step ID, or a path array. Omit it only when exactly one step is suspended.
Workflow
- Verify the API. If
node_modules/@mastra/exists, readnode_modules/@mastra/core/dist/docs/and the installedRuntypes. Otherwise fetchhttps://mastra.ai/docs/workflows/suspend-and-resume.md,https://mastra.ai/reference/workflows/run-methods/resume.md, andhttps://mastra.ai/docs/workflows/time-travel.md. Trust these over memory. - Configure storage. Add a persistent adapter to
new Mastra({ storage })(for exampleLibSQLStorewithurl: 'file:./mastra.db'). In-memory storage loses suspended runs on restart. - Design the pause. Write
suspendSchema(what the reviewer sees) andresumeSchema(what they send back). Keep both small and JSON-serializable. - Write the suspend condition. Read
resumeData ?? {}. Handle rejection first (bail()), then suspend when input is missing, then continue. - Expose the pause. Persist or return
runIdandsuspendPayloadto the UI, ticket, or message that collects the decision. - Resume. Rebuild the run with
workflow.createRun({ runId }), then callrun.resume({ step, resumeData }). CatchWORKFLOW_RESUME_ALREADY_CLAIMEDfor double-clicks and retried webhooks. - Recover and inspect. Use
workflow.getWorkflowRunById(runId)withcreateWorkflowStateReader()to find suspended steps and resume labels. - Debug with time travel. Re-run from a step with
run.timeTravel({ step, inputData })once the cause is fixed. - Test each path: suspend, approve, reject, double resume, resume after restart.
Deep dive: resuming later and recovering runs
Resume from anywhere with only the runId:
import { createWorkflowStateReader } from '@mastra/core/workflows'
const workflow = mastra.getWorkflow('approvalWorkflow')
const state = await workflow.getWorkflowRunById(runId)
if (state?.status === 'suspended') {
const reader = createWorkflowStateReader(state)
const suspendedStep = reader.getSuspendedStep()
const label = reader.getResumeLabel('approve')
const run = await workflow.createRun({ runId: state.runId })
try {
await run.resume({
step: label?.stepId ?? suspendedStep?.path,
resumeData: { approved: true },
forEachIndex: label?.foreachIndex,
})
} catch (error) {
if (error.id === 'WORKFLOW_RESUME_ALREADY_CLAIMED') {
// Another caller is continuing this run. Re-read state instead.
}
}
}- Name a pause with
suspend(payload, { resumeLabel: 'approve' })so callers can find it by label. - In
.foreach(), each iteration suspends on its own. PassforEachIndex(zero-based) to resume one item. Omit it to resume all with the same data. - Nested workflows report paths such as
['nested-workflow', 'step-1']. Pass the whole path asstep. - With
run.stream(), the stream closes on suspend by default (closeOnSuspend: true). Continue withrun.resumeStream({ resumeData }). .sleep()sets statuswaiting;suspend()setssuspended. Only suspended steps takeresumeData.
Failure patterns
- No storage or
:memory:storage in production. Suspended runs vanish on restart. Use a persistent adapter. resumeData.approvedwithout a fallback.resumeDataisundefinedon the first run. Destructure fromresumeData ?? {}.- Treating
falseandundefinedthe same. A rejection then suspends again forever. Checkapproved === falsebefore!approved. - Forgetting
returnbeforesuspend(). Code after it runs. Writereturn await suspend({...}). - Resuming with a fresh
createRun(). That creates a new run. Pass{ runId }from the suspended run. - Omitting
stepwith several suspended steps. Resume fails. Pass the step, ID, or path fromresult.suspended. - Reading
result.suspended[0]as a string. Each entry is a path array. Useresult.steps[path[0]]for the payload. - Double resume from a retried webhook. The second call throws
WORKFLOW_RESUME_ALREADY_CLAIMED(HTTP 409). Catch it and re-read state. Adapters without atomic updates (ClickHouse, Cloudflare D1, KV, Durable Objects, LanceDB, Redis) cannot enforce this claim. - Large objects in
suspend()payloads. Snapshots bloat. Store IDs and fetch data on resume. - Time travel on a running run. It throws (
WORKFLOW_TIME_TRAVEL_RUN_RUNNING). Wait for the run to finish or suspend. - Time travel after renaming steps. It fails before running anything. Keep step IDs stable.
Output format
A finished suspend and resume delivery contains:
- Steps with
suspendSchema,resumeSchema, and a rejection path - Persistent
storageon theMastrainstance - A resume entry point (route, webhook handler, or job) that rebuilds the run by
runIdand handles the already-claimed error - A way to show
suspendPayloadto the person or system that resumes - Tests or Studio runs for approve, reject, double resume, and resume after restart
Reference files
references/api.md-suspend(), resume and stream options, run statuses, snapshot anatomy, state reader functions, restart, time travel parameters and errors.references/examples.md- Approval endpoint with resume by run ID, multi-stage approvals, per-item foreach approval, recovering a failed run with time travel.references/checklist.md- Production checklist for pausable workflows.
Live docs
- https://mastra.ai/docs/workflows/suspend-and-resume
- https://mastra.ai/docs/workflows/human-in-the-loop
- https://mastra.ai/docs/workflows/snapshots
- https://mastra.ai/docs/workflows/time-travel
- https://mastra.ai/reference/workflows/run-methods/resume
- https://mastra.ai/reference/workflows/run-methods/timeTravel
- https://mastra.ai/reference/workflows/workflow-state-reader
- https://mastra.ai/reference/streaming/workflows/resumeStream
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

