Enhance Resilience in .NET Applications with Polly

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?

  • Customizable Resilience: Flexible configurations for retries, timeouts, and circuit breakers.
  • Seamless Integration: Works effortlessly with ASP.NET Core via the IHttpClientFactory.
  • Improved Fault Tolerance: Mitigate the impact of transient errors while keeping your services responsive.

Polly empowers developers to build robust, resilient applications capable of handling fault scenarios gracefully. Share your thoughts and experiences below! ?? #DotNet #ResiliencePatterns #PollyFramework #Coding




要查看或添加评论,请登录

Amit Halder - AzureCloud的更多文章

  • Deploying API Management (APIM) with Terraform

    Deploying API Management (APIM) with Terraform

    In addition to our Logic App, deploying an Azure API Management (APIM) service helps manage APIs securely, monitor…

  • Deploying a Logic App with Terraform

    Deploying a Logic App with Terraform

    Hello there, tech enthusiasts! Today, we'll walk through an exciting demo project that showcases how to deploy an Azure…

社区洞察

其他会员也浏览了