import ballerina/io;

public function main() returns error? {
    // Short for retry<DefaultRetryManager>(3)
    // If any of `doStage1` and `doStage2` returns  `error:Retriable`,
    // program will retry execution until execution succeed without an error `error:Retriable`.
    // By default, it will retry 3 times with `DefaultRetryManager`.
    retry transaction {
        check doStage1();
        check doStage2();
        check commit;
    }
}

function doStage1() returns error? {
    io:println("Stage1 completed");
}

function doStage2() returns error? {
    // Returns `error:Retriable` error for retrying.
    // To support custom errors, a custom implementation of `RetryManager` is required.
    return error 'error:Retriable("Stage2 failed");
}

Retry Transaction Statement

Transactional errors are often transient: retrying will fix them. This works by creating a RetryManager object r, before executing the transaction. If the block fails with error e, it calls r.shouldRetry(e). If that returns true, then it executes the block again. retry has an optional type parameter giving class of RetryManager to create, and optional arguments to new DefaultRetryManager tries n times. retry can be used without transaction.

import ballerina/io;
public function main() returns error? {
    retry transaction {
        check doStage1();
        check doStage2();
        check commit;
    }
}

Short for retry(3) If any of doStage1 and doStage2 returns error:Retriable, program will retry execution until execution succeed without an error error:Retriable. By default, it will retry 3 times with DefaultRetryManager.

function doStage1() returns error? {
    io:println("Stage1 completed");
}
function doStage2() returns error? {
    return error 'error:Retriable("Stage2 failed");
}

Returns error:Retriable error for retrying. To support custom errors, a custom implementation of RetryManager is required.

bal run retry_transaction_statement.bal
Stage1 completed
Stage1 completed
Stage1 completed
Stage1 completed
error: Stage2 failed {}