@workflow decorator, you can reliably execute email sending, data processing, scheduled tasks, and more.
Basic Concepts
The purpose of a Workflow is to safely execute asynchronous tasks. Unlike API requests, Workflows:- Run for extended periods: Can execute from minutes to hours
- Are retryable: Automatically retry on failure
- Are monitored: Execution state is recorded in the database
- Are schedulable: Run periodically using Cron expressions
Basic Usage
When defining a Workflow, provide a name and an execution function. The execution function receives parameters likeinput, step, and logger.
name: Workflow identifier (must be unique)input: Input data passed to the Workflowstep: Step execution object (divides and manages tasks)logger: Logging object (records execution state)
Running Workflows
Running from API
When running a Workflow from an API endpoint, it returns immediately and the task proceeds in the background. Users don’t have to wait for long-running tasks.- API calls
Sonamu.workflows.run() - Workflow is added to the queue and returns immediately
- Worker picks up the Workflow from the queue and executes it
- Execution results are stored in the database
Direct Execution
You can also run directly from scripts or other Workflows. Usehandle.result() to wait for completion.
handle.result() waits until the Workflow completes. Don’t use this in API responses!Schema Validation
Using Zod schemas, you can automatically validate input and output data. This prevents runtime errors from invalid data and improves TypeScript type inference.- Type Safety: TypeScript accurately infers input/output types
- Runtime Validation: Verifies data format before execution
- Clear Contract: Makes the Workflow interface explicit
Version Management
When you need to change Workflow logic, specifying a version ensures existing running tasks complete with the old logic while new executions use the new logic.- Email template changes
- Data processing logic improvements
- External API integration changes
Scheduling
Using Cron expressions, you can automatically run Workflows on a schedule. Use this for daily report generation, periodic data backups, and more.Multiple Schedules
You can register multiple schedules for a single Workflow. Each schedule can pass different input data, allowing the same logic to perform different tasks.- Incremental backup: Only changed data every hour
- Full backup: All data daily
- Different timezones: Run at different times by region
Practical Examples
1. Bulk Email Sending
When sending emails to thousands of users, Workflows let you process safely without API request timeouts.- User fetching and email sending are separate Steps
- Each email creates a Step enabling individual retries
- Progress is recorded in DB for monitoring
2. Data Pipeline
You can build pipelines that fetch data from external APIs, transform it, and store it.- Even if a stage fails, don’t restart from the beginning
- Measure execution time of each stage to identify bottlenecks
- When transform logic changes, skip the collection stage
3. Scheduled Cleanup Task
Schedule automatic deletion of old data.- Log data cleanup
- Temporary file deletion
- Expired session removal
Pause and Resume
You can pause a running Workflow and resume it later. This feature is useful when managing resources or dealing with external dependency issues.State Transitions
Workflow states transition as follows:Using Sonamu UI
You can directly pause or resume running Workflows from the Tasks tab in Sonamu UI.- Pause: Click the “Pause” button on Workflow cards with
pending,running, orsleepingstatus - Resume: Click the “Resume” button on Workflow cards with
pausedstatus
Using the API
You can programmatically control Workflows from the backend.Key Features
- Idempotency Guaranteed: Calling pause on an already
pausedWorkflow doesn’t throw an error. The same applies to resume. - Terminal State Protection: Workflows with
completed,failed, orcanceledstatus cannot be paused/resumed. - Immediate Resume: When resume is called,
available_atis set to the current time, so the Worker picks up the task immediately.
Use Cases
Important Notes
Next Steps
Step
Divide tasks and implement retry strategies with Steps
Error Handling
Learn error handling patterns and compensating transactions
Worker Setup
Configure and manage the Worker process