4.6.3. Compensation Function

In this chapter, you'll learn how to add a compensation function to a step.

Compensation Function#

To avoid data inconsistency when an error is thrown in a workflow, define a function (called a compensation function) and pass it as a second parameter to the createStep function.

For example:

src/workflows/hello-world.ts
5} from "@medusajs/workflows-sdk"6
7const step1 = createStep(8  "step-1",9  async () => {10    const message = `Hello from step one!`11
12    console.log(message)13
14    return new StepResponse(message)15  },16  async () => {17    console.log("Oops! Rolling back my changes...")18  }19)

Each step can have a compensation function. The compensation function only runs if an error occurs throughout the workflow. It’s useful to undo or roll back actions you’ve performed in a step.


Test the Compensation Function#

  1. Add another step that throws an error:
src/workflows/hello-world.ts
1// ...2const step2 = createStep(3  "step-2",4  async () => {5    throw new Error("Throwing an error...")6  }7)
  1. Use the steps in a workflow. For example:
src/workflows/hello-world.ts
6// ...7
8type WorkflowOutput = {9  message: string10}11
12const myWorkflow = createWorkflow<13  {},14  WorkflowOutput15>("hello-world", function (input) {16  const str1 = step1()17  step2()18
19  return {20    message: str1,21  }22})23
24export default myWorkflow
  1. Execute the workflow from a resource, such as an API route:
src/api/store/workflow/route.ts
5import myWorkflow from "../../../workflows/hello-world"6
7export async function GET(8  req: MedusaRequest,9  res: MedusaResponse10) {11  const { result } = await myWorkflow(req.scope)12    .run()13
14  res.send(result)15}
  1. Run the Medusa application:
  1. Send a GET request to /store/workflow:
curl http://localhost:9000/store/workflow

In the console, you'll see:

  • Hello from step one! logged in the terminal, indicating that the first step ran successfully.
  • Oops! Rolling back my changes... logged in the terminal, indicating that the second step failed and the compensation function of the first step ran consequently.
Was this chapter helpful?