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.

import (
"fmt"
"time"
"go.temporal.io/sdk/temporal"
"go.temporal.io/sdk/workflow"
)

func ReimbursementWorkflow(ctx workflow.Context, userId string, amount float64) (string, error) {
options := workflow.ActivityOptions{
StartToCloseTimeout: time.Second * 5, // maximum time allowed for a single attempt of an Activity to execute
RetryPolicy: &temporal.RetryPolicy{
InitialInterval: time.Second * 2, // duration before the first retry
BackoffCoefficient: 2, // multiplier used for subsequent retries
MaximumInterval: time.Minute, // maximum duration between retries
MaximumAttempts: 100, // maximum number of retry attempts
},
}
ctx = workflow.WithActivityOptions(ctx, options)

var withdrawSuccess bool
err := workflow.ExecuteActivity(ctx, WithdrawMoney, amount).Get(ctx, &withdrawSuccess)

var depositSuccess bool
err = workflow.ExecuteActivity(ctx, DepositMoney, amount).Get(ctx, &depositSuccess)

return fmt.Sprintf("reimbursement to %s successfully complete", userId), nil
}
5 / 9