Skip to main content
Workflow is a system for defining long-running tasks that execute in the background. Using the @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 like input, step, and logger.
Key Parameters:
  • name: Workflow identifier (must be unique)
  • input: Input data passed to the Workflow
  • step: Step execution object (divides and manages tasks)
  • logger: Logging object (records execution state)
If you omit the workflow name, it will be automatically set by converting the function name to snake_case. Example: sendWelcomeEmail -> send_welcome_email

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.
Execution Flow:
  1. API calls Sonamu.workflows.run()
  2. Workflow is added to the queue and returns immediately
  3. Worker picks up the Workflow from the queue and executes it
  4. Execution results are stored in the database

Direct Execution

You can also run directly from scripts or other Workflows. Use handle.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.
Schema Validation Benefits:
  • 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.
Use Cases:
  • Email template changes
  • Data processing logic improvements
  • External API integration changes
When changing versions, existing running Workflows need the old version logic to still exist in the code to complete. Verify all executions are completed before deleting old version code.

Scheduling

Using Cron expressions, you can automatically run Workflows on a schedule. Use this for daily report generation, periodic data backups, and more.
Cron Expression Guide:
Providing a function for the input parameter allows you to dynamically generate data at execution time.

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.
Practical Applications:
  • 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.
Key Points:
  • 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.
Benefits:
  • 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.
Use Cases:
  • 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.
  1. Pause: Click the “Pause” button on Workflow cards with pending, running, or sleeping status
  2. Resume: Click the “Resume” button on Workflow cards with paused status

Using the API

You can programmatically control Workflows from the backend.

Key Features

  • Idempotency Guaranteed: Calling pause on an already paused Workflow doesn’t throw an error. The same applies to resume.
  • Terminal State Protection: Workflows with completed, failed, or canceled status cannot be paused/resumed.
  • Immediate Resume: When resume is called, available_at is set to the current time, so the Worker picks up the task immediately.

Use Cases

When a Workflow is paused, the currently running Step continues until completion. Before starting the next Step, the Worker checks the paused status and stops the work.

Important Notes

Workflow Best Practices:
  1. Worker Required: A Worker process must be running to execute Workflows.
  2. Divide into Steps: Split long tasks into multiple Steps. On failure, you don’t need to re-run everything.
  3. Avoid Duplicate Schedule Names: Schedule names must be unique within the same Workflow.
  4. Timezone Configuration: Schedules follow Sonamu.config.api.timezone.
  5. Error Handling: Failed Workflows are automatically retried. Protect important tasks with try-catch.

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