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
createInstance
Creates a new workflow process instance with the given input.
Creates a new instance of the specified workflow process and begins execution.
The workflow ID is extracted from the id field in the input data.
Returns a unique workflow ID that can be used to track, query, or send events
to the running workflow.
Parameters
- processFunction
function() ()- The process function to execute (must be annotated with @Process)
- input map<anydata> - The workflow input data (must contain "id" field for correlation)
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 createInstance 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.
sendEvent
function sendEvent( function() () processFunction, map<anydata> eventData, string? signalName) returns boolean|errorSends an event (signal) to a running workflow process.
Events can be used to communicate with running workflows and trigger state changes.
The workflow can wait for and react to these events using workflow primitives.
The id field in the event data is used to identify the target workflow instance.
Parameters
- processFunction
function() ()- The process function that identifies the workflow type
- eventData map<anydata> - The signal data (must contain "id" field for workflow correlation)
- signalName string? (default ()) - Optional name of the signal. This should match a field name in the workflow's events record parameter. If not provided, defaults to process name.
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 Temporal
callActivity
function callActivity( function() () activityFunction, Parameters args, 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.
Example:
string result = check ctx->callActivity(sendEmailActivity, {"email": recipientEmail, "subject": subject}); // For activities with no parameters, pass an empty record: string result = check ctx->callActivity(noArgActivity, {});
Parameters
- activityFunction
function() ()- The activity function to execute (must be annotated with @Activity)
- args Parameters (default {}) - Record containing the arguments to pass to the activity function
- 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.
Enums
workflow: Provider
Supported workflow providers.
Members
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: Process
Marks a function as a workflow process.
A process function defines the main workflow logic that orchestrates activities and handles workflow state. Process 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 Temporal 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: AuthConfig
Authentication configuration for workflow provider.
Fields
- apiKey string?(default ()) - Optional API key for authentication
- mtlsCert string?(default ()) - Optional mTLS certificate path
- mtlsKey string?(default ()) - Optional mTLS private key path
workflow: CorrelatedData
Data type with correlation keys for workflow-signal matching.
When using correlation keys, define your input and signal types with readonly fields.
The readonly fields become correlation keys that the workflow engine uses to:
- Generate a composite workflow ID (e.g., "processName-customerId=C123-orderId=O456")
- Create Temporal Search Attributes for workflow discovery
- Validate signal data has matching correlation keys
Example with readonly correlation keys:
# Workflow input with correlation keys type OrderInput record {| readonly string customerId; // Correlation key readonly string orderId; // Correlation key string product; // Regular field int quantity; // Regular field |}; # Signal data MUST have same readonly fields (name and type) type PaymentSignal record {| readonly string customerId; // Must match OrderInput.customerId readonly string orderId; // Must match OrderInput.orderId decimal amount; // Signal-specific data string paymentMethod; |}; @workflow:Process function orderProcess(workflow:Context ctx, OrderInput input, record {| future<PaymentSignal> payment; |} events) returns OrderResult|error { PaymentSignal payment = check events.payment; // Wait for payment signal // ... }
The compiler plugin validates that:
- Signal types have the same readonly fields (name AND type) as the input type
- If no readonly fields exist, falls back to requiring an "id" field
At runtime, sending a signal like:
workflow:sendEvent("payment", {customerId: "C123", orderId: "O456", amount: 99.99});
Will automatically find the workflow with matching correlation keys.
Fields
- anydata... - Rest field
workflow: CorrelatedInput
Type constraint for process input with correlation keys. Use this as a type constraint when you want to enforce correlation key pattern.
Example:
type MyInput record {| *workflow:CorrelatedInput; // Inherit readonly id string data; |};
Fields
- idreadonly string - The correlation identifier (readonly for type safety)
- anydata... - Rest field
workflow: InputData
Base input data type for workflow and signal data.
All workflow inputs and signal data must include a mandatory "id" field
which is used internally by the workflow engine for correlation.
This is a type alias for documentation purposes - use map<anydata> with "id" field.
Expected structure:
{ id: "unique-identifier", ... // other fields }
Fields
- id string - Unique identifier for the workflow instance or signal (used for correlation)
- anydata... - Rest field
workflow: Parameters
Record type for activity parameters. Used to pass arguments to activity functions in a type-safe manner.
Fields
- anydata... - Rest field
workflow: TemporalParams
Temporal-specific 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)
- authentication AuthConfig?(default ()) - Optional authentication configuration
workflow: WorkflowConfig
Workflow module configuration. This is a generic configuration that can support multiple providers.
Fields
- provider Provider(default TEMPORAL) - The workflow provider to use (currently only TEMPORAL is supported)
- url string(default "localhost:7233") - URL of the workflow server (default: "localhost:7233")
- namespace string(default "default") - Workflow namespace (default: "default")
- params TemporalParams(default {}) - Provider-specific parameters
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
Errors
workflow: DuplicateWorkflowError
Error type alias for duplicate workflow errors. When a workflow with the same correlation keys already exists, an error is thrown with "DuplicateWorkflowError" in the message. Check error message for details.
Simple name reference types
workflow: WorkflowData
WorkflowData
Workflow input data type alias. Used when starting a workflow. The "id" field becomes the workflow ID in Temporal.
workflow: SignalData
SignalData
Signal input data type alias. Used when sending signals. The "id" field identifies the target workflow instance.
Import
import ballerina/workflow;Other versions
0.1.0
Metadata
Released date: 9 days ago
Version: 0.1.0
License: Apache-2.0
Compatibility
Platform: java21
Ballerina version: 2201.13.0
GraalVM compatible: No
Pull count
Total: 3
Current verison: 3
Weekly downloads
Keywords
workflow
Contributors
Dependencies