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.
import io.temporal.activity.ActivityOptions;
import io.temporal.common.RetryOptions;
import io.temporal.workflow.Workflow;
import java.time.Duration;
public class ReimbursementWorkflowImpl implements ReimbursementWorkflow {
private final ReimbursementActivities activities = Workflow.newActivityStub(
ReimbursementActivities.class,
ActivityOptions.newBuilder()
.setStartToCloseTimeout(Duration.ofSeconds(5)) // maximum time allowed for a single attempt of an Activity to execute
.setRetryOptions(RetryOptions.newBuilder()
.setInitialInterval(Duration.ofSeconds(2)) //duration before the first retry
.setBackoffCoefficient(2.0) //multiplier used for subsequent retries
.setMaximumInterval(Duration.ofMinutes(1)) //maximum duration between retries
.setMaximumAttempts(100) //maximum number of retry attempts before giving up
.build())
.build()
);
@Override
public String processReimbursement(String userId, double amount) {
activities.withdrawMoney(amount);
activities.depositMoney(amount);
return "Reimbursement of $" + amount + " for user " + userId + " processed successfully";
}
}