DEV Community

Albert Bennett
Albert Bennett

Posted on

How to add a retry policy to a Timer Function

If you liked what you read feel free to connect with me on linkedin or follow me on dev.to :)

Hi and welcome to my blog post.
It's a quick one today. I'm going to show you how to add a retry policy on a timer function. I had seen an article shared on Microsoft's twitter account a short while ago and wanted to share some of the info. It seems like a really cool feature and, one that I am excited about. Having worked with function apps on an off for the past 5 years or so. Also I'll link their article on it below.

What is a retry policy
A retry policy is an action that retries a request a number of times until either the maximum number of retries has occurred or the endpoint returns a successful response.
It is mostly used to handle transient errors in an application. Things such as drops in connections, minor unexpected errors that kind of thing.

Implementation
This retry policy isn't available on all kinds of Azure functions. For the example today, I'll be showing it on a timer function but. To my knowledge this binding only works for Timer, Event Hubs functions but, there are other ways of adding a retry policy to an Azure function.
For timer functions adding a retry policy is very straight forward. Simply add the following 'FixedDelayRetry' binding to your function app:

        [FunctionName("Function1")]
        [FixedDelayRetry(5, "00:00:10")]
        public void Run([TimerTrigger("0 */5 * * * *")]TimerInfo myTimer, ILogger log)
        {
            log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");

            int i = Random.Shared.Next(4);

            if (i < 4)
            {
                log.LogError($"Thrown an error because number generated was < 4: {i}");
                throw new FunctionException("Not working :(");
            }
        }
Enter fullscreen mode Exit fullscreen mode

I've added extra logic to the function simply to test out the retry policy.
Important things to note is that in the binding you need to specify the number of retries that you want to be attempted and also the time delay between them. For this example I have set it to retry a maximum of 5 times with a 10 second delay between each attempt.
timer trigger retrying
It's also worth noting that this feature is only available on version 3 function apps and above.

As promised here is the original article:
https://docs.microsoft.com/en-us/azure/azure-functions/functions-bindings-error-pages?tabs=fixed-delay%2Cin-process&pivots=programming-language-csharp

Or if you want to find out more about the retry pattern:
https://docs.microsoft.com/en-us/azure/architecture/patterns/retry

Thanks for reading and I hope to see you guys next time.

Top comments (0)