Having a resilient HTTP client is a huge benefit if your application depends on third-party API calls. This will helps to avoid transient errors. These errors may be temporary and will be solved quickly. Most of the time these errors occurred due to network issues.
The below example demonstrates how to implement a HttpClient with multiple retries using Polly and Flurl.
Polly is a .NET resilience and transient-fault-handling library that allows developers to express policies such as Retry, Circuit Breaker, Timeout, Bulkhead Isolation, Rate-limiting, and Fallback in a fluent and thread-safe manner.
Flurl is a modern, fluent, asynchronous, testable, portable, buzzword-laden URL builder and HTTP client library.
Creating the Retry Policy
This IsWorthRetrying method will check returned HTTP status is worth of retry.
And I used OnRetryAsyncFunc to log the retry information.
Use the Retry Policy
Example usage and results
var result = await apiClient.GetAsync("https://httpstat.us/503").ConfigureAwait(false);
Console.WriteLine($"Hello, World! {result}");