Workflows
Workflows are Medusa’s orchestration engine for building reliable, distributed transactions with automatic compensation (rollback). They compose multiple steps into a single, fault-tolerant operation.Why Workflows?
Workflows solve critical challenges in distributed commerce systems:- Automatic rollback - Failed steps trigger compensation functions
- Idempotency - Steps can be safely retried
- Composability - Reuse steps across multiple workflows
- Observability - Track execution state and errors
- Background execution - Async steps for long-running operations
Workflows are the recommended way to implement business logic that spans multiple modules or requires transactional guarantees.
Creating a Step
Steps are the building blocks of workflows. Each step defines an action and optional compensation.Basic Step Pattern
packages/core/core-flows/src/api-key/steps/create-api-keys.ts:33-52
Step Response
TheStepResponse constructor accepts two arguments:
- Output - Data returned to the workflow
- Compensation data - Data passed to the compensation function
Step Context
Steps receive a context object with:container- Dependency injection containercontext- Shared context (transaction metadata, user info)transactionId- Unique transaction identifieridempotencyKey- For idempotent execution
Creating a Workflow
Workflows compose steps into a transaction with automatic compensation.Basic Workflow Pattern
packages/core/core-flows/src/api-key/workflows/create-api-keys.ts:51-64
Executing Workflows
Workflows are executed by calling them with a container and running:Workflow Composition
Transform Data
Usetransform to manipulate step outputs:
packages/core/workflows-sdk/src/utils/composer/transform.ts:34-58
Parallel Execution
Useparallelize to run steps concurrently:
packages/core/workflows-sdk/src/utils/composer/parallelize.ts:11-42
Conditional Execution
Usewhen-then for conditional step execution:
packages/core/workflows-sdk/src/utils/composer/when.ts:31-62
You cannot use regular
if statements in workflows because they evaluate at composition time, not runtime. Use when-then instead.Workflow Hooks
Hooks emit events at specific points in workflow execution:Async Steps
Steps can be marked as async for background execution:Compensation Flow
When a step fails, all previous steps are compensated in reverse order:1
Step 1 executes
Creates a product → Returns
product.id as compensation data2
Step 2 executes
Creates prices → Returns
price.ids as compensation data3
Step 3 fails
Fails to attach to sales channel → Triggers compensation
4
Step 2 compensates
Deletes prices using
price.ids5
Step 1 compensates
Deletes product using
product.idRunning Workflows as Steps
Workflows can be composed as steps in other workflows:packages/core/workflows-sdk/src/utils/composer/create-workflow.ts:203-296