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.
@workflow.defn
class ReimbursementWorkflow:
@workflow.run
async def run(self, user_id: str, amount: float) -> str:
retry_policy = RetryPolicy(
initial_interval=timedelta(seconds=2), # duration before the first retry
backoff_coefficient=2.0, # multiplier used for subsequent retries
maximum_interval=timedelta(minutes=1), # maximum duration between retries
maximum_attempts=100, # maximum number of retry attempts before giving up
)
await workflow.execute_activity(
withdraw_money,
amount,
start_to_close_timeout=timedelta(seconds=5), # maximum time allowed for a single attempt of an Activity to execute
retry_policy=retry_policy,
)
await workflow.execute_activity(
deposit_money,
amount,
start_to_close_timeout=timedelta(seconds=5),
retry_policy=retry_policy,
)
return f"reimbursement to {user_id} successfully complete"