What is a Workflow?
A workflow is:- A sequence of steps that execute in order
- Transactional - all steps succeed or all are rolled back
- Composable - workflows can call other workflows
- Asynchronous - steps can run in the background
- Type-safe - fully typed inputs and outputs
Creating Your First Workflow
Create a Step
Steps are the building blocks of workflows. Each step has an invocation function and optional compensation function:The
src/workflows/brand/steps/create-brand.ts
StepResponse takes two arguments:- The output of the step (returned to the workflow)
- Data to pass to the compensation function if rollback is needed
Create the Workflow
Compose steps into a workflow using
createWorkflow:src/workflows/brand/create-brand.ts
Advanced Workflow Patterns
Multiple Steps with Compensation
Here’s a complete example showing multiple steps with compensation:src/workflows/brand/steps/delete-brand.ts
src/workflows/brand/delete-brand.ts
Transform Data Between Steps
Usetransform to manipulate data between steps:
Conditional Execution
Usewhen to conditionally execute steps:
Parallel Execution
Useparallelize to run independent steps concurrently:
Query Data in Workflows
UseuseQueryGraphStep to fetch data:
Step Context
The step context provides access to:container- Dependency injection containercontext- Shared context across stepsmetadata- Additional metadataidempotencyKey- Unique key for idempotent execution
Error Handling
Workflows automatically handle errors and trigger compensation:Workflow Hooks
Hooks allow you to emit events when a workflow completes:Best Practices
- Keep steps focused on a single responsibility
- Always provide compensation functions for steps that modify data
- Use
transformfor data manipulation instead of complex logic in steps - Name steps and workflows descriptively
- Type your inputs and outputs for type safety
- Use
parallelizefor independent operations - Handle errors with proper MedusaError types
- Test workflows in isolation
Next Steps
Create API Routes
Build HTTP endpoints that use workflows
Event Subscribers
React to workflow events and hooks