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:
Medusa compensates the steps that ran in helloWorkflow, then marks the execution as reverted.
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:
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:
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.
transaction that the run method returns and pass it to the cancel method instead.