Skip to main content

Build a Durable Workflow

  • Time: 20 minutes
  • What you'll build: A durable workflow that handles customer orders

The durable workflow reserves inventory for an order, suspends until a payment confirmation arrives, and then either emails the customer or cancels the order. Every activity result and data event is recorded, so a restart replays the record instead of reserving twice, and the wait for payment holds no thread and no connection while it lasts, whether that is seconds or days.

The finished flow has three steps:

  1. Reserve inventory as a recorded activity.
  2. Wait for a payment data event delivered from outside the workflow.
  3. Send the confirmation email when payment succeeded, or cancel the order when it did not.

The completed orderWorkflow diagram: Start, the reserveInventory activity, a Wait for payment node fed from outside the flow, and an If that branches to sendEmail on the payment path and cancelOrder on the Else pathThe completed orderWorkflow diagram: Start, the reserveInventory activity, a Wait for payment node fed from outside the flow, and an If that branches to sendEmail on the payment path and cancelOrder on the Else path

Prerequisites​

A working WSO2 Integrator environment.

  • WSO2 Cloud setup: Sign up and launch WSO2 Integrator in the browser-based cloud editor.

  • Temporal server: An internet-accessible Temporal server, such as Temporal Cloud or a publicly exposed self-hosted instance, with its endpoint URL, namespace, and credentials. See Temporal credentials.

Step 1: Create the integration​

  1. On the project home page, click Create on Cloud.

    WSO2 Cloud project home showing the Create on Cloud option

  2. The WSO2 Integrator cloud editor opens in your browser.

    WSO2 Integrator cloud editor landing page showing an empty integration and the Deploy to WSO2 Cloud panel

Note

The cloud editor creates a default integration for you, so you don't need to name it now. You can change its name when you deploy it. For more information, see Save and deploy.

Step 2: Add the durable workflow artifact​

  1. In the design view, click Add Artifact Manually.

    Integration design view with the Add Artifact manually button highlighted

  2. On the Artifacts page, under Durable Workflow, click Durable Workflow.

    Artifacts page with Durable Workflow highlighted under Durable Workflow

  3. The Create New Durable Workflow form opens.

  4. Set Name to orderWorkflow.

  5. Click the Workflow Input Data Type field, then click + Create New Type.

    Create New Durable Workflow form with Name set to orderWorkflow and Create New Type highlighted

  6. The Create New Type dialog opens with the correct defaults: the Create from scratch tab and Kind set to Record.

  7. Change Name from MyType to OrderInfo.

  8. Add each field with the + next to Fields, then set its name and type:

    FieldType
    idstring
    customerIdstring
    customerEmailstring
    totalint
  9. Click Save. The record is added to your project and appears under Types in the sidebar.

    Create New Type dialog with the OrderInfo record and its id, customerId, customerEmail, and total fields

  10. Click Create. The workflow is generated and its diagram opens with a single Start node, ready for the first step. The workflow receives the order as its input parameter.

    Create New Durable Workflow form with OrderInfo set as the Workflow Input Data Type and Create highlighted

Reuse an existing type

+ Create New Type is only one way to fill Workflow Input Data Type. Pick any type already in the project straight from the list, or click Open Type Browser to search the wider set. Either way the result is an ordinary record you can edit later from Types in the sidebar. See Types.

Step 3: Reserve the inventory​

Anything that touches the outside world belongs in an activity rather than in the workflow body. The runtime records each activity result, so a completed activity is never executed twice on replay.

The first step of the order process reserves stock. You create the activity and the call that uses it in one pass, straight from the workflow diagram.

  1. On the workflow diagram, click +.

    Workflow diagram with the + button below the Start node highlighted

  2. In the node panel, under Workflow > Steps, click Call Activity. The Activities panel opens, listing everything this workflow can call.

    Node panel with Call Activity highlighted under Workflow Steps

  3. Under Current Integration, click + Create Activity.

    Activities panel with Create Activity highlighted under Current Integration

  4. In the Workflow Activity form, set Activity Name to reserveInventory.

    Workflow Activity form with Activity Name set to reserveInventory and Add Parameter highlighted

  5. Under Parameters, click + Add Parameter, set Type to OrderInfo and Name to orderInfo, then click Add.

    Parameter form with Type set to OrderInfo, Name set to orderInfo, and Add highlighted

  6. Leave Return Type empty. This activity holds stock and returns nothing, so the designer declares it as returns error?. Click Save.

    Workflow Activity form with the orderInfo parameter added and Save highlighted

  7. In the Activities panel, under Current Integration, click reserveInventory to add the activity call to the workflow diagram.

    Activities panel with reserveInventory highlighted under Current Integration

  8. Fill in the call form:

    FieldValue
    Order InfoThe order to reserve. Switch to Expression and set it to the workflow's input parameter.
    Retry PolicyLeave it on No Retry, the default, for now.

    reserveInventory call form with Expression selected and the workflow input highlighted

  9. Click Save. The reserveInventory node appears on the diagram.

    reserveInventory call form with Order Info set to input and Save highlighted

  10. Give the activity something to do. Click the open icon on the node to open its own diagram. To keep it simple, mock the implementation with a log line.

    Workflow diagram with the open icon on the reserveInventory node highlighted

  11. On the activity diagram, click +.

    reserveInventory activity diagram with the + button below the Start node highlighted

  12. In the node panel, under Logging, click Log Info.

    Node panel with Log Info highlighted under Logging

  13. Set Msg to Inventory reserved and click Save.

    log form with Msg set to Inventory reserved and Save highlighted

Where activities come from

+ Create Activity writes a new activity function in your integration. Create Activity from a Connection wraps an action on a connector you already have, and Prebuilt Activities holds the ones that ship with the runtime, for REST calls, SOAP calls, and email. See Activities.

Step 4: Wait for the payment confirmation​

Payment is confirmed by something outside the workflow, such as a payment gateway callback or an operator action. Model that as a data event: a named slot the workflow waits on, and that anyone holding the workflow ID can fill.

  1. Go back to orderWorkflow under Workflows in the sidebar, then click the + below the reserveInventory step.

    orderWorkflow diagram with the + button below the reserveInventory step highlighted

  2. In the node panel, under Workflow > Steps, click Await Data. The Await Data form opens.

    Node panel with Await Data highlighted under Workflow Steps

  3. Under Data Waits, fill in the entry:

    FieldValueDescription
    Data Receive Variable NamepaymentThe variable that receives the value once it arrives.
    Data TypebooleanThe type of the value the workflow expects. To keep this guide simple, use boolean. If the payment is received, the value is true.
    Data NamepaymentThe name used when sending the data into this workflow.

    Await Data form with Data Receive Variable Name set to payment, Data Type set to boolean, Data Name set to payment, and Add highlighted

  4. Click Add then click Save.

    Await Data form with the boolean payment data wait added and Save highlighted

The diagram gains a Wait for payment node, drawn with an incoming arrow from outside the flow, because that is where the value comes from. The workflow now suspends at this line, and only at this line. It holds no thread and no connection while it waits, and it survives a restart of the runtime.

Data event or human task?

Use a data event when a system or a person submits content the workflow processes, as here. Use a human task when a person makes a decision that the cloud-managed control plane should render as a form in their inbox.

Step 5: Branch on the payment result​

The value that arrived decides what happens next, so split the flow in two.

  1. Click + below the wait.

    orderWorkflow diagram with the + button below the Wait for payment node highlighted

  2. In the node panel, under Control, click If.

    Node panel with If highlighted under Control

  3. Condition is prefilled with true. Replace it with the value the wait produced: click the field and pick payment under Variables in the value helper.

  4. Click Add Else Block.

  5. Click Save.

    If form with the else block added and Save highlighted

The diagram splits into a payment path and an Else path, each with its own +.

More than two paths

+ Add Else If Block adds another condition to the same node, and Remove Else Block drops the else path when a branch is all you need.

Step 6: Send the confirmation email​

The payment path tells the customer the order is confirmed. Create that activity and call it in one pass, the same way as reserveInventory.

  1. Click + on the payment path, then under Workflow > Steps, click Call Activity.

    orderWorkflow diagram with the + button on the payment path highlighted

    Node panel with Call Activity highlighted under Workflow Steps

  2. The Activities panel already lists reserveInventory, so click the + on the Current Integration header to add another activity.

    Activities panel with the + button on the Current Integration header highlighted

  3. Set Activity Name to sendEmail. Click + Add Parameter, set Type to OrderInfo and Name to orderInfo, click Add, then click Save.

    Workflow Activity form with Activity Name set to sendEmail, an OrderInfo parameter named orderInfo, and Add highlighted

    Workflow Activity form with the orderInfo parameter added and Save highlighted

  4. Click sendEmail in the Activities panel under Current Integration.

    Activities panel with sendEmail highlighted under Current Integration

  5. In the Order Info field, switch from Record to Expression, then select the workflow's input, and click Save.

    sendEmail call form with Order Info set to the workflow input as an Expression and Save highlighted

  6. Click the open icon on the sendEmail node to open its diagram. To keep it simple, mock the implementation with a log line.

  7. Click +, then click Log Info under Logging.

    sendEmail activity diagram with the + button below Start highlighted

    Node panel with Log Info highlighted under Logging

  8. Leave Msg on Text and type Email sent to . Click on the text box to open the field's value helper, then click Inputs > orderInfo > customerEmail. It lands in the text as an expression.

    Msg value helper showing Inputs > orderInfo with customerEmail listed

  9. Click Save.

    log form with Msg set to Email sent to orderInfo.customerEmail and Save highlighted

Text or Expression?

Keep Msg on Text whenever the message is words with values dropped into it. Text takes what you type as the message and turns each inserted value into an interpolation, which is what produces the string template above. Expression treats the whole field as a single Ballerina expression, so bare words like Email sent to are a syntax error there. The same toggle appears on any field that accepts either, such as Order Info on a call.

Step 7: Cancel the order​

The Else path releases the hold instead.

  1. Go back to orderWorkflow under Workflows in the sidebar. Click + on the Else path, then under Workflow > Steps, click Call Activity.

    orderWorkflow diagram with the + button on the Else path highlighted

    Node panel with Call Activity highlighted under Workflow Steps

  2. Click the + on the Current Integration header.

    Activities panel with the + button on the Current Integration header highlighted

  3. Set Activity Name to cancelOrder. Click + Add Parameter, set Type to OrderInfo and Name to orderInfo, click Add, then click Save.

    Workflow Activity form with Activity Name set to cancelOrder, an OrderInfo parameter named orderInfo, and Add highlighted

    Workflow Activity form with the orderInfo parameter added and Save highlighted

  4. Click cancelOrder in the Activities panel under Current Integration.

    Activities panel with cancelOrder highlighted under Current Integration

  5. In the Order Info field, switch from Record to Expression, then select the workflow's input, and click Save.

    cancelOrder call form with Order Info set to the workflow input as an Expression and Save highlighted

Both branches now end in an activity, and the workflow is complete.

Step 8: Start the workflow from a service​

A workflow does not start itself. It is launched from an entry point such as a service or an automation, so give the order process an HTTP resource that starts a run for each order that arrives.

  1. In the sidebar, click the overview icon next to the integration name to return to the design view.

    Sidebar with the overview icon next to the integration name highlighted, and the integration design view open

  2. Click + Add Artifact, then under Integration as API, click HTTP Service.

    Artifacts page with HTTP Service highlighted under Integration as API

  3. On the Create HTTP Service form, keep Service Contract on Design From Scratch, set Service Base Path to /orderProcess, and click Create.

    Create HTTP Service form with Service Base Path set to /orderProcess and Create highlighted

  4. The service opens with no resources. Click + Add Resource, then click POST in the Select HTTP Method to Add list.

    HTTP Service with Add Resource highlighted and POST highlighted in the Select HTTP Method to Add list

  5. In New Resource Configuration, set Resource Path to ..

    New Resource Configuration with Resource Path set to . and Define Payload highlighted

  6. Click + Define Payload, open the Browse Existing Types tab, click OrderInfo under the current integration, and click Save.

    Define Payload dialog on the Browse Existing Types tab with OrderInfo selected and Save highlighted

  7. Click Save to create the resource. Its own diagram opens.

    New Resource Configuration with the OrderInfo payload added and Save highlighted

  8. Click +, then under Workflow, click Run Workflow.

    Node panel with Run Workflow highlighted under Workflow

  9. Select the orderWorkflow under Current Integration.

    Durable Workflows panel with orderWorkflow highlighted under Current Integration

  10. Under Input, switch from Record to Expression and set Input to the request payload. Leave Workflow ID Variable Name as workflowId, then click Save.

    Run Workflow form with Input set to payload as an Expression and Save highlighted

  11. Click + below the Run Workflow node, then click Return under Control. In the Expression field, select Variables, then select workflowId, and click Save.

    Resource diagram with the + button below the Run Workflow node highlighted

    Node panel with Return highlighted under Control

    Return form with Expression set to workflowId and Save highlighted

The resource now starts a run for every order it receives and answers with that run's workflow ID.

Hold on to the workflow ID

Run Workflow starts an instance and returns immediately with its ID. It does not wait for the order to finish, which is the point: the run may sit on the payment event for days. Return the ID to the caller, because it is what ties a later payment confirmation to this instance.

Step 9: Deliver the payment confirmation​

The run is now waiting on the payment data event, and it will wait forever until something fills it. Add a second resource that does.

  1. Return to the service: click HTTP Service - /orderProcess under Entry Points in the sidebar.

    Sidebar with HTTP Service - /orderProcess highlighted under Entry Points, and + Resource highlighted on the service

  2. Click + Resource, then click POST.

    Select HTTP Method to Add list with POST highlighted

  3. The path needs a segment that carries the workflow ID, so click + Path Param and fill in the Path Parameter form:

    New Resource Configuration with + Path Param highlighted

    FieldValueDescription
    NameorderIdThe variable the segment binds to, and the name you reference it by inside the resource.
    TypestringUnder Advanced Configurations. Defaults to string, which is what a workflow ID is.
  4. Click Save. The segment lands in Resource Path as [string orderId]. Complete the path so it reads [string orderId]/payment.

    Path Parameter form with Name set to orderId, Type string, and Save highlighted

  5. Click Save to create the resource. Its diagram opens.

    New Resource Configuration with Resource Path set to [string orderId]/payment and Save highlighted

  6. Click +, then under Workflow, click Send Data Event.

    Node panel with Send Data Event highlighted under Workflow

  7. Fill in the Send Data form:

    FieldValueDescription
    Workflow NameorderWorkflowThe workflow to send the data to. The dropdown lists all the available workflows.
    Target Workflow IdorderIdThe instance to resume, taken from the request path.
    Data NamepaymentThe event to fill. The dropdown lists the events the chosen workflow declares.
    DatatrueThe value to deliver.

    Send Data form with Workflow Name orderWorkflow, Target Workflow Id orderId, Data Name payment, Data true, and Save highlighted

  8. Click Save.

The node reads Send to payment and is drawn with a dashed arrow across to orderWorkflow, because it hands a value to a run rather than calling something.

Take the value from the request

Anyone holding the workflow ID can deliver the value, so in a real integration this resource is what the payment gateway's callback hits. This walkthrough leaves it unprotected to keep the steps short. A real callback needs authentication and authorization on this resource, because the workflow ID on its own is not an authorization check. See Await data events.

Step 10: Deploy to WSO2 Cloud​

The cloud editor runs in WSO2 Cloud and cannot connect to a Temporal server on your computer, so you run the workflow by deploying it. A deployed workflow connects to the Temporal server set in its environment's Temporal credential.

  1. Add a Temporal credential for your Temporal server, and assign it to the Development environment. See Temporal credentials.

  2. In the cloud editor, open the integration overview and click Save and Deploy in the Deploy to WSO2 Cloud panel. Follow the steps in Save and deploy. WSO2 Cloud builds the integration and deploys it to the Development environment.

  3. In the WSO2 Cloud console, open the integration. Wait until the Development environment shows Active and the Workflow Definitions panel lists orderWorkflow.

    Development environment with the Active status and orderWorkflow under Workflow Definitions highlighted

Step 11: Test the workflow​

  1. In the Development environment, click Test.

    Development environment with Test highlighted

  2. Expand POST /, click Try it out, and replace the request body with the following:

    {
    "customerEmail": "[email protected]",
    "customerId": "CUS-9",
    "id": "ORD-1",
    "total": 4500
    }

    POST / resource expanded in the Test console with Try it out highlighted

  3. Click Execute.

    POST / request body set to the order details, with Execute highlighted

  4. Confirm that the response code is 201, and copy the workflow ID from the response body. The workflow reserves the inventory and waits for the payment event.

    Server response with the 201 code and the workflow ID in the response body highlighted

  5. Expand POST /{orderId}/payment, click Try it out, and set orderId to the workflow ID.

  6. Click Execute.

    POST /{orderId}/payment request with orderId set to the workflow ID, and orderId and Execute highlighted

  7. Confirm that the response code is 202. The workflow resumes and sends the confirmation email.

    Server response for the payment request with the 202 code highlighted

  8. Click Back to Overview. In the Development environment, confirm that COMPLETED (24H) shows 1.

    Development environment with COMPLETED (24H) showing 1 highlighted

  9. Click View Workflows and confirm that the run shows Completed.

    Workflow runs list with the completed orderWorkflow run highlighted

  10. In the Development environment, click View Logs and confirm that the logs show Inventory reserved and Email sent to [email protected].

    Runtime logs with the Inventory reserved and Email sent to ann@example.com lines highlighted

To test the cancellation path, change the payment resource's Data value to false, deploy the integration again, and start a new workflow.

Source code​

View the generated Ballerina code

The steps above generate the following complete, runnable Ballerina program: the types, the workflow and its activities, and the HTTP service that starts and resumes it.

Types (types.bal)

type OrderInfo record {|
string id;
string customerId;
string customerEmail;
int total;
|};

# Data record for workflow function
type OrderWorkflowData record {|
future<boolean> payment;
|};

Workflow and activities

import ballerina/log;
import ballerina/workflow;

@workflow:Workflow
function orderWorkflow(workflow:Context ctx, OrderInfo input, OrderWorkflowData data) returns json|error {
() _ = check ctx->callActivity(reserveInventory, {orderInfo: input});
boolean payment = check wait data.payment;
if payment {
() _ = check ctx->callActivity(sendEmail, {orderInfo: input});
} else {
() _ = check ctx->callActivity(cancelOrder, {orderInfo: input});
}
}

@workflow:Activity
function reserveInventory(OrderInfo orderInfo) returns error? {
log:printInfo("Inventory reserved");
}

@workflow:Activity
function sendEmail(OrderInfo orderInfo) returns error? {
log:printInfo(string `Email sent to ${orderInfo.customerEmail}`);
}

@workflow:Activity
function cancelOrder(OrderInfo orderInfo) returns error? {
}

HTTP service

import ballerina/http;
import ballerina/workflow;

listener http:Listener httpDefaultListener = http:getDefaultListener();

service /orderProcess on httpDefaultListener {

resource function post .(OrderInfo payload) returns json|error {
string workflowId = check workflow:run(orderWorkflow, payload);
return workflowId;
}

resource function post [string orderId]/payment() returns json|error {
check workflow:sendData(orderWorkflow, orderId, "payment", true);
}
}

Watch it run​

Once the integration is connected to the cloud-managed control plane, every instance is visible there, running or completed. The execution graph shows the reservation as a completed activity and the pending payment as a DATA node with status WAITING, so anyone can see exactly what an order is blocked on instead of guessing that it is stuck.

Next steps​

  • Activities — retry policies, activity inputs, and how results are recorded.
  • Await data events — several events, timeouts, and delivering data from other systems.
  • Await human task — pause the order for a person's decision instead of a system's data.
  • Durable timers — add a payment deadline that survives restarts.

Was this page helpful?