1
When building microservices or communicating with external APIs, transient network faults can cause temporary request failures. Implementing a retry strategy with exponential backoff helps mitigate these issues without overwhelming the downstream service.
Using Polly v8 Resilience Pipeline
With Polly v8 and Microsoft.Extensions.Resilience, you can construct a resilient pipeline using the ResiliencePipelineBuilder class.
Code Example
var pipeline = new ResiliencePipelineBuilder()
.AddRetry(new RetryStrategyOptions
{
ShouldHandle = new PredicateBuilder().Handle<HttpRequestException>(),
MaxRetryAttempts = 3,
Delay = TimeSpan.FromSeconds(2),
BackoffType = DelayBackoffType.Exponential,
UseJitter = true
})
.Build();
await pipeline.ExecuteAsync(async cancellationToken =>
{
// Perform HTTP operation here
await MakeNetworkRequestAsync(cancellationToken);
});Key Considerations
- Jitter: Adding randomness prevents the thundering herd problem.
- Transient Errors: Only retry operations that are transient (e.g., HTTP 503 or network socket timeouts).