4.8.12. Cancel a Workflow Execution

In this chapter, you'll learn how to cancel a workflow execution and revert its steps.

How to Cancel a Workflow Execution?#

Every workflow you create with createWorkflow has a cancel method. When you cancel a workflow execution, Medusa runs the compensation function of every step that ran, in reverse order, then sets the execution's state to reverted.

You can cancel a workflow execution while it's still running, such as a Long-Running Workflow, or after it finished.

To cancel a workflow execution, pass its transaction to the cancel method:

Code
1import { helloWorkflow } from "../workflows/hello"2
3const { transaction } = await helloWorkflow(container).run({4  input: {},5})6
7await helloWorkflow(container).cancel({8  transaction,9})

Medusa compensates the steps that ran in helloWorkflow, then marks the execution as reverted.

Tip: The cancel method throws an error if the execution already failed, reverted, or is compensating.

Cancel by Transaction ID#

Instead of the transaction, you can pass the ID of the execution's transaction to the cancel method. This is useful when you cancel the execution in a different request or process than the one that ran the workflow:

Code
1await helloWorkflow(container).cancel({2  transactionId: "123",3})

Medusa loads the execution from the database, so this only works if the workflow stores its executions. Otherwise, Medusa removes the execution once it's done, and the cancel method throws a Transaction {id} could not be found error.

To cancel a completed execution by its transaction ID, set the store and retentionTime options when you create the workflow:

Code
1export const helloWorkflow = createWorkflow(2  {3    name: "hello-workflow",4    retentionTime: 3600,5    store: true,6  },7  () => {8    step1()9  }10)

Medusa enables the store option by default for long-running workflows, workflows with a timeout, and idempotent workflows. Even then, you still need the retentionTime option to cancel an execution after it's done.

Note: If you don't want to store the workflow's executions, keep a reference to the transaction that the run method returns and pass it to the cancel method instead.
Was this chapter helpful?
Ask Bloom
For assistance in your development, use Claude Code Plugins or Medusa MCP server in Cursor, VSCode, etc...FAQ
What is Medusa?
How can I create a module?
How can I create a data model?
How do I create a workflow?
How can I extend a data model in the Product Module?
Recipes
How do I build a marketplace with Medusa?
How do I build digital products with Medusa?
How do I build subscription-based purchases with Medusa?
What other recipes are available in the Medusa documentation?
Chat is cleared on refresh
Line break