Enhance Resilience in .NET Applications with Polly
Amit Halder - AzureCloud
Technical Lead | Microsoft and Cloud Technologies | Ex - TCS | 2X- Azure Certification | Az-204| Azure Integration Azure Paas services | Terraform
Enhance Resilience in .NET Applications with Polly
Building resilient .NET applications is critical in the face of transient faults, network latencies, and unexpected failures. Polly, the robust .NET library for implementing resilience patterns, offers tools like Retry Policies, Circuit Breakers, and Timeouts for managing fault scenarios effectively. Here's how you can integrate Polly into your workflow:
Key Features and Code Examples:
1. Retry Policies: Handling transient faults with jittered backoff
Ensure smooth retry operations with transient error handling and jittered backoff to prevent server overload.
// Method no 1 : retry with in general case in TransientHttpError with DecorrelatedJitterBackoff
services.AddHttpClient<IService, ServiceImplemet>((services, httpClient) =>
{
httpClient.BaseAddress = new Uri("https://localhost:5000");
httpClient.DefaultRequestHeaders.Add("svc-version", "3.0");
httpClient.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "Value");
httpClient.DefaultRequestHeaders.Add("id", "value");
})
.AddPolicyHandler((services, req) =>
HttpPolicyExtensions
.HandleTransientHttpError()
.OrResult(msg => !msg.IsSuccessStatusCode)
.WaitAndRetryAsync(
Backoff.DecorrelatedJitterBackoffV2(
medianFirstRetryDelay: TimeSpan.FromSeconds(5),
retryCount: 4),
(outcome, timespan, retryAttempt, context) =>
{
var logs = services.GetService<ILogger<IService>>();
if (outcome?.Result?.StatusCode != null)
{
logs.LogWarning($"Retrying due to {outcome.Result.StatusCode}. Delaying for {timespan.TotalMilliseconds}ms, retry #{retryAttempt}.");
}
else
{
logs.LogWarning($"Retrying due to {outcome.Exception?.Message}. Delaying for {timespan.TotalMilliseconds}ms, retry #{retryAttempt}.");
}
}));
2. Timeouts: Controlling execution duration for responsiveness
Prevent service calls from hanging indefinitely using timeout policies.
领英推荐
// Method no 2 Timeouts - Controlling Execution Duration
services.AddHttpClient<IService, ServiceImplemet>((services, httpClient) =>
{
httpClient.BaseAddress = new Uri("https://localhost:5000");
})
.AddPolicyHandler((services, req) =>
Policy.TimeoutAsync<HttpResponseMessage>(TimeSpan.FromSeconds(1)));
3. Circuit Breakers: Preventing cascading failures
A circuit breaker in Polly is designed to stop the application from repeatedly invoking a failing operation, which could otherwise worsen the situation. When the failure threshold is reached, the circuit “opens,” temporarily blocking calls until a reset period elapses.
// Method no 3 Circuit Breakers - Preventing Cascading Failures
services.AddHttpClient<IService, ServiceImplemet>((services, httpClient) =>
{
httpClient.BaseAddress = new Uri("https://localhost:5000");
})
.AddTransientHttpErrorPolicy(services => services.CircuitBreakerAsync(3, TimeSpan.FromSeconds(15),
onBreak: (outcome, timespan) =>
{
Console.WriteLine($"Circuit broken! Pausing for {timespan.TotalSeconds} seconds.");
},
onReset: () =>
{
Console.WriteLine("Circuit reset! Resuming normal operations.");
}));
Why Use Polly?
Polly empowers developers to build robust, resilient applications capable of handling fault scenarios gracefully. Share your thoughts and experiences below! ?? #DotNet #ResiliencePatterns #PollyFramework #Coding