Ihttpclientfactory and polly in Azure Functions
Following the last article on correct way to use HTTP client in Azure Functions, the next step is to make the http requests made to the remote APIs more resilient. Resiliency can be achieved by having retry logic to retry calls to remote at exponential intervals and using circuit breaker pattern to break the remote connection in case of repeated failures.
There are multiple ways to implement retry and circuit breaker patterns in .net core, but we will use the Polly library for this.
Start by adding the reference to the Microsoft.Extensions.Http.Polly nuget package.
We can then add the retry and circuit breaker policies in the Startup class as shown
The policies can then be added to the http client as shown below
The retry policy will retry the call to the remote API for four times with a exponential sleep duration between the calls and the circuit breaker will break the call to the remote API for two seconds after two attempts
The HttpClient can be created as shown in the image below
This way the calls to the remote APIs can be made more resilient. Polly supports advanced policy configuration which can be found at Polly Wiki.