Skip to main content

Adding a Retry Policy

Let’s go ahead and add a retry policy and timeout to our Workflow code. Remember, your Activity contains code that is prone to failure. By default, Temporal automatically retries failed Activities until it either succeeds or is canceled. You can also override the default retry policies like in the code sample.

With the following configuration, your Activities will retry up to 100 times with an exponential backoff — waiting 2 seconds before the first retry, doubling the delay after each failure up to a 1-minute cap — and each attempt can run for at most 5 seconds.

using Temporalio.Workflows;

[Workflow]
public class ReimbursementWorkflow
{
[WorkflowRun]
public async Task<string> RunAsync(string userId, double amount)
{
var activityOptions = new ActivityOptions
{
StartToCloseTimeout = TimeSpan.FromSeconds(5), // maximum time allowed for a single attempt of an Activity to execute
RetryPolicy = new()
{
InitialInterval = TimeSpan.FromSeconds(2), // duration before the first retry
BackoffCoefficient = 2, // multiplier used for subsequent retries
MaximumInterval = TimeSpan.FromMinutes(1), // maximum duration between retries
MaximumAttempts = 100 // maximum number of retry attempts before giving up
}
};

await Workflow.ExecuteActivityAsync(
(Activities act) => act.withdrawMoney(amount),
activityOptions
);

await Workflow.ExecuteActivityAsync(
(Activities act) => act.depositMoney(amount),
activityOptions
);
return $"reimbursement to {userId} successfully complete";
}
}
5 / 9