workflow
Module workflow
API
ballerina/workflow Ballerina library
Ballerina Workflow Library
The ballerina/workflow library provides support for creating and managing workflows in Ballerina applications.
Functions
getWorkflowInfo
function getWorkflowInfo(string workflowId) returns WorkflowExecutionInfo|errorGets information about a workflow execution without waiting for completion. Returns the current state including any activity invocations. Used for testing to inspect workflow state during execution.
Parameters
- workflowId string - The ID of the workflow to get info for
Return Type
- WorkflowExecutionInfo|error - The workflow execution info, or an error
getWorkflowResult
function getWorkflowResult(string workflowId, int timeoutSeconds) returns WorkflowExecutionInfo|errorGets the execution result of a workflow. This function waits for the workflow to complete and returns its result. Used for testing to verify workflow execution outcomes.
Parameters
- workflowId string - The ID of the workflow to get the result for
- timeoutSeconds int (default 30) - Maximum time to wait for the workflow to complete
Return Type
- WorkflowExecutionInfo|error - The workflow execution info including result, or an error
registerProcess
function registerProcess( function() () processFunction, string processName, map< function() () >? activities) returns boolean|errorRegisters a workflow process function with the singleton worker.
Makes the process available for execution when run is called.
The process is registered with the singleton worker that was created at
module initialization time. This function should be called during
application initialization to register all workflow processes.
run
Runs a new workflow instance.
Creates a new instance of the specified workflow and begins execution. Returns a unique workflow ID that can be used to track, query, or send signals to the running workflow.
Parameters
- processFunction
function() ()- The process function to execute (must be annotated with @Workflow)
- input map<anydata>? (default ()) - Optional workflow input data. If nil, the workflow is created with no input.
sendData
function sendData( function() () workflow, string workflowId, string dataName, anydata data) returns error?Sends data to a running workflow process.
Data can be sent to running workflows to trigger state changes. The workflow can wait for and react to this data using future-based event handling.
Parameters
- workflow
function() ()- The workflow function that identifies the workflow type (must be annotated with @Workflow)
- workflowId string - The unique workflow ID to send the data to (obtained from
run)
- dataName string - The name identifying the data. Must match a field name in the workflow's events record parameter.
- data anydata - The data to send to the workflow
Return Type
- error? - An error if sending fails, otherwise nil
Clients
workflow: Context
Workflow execution context providing workflow APIs. This is a client object that provides access to workflow operations.
This client provides:
- Activity execution via
callActivityremote method - Durable sleep operations
- Workflow state queries (replaying status, workflow ID, workflow type)
Use check ctx->callActivity(myActivity, {"arg1": val1, "arg2": val2}) to execute activities.
Use Ballerina's wait action with event futures for signal handling.
Constructor
Initialize the context with native workflow context handle.
init (handle nativeContext)- nativeContext handle - Native context handle from the workflow engine
callActivity
function callActivity( function() () activityFunction, map<anydata> args, ActivityOptions? options, typedesc<anydata> T) returns T|errorExecutes an activity function within the workflow context.
Activities are non-deterministic operations (I/O, database calls, external APIs) that should only be executed once during workflow execution and not during replay. The workflow runtime ensures exactly-once execution semantics for activities.
The return type is determined by the T typedesc parameter, allowing compile-time
type checking when the expected return type is specified. The compiler plugin
validates that the activity function's return type is compatible with T.
By default, if the activity function returns an error, it is treated as a failure
and the engine will retry the activity based on the retry policy. To treat errors
as normal completion values, set failOnError to false in the options.
Example:
// Basic activity call (errors cause failure + retry by default) string result = check ctx->callActivity(sendEmailActivity, {email: recipientEmail, subject: subject}); // With custom retry policy string result = check ctx->callActivity(sendEmailActivity, {email: recipientEmail}, options = {retryPolicy: {maximumAttempts: 3, initialIntervalInSeconds: 2}}); // Treat errors as normal completion (no retry on error) string|error result = ctx->callActivity(riskyActivity, {data: input}, options = {failOnError: false});
Parameters
- activityFunction
function() ()- The activity function to execute (must be annotated with @Activity)
- args map<anydata> (default {}) - Map containing the arguments to pass to the activity function
- options ActivityOptions? (default ()) - Optional activity options for retry policy and error handling behavior
- T typedesc<anydata> (default <>) - The expected return type (inferred from context or explicitly specified)
Return Type
- T|error - The result of the activity execution cast to type T, or an error if execution fails
sleep
Durable sleep that survives workflow restarts.
Unlike regular sleep, this is persisted and will continue counting even if the workflow is replayed or the worker restarts.
Parameters
- duration Duration - Duration to sleep
Return Type
- error? - Error if sleep fails
isReplaying
function isReplaying() returns booleanCheck if the workflow is currently replaying history.
Useful for skipping side effects that should only happen on first execution. For example, logging or metrics that shouldn't be duplicated during replay.
Return Type
- boolean - True if replaying, false if first execution
getWorkflowId
Get the unique workflow ID.
getWorkflowType
Get the workflow type name.
Annotations
workflow: Activity
Marks a function as a workflow activity.
An activity function performs non-deterministic operations such as I/O, database calls, external API calls, or any operation with side effects. Activities are executed exactly once by the workflow runtime, even during workflow replay after failures.
Example
workflow: Workflow
Marks a function as a workflow.
A workflow function defines the main workflow logic that orchestrates activities and handles workflow state. Workflow functions must be deterministic - they should produce the same results given the same inputs and should not perform I/O directly. Use activities for non-deterministic operations.
Example
Configurables
workflow: workflowConfig
The workflow module configuration. This is read from Config.toml or set programmatically. Defaults to connecting to a local development server.
Records
workflow: ActivityInvocation
Information about an activity invocation (for testing/introspection).
Fields
- activityName string - The name of the activity that was invoked
- input anydata[] - The arguments passed to the activity
- output anydata? - The result returned by the activity (nil if not yet completed or failed)
- status string - The status of the activity execution ("COMPLETED", "FAILED", "RUNNING", "PENDING")
- errorMessage string? - Error message if the activity failed
workflow: ActivityOptions
Options for activity execution via callActivity.
Allows configuring retry behavior and error handling semantics per activity call.
Fields
- retryPolicy? ActivityRetryPolicy - Retry policy for the activity (optional, uses the global default
from
WorkerConfig.defaultActivityRetryPolicyif not set)
- failOnError boolean(default true) - If
true(default), an error returned by the activity function is treated as a failure, triggering engine retries based on the retry policy. Iffalse, an error is treated as a normal completion value and no retries are attempted.
workflow: ActivityRetryPolicy
Retry policy for activity execution. Controls how the workflow engine retries failed activity executions.
Fields
- initialIntervalInSeconds int(default 1) - Initial delay before the first retry attempt (default: 1 second)
- backoffCoefficient decimal(default 2.0) - Multiplier applied to the interval after each retry (default: 2.0)
- maximumIntervalInSeconds? int - Maximum delay between retries (optional, no cap if not set)
- maximumAttempts int(default 1) - Maximum number of retry attempts (default: 1, meaning no retries)
workflow: AuthConfig
Authentication configuration for workflow server connections.
Supports API key authentication and mutual TLS (mTLS). For cloud deployments, provide either an API key or mTLS certificate/key pair. For self-hosted deployments, configure based on your server's security setup.
Fields
- apiKey string?(default ()) - API key for bearer token authentication
- mtlsCert string?(default ()) - Path to the mTLS client certificate file
- mtlsKey string?(default ()) - Path to the mTLS client private key file
workflow: CloudConfig
Configuration for connecting to a managed cloud deployment. All connection and authentication parameters are mandatory.
Fields
- mode "CLOUD" - Deployment mode identifier (always "CLOUD")
- url string - Cloud server URL (e.g., "<namespace>.<account>.tmprl.cloud:7233")
- namespace string - Cloud namespace (e.g., "<namespace>.<account>")
- auth AuthConfig - Authentication configuration (required for cloud)
- params WorkerConfig(default {}) - Worker configuration parameters
workflow: InMemoryConfig
Configuration for an in-memory workflow engine.
No external server is required. Workflows are not persisted and will be lost on restart.
Signal-based communication via sendData is supported when the workflow ID is known.
Fields
- mode "IN_MEMORY" (default "IN_MEMORY") - Deployment mode identifier (always "IN_MEMORY")
workflow: LocalConfig
Configuration for connecting to a local development server.
Defaults are tuned for a locally running workflow server (e.g., temporal server start-dev).
Fields
- mode "LOCAL" (default "LOCAL") - Deployment mode identifier (always "LOCAL")
- url string(default "localhost:7233") - Server URL (default: "localhost:7233")
- namespace string(default "default") - Workflow namespace (default: "default")
- params WorkerConfig(default {}) - Worker configuration parameters
workflow: SelfHostedConfig
Configuration for connecting to a self-hosted server deployment. Supports optional authentication for secured installations.
Fields
- mode "SELF_HOSTED" - Deployment mode identifier (always "SELF_HOSTED")
- url string - Server URL (e.g., "temporal.mycompany.com:7233")
- namespace string(default "default") - Workflow namespace (default: "default")
- auth AuthConfig?(default ()) - Optional authentication configuration
- params WorkerConfig(default {}) - Worker configuration parameters
workflow: WorkerConfig
Worker configuration parameters.
Fields
- taskQueue string(default "BALLERINA_WORKFLOW_TASK_QUEUE") - The task queue for workflow execution (default: "BALLERINA_WORKFLOW_TASK_QUEUE")
- maxConcurrentWorkflows int(default 100) - Maximum number of concurrent workflow executions (default: 100)
- maxConcurrentActivities int(default 100) - Maximum number of concurrent activity executions (default: 100)
- defaultActivityRetryPolicy ActivityRetryPolicy(default {}) - Default retry policy applied to all activity executions
unless overridden per-call via
ActivityOptions.retryPolicy
workflow: WorkflowExecutionInfo
Information about a workflow execution (for testing/introspection).
Fields
- workflowId string - The unique identifier for the workflow instance
- workflowType string - The type (process name) of the workflow
- status string - The execution status ("RUNNING", "COMPLETED", "FAILED", "CANCELED", "TERMINATED")
- result anydata? - The workflow result if completed successfully
- errorMessage string? - Error message if the workflow failed
- activityInvocations ActivityInvocation[] - List of activities invoked by this workflow
Union types
workflow: WorkflowConfig
WorkflowConfig
Workflow module configuration.
A union of deployment-specific configuration records, discriminated by the mode field.
Supported modes:
LOCAL- Local development server (default)CLOUD- Managed cloud deployment with mandatory authenticationSELF_HOSTED- Self-hosted server with optional authenticationIN_MEMORY- Lightweight in-memory engine (no persistence)
Import
import ballerina/workflow;Metadata
Released date: 3 days ago
Version: 0.2.0
License: Apache-2.0
Compatibility
Platform: java21
Ballerina version: 2201.13.0
GraalVM compatible: No
Pull count
Total: 9
Current verison: 2
Weekly downloads
Keywords
workflow
Contributors
Dependencies