.NET Core Polly (How it Works for Developers)

Polly is a .NET resilience strategies and transient fault handling library, allowing developers to express resilience policies such as Retry policy, Circuit Breakers, Timeout, Bulkhead Isolation policy, and Fallback. Polly targets ASP.NET Core, making it a vital tool for .NET Core resilience. Polly has a thread safe manner and supports handling multiple concurrent requests with successful response.

This tutorial will provide more detail about transient fault handling .NET library, Polly and how to use it with IronPDF in an ASP.NET Core application. We'll take a deep dive into each aspect of Polly, explain the mechanics of the circuit breaker pattern, discuss bulkhead isolation and timeouts, and show how to handle specific exceptions or failing service with failure response in a controlled thread safe manner.

Polly Policies

Transient faults often occur when your application tries to connect with a web service through HTTP request, database, or other external resources. These faults, like network failures, temporary connectivity issues, or timeouts, are brief and typically correct themselves after a short time.

Polly manages these transient faults by applying different strategies and express policies like Retry Policy, advanced Circuit Breaker Policy, Timeout Policy, Fallback Policy, and Bulkhead Isolation Policy.

Retry Policy

Retry Policy automatically retries failed concurrent requests using retry logic. It can be configured to retry forever or do automatic retries for a certain number of times, and it can wait a set time interval between retries or use an exponential back-off.

Circuit Breaker

The Circuit Breaker policy lets your system support cancellation token for trying a particular service after a pre-configured threshold of failed requests. The Circuit Breaker strategy is analogous to chaos engineering or a ship closing watertight doors to localize damage: one fault won't sink the whole ship.

Timeout Policy

Timeout policy enforces a maximum time that a particular piece of .NET resilience code can execute. It comes in two flavors: optimistic timeout and pessimistic timeout.

Fallback Policy

Fallback policy is used to provide a substitute value or behavior in the event of a failure. This policy can be useful when a failing service should not halt the entire process.

Bulkhead Isolation

Bulkhead isolation is used to limit how many concurrent requests can be made to a specific operation, thereby limiting the potential for socket exhaustion and maintaining a controlled number of execution slot.

Cache Policy

Cache policy caches the successful response of an execution so that if the same execution is invoked again, Polly can return the distributed cache value.

Policy Wrap

Allows us to wrap multiple policies together, so they can work as a single unit.

Create and Configure Policies

Retry Policy

A retry policy is simple: when a specific exception or a fault occurs, Polly will try to execute the underlying delegate again. You can define how many times to retry, the time interval between retries, or use an exponential back-off strategy else it will retry forever. Here's an example:

//extension method
var retryPolicy = Policy
    .Handle<HttpRequestException>()
    .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), 
    (exception, timeSpan, retryCount, context) =>
    {
        // This is the OnRetry delegate, where you can log or monitor failed requests
    });
//extension method
var retryPolicy = Policy
    .Handle<HttpRequestException>()
    .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), 
    (exception, timeSpan, retryCount, context) =>
    {
        // This is the OnRetry delegate, where you can log or monitor failed requests
    });
'extension method
Dim retryPolicy = Policy.Handle(Of HttpRequestException)().WaitAndRetryAsync(3, Function(retryAttempt) TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), Sub(exception, timeSpan, retryCount, context)
End Sub)
VB   C#

Circuit Breaker Policy

The Circuit Breaker policy lets Polly library monitor for faults, and if the number of faults exceeds a configured threshold within a specified period, the circuit is "broken," and further requests are blocked for a specified time. This is called the 'open' state. After this time, the circuit enters a 'half-open' state, where it allows some traffic to check the health of the particular service. If these requests are successful and no faults occur, the circuit closes, otherwise, it opens again.

var circuitBreakerPolicy = Policy
    .Handle<HttpRequestException>()
    .CircuitBreakerAsync(5, TimeSpan.FromMinutes(1));
var circuitBreakerPolicy = Policy
    .Handle<HttpRequestException>()
    .CircuitBreakerAsync(5, TimeSpan.FromMinutes(1));
Dim circuitBreakerPolicy = Policy.Handle(Of HttpRequestException)().CircuitBreakerAsync(5, TimeSpan.FromMinutes(1))
VB   C#

Timeout Policy

Timeout policies handle scenarios where a service isn't responding within a reasonable timeframe. Polly offers two types of timeouts: Optimistic and Pessimistic. An optimistic timeout works on a separate thread and cancels the underlying operation via a CancellationToken. A pessimistic timeout blocks the parent thread until the operation completes or the timeout period elapses.

var timeoutPolicy = Policy.TimeoutAsync(30); // Optimistic timeout of 30 seconds
var timeoutPolicy = Policy.TimeoutAsync(30); // Optimistic timeout of 30 seconds
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

Bulkhead Isolation

Bulkhead Isolation is used to limit the number of concurrent actions against a particular service. It provides a way to isolate faults and prevent them from cascading. It also limits the load we place on our dependencies.

var bulkheadIsolationPolicy = Policy.BulkheadAsync(10, 20); // 10 concurrent actions, queue 20 additional actions
var bulkheadIsolationPolicy = Policy.BulkheadAsync(10, 20); // 10 concurrent actions, queue 20 additional actions
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

Fallback Policy

Fallback policies are useful when you need to provide a default behavior or substitute value when all else fails.

var fallbackPolicy = Policy
    .Handle<Exception>()
    .FallbackAsync<FallbackResult>(FallbackResult.SomethingWentWrong);
var fallbackPolicy = Policy
    .Handle<Exception>()
    .FallbackAsync<FallbackResult>(FallbackResult.SomethingWentWrong);
Dim fallbackPolicy = Policy.Handle(Of Exception)().FallbackAsync(Of FallbackResult)(FallbackResult.SomethingWentWrong)
VB   C#

Wrapping the Policies

Multiple policies can be combined flexibly using a PolicyWrap:

var policyWrap = Policy.WrapAsync(fallbackPolicy, retryPolicy, circuitBreakerPolicy, timeoutPolicy, bulkheadIsolationPolicy);
var policyWrap = Policy.WrapAsync(fallbackPolicy, retryPolicy, circuitBreakerPolicy, timeoutPolicy, bulkheadIsolationPolicy);
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

Getting Started

To begin using Polly with IronPDF, make sure you have Visual Studio installed and create a new Console Application project in .NET Core. Open the NuGet Package Manager Console in Visual Studio and install the Polly and IronPdf packages:

Install-Package Polly
Install-Package IronPdf

Using Polly with IronPDF Converting a URL to PDF

Let's walk through an example of using Polly with IronPDF to convert a URL to PDF. Assume we have a web service that occasionally fails due to transient faults, and we want to handle those failures gracefully using Polly.

First, let's import the necessary namespaces in our Program.cs file:

using System;
using System.Threading.Tasks;
using Polly;
using Polly.Wrap;
using IronPdf;
using System;
using System.Threading.Tasks;
using Polly;
using Polly.Wrap;
using IronPdf;
Imports System
Imports System.Threading.Tasks
Imports Polly
Imports Polly.Wrap
Imports IronPdf
VB   C#

Next, we'll define our policies. In this example, we'll use a combination of retry and circuit breaker policies to handle failures:

var retryPolicy = Policy
    .Handle<Exception>()
    .WaitAndRetryAsync(3, i => TimeSpan.FromSeconds(2 * i));

var circuitBreakerPolicy = Policy
    .Handle<Exception>()
    .CircuitBreakerAsync(2, TimeSpan.FromSeconds(30));
var retryPolicy = Policy
    .Handle<Exception>()
    .WaitAndRetryAsync(3, i => TimeSpan.FromSeconds(2 * i));

var circuitBreakerPolicy = Policy
    .Handle<Exception>()
    .CircuitBreakerAsync(2, TimeSpan.FromSeconds(30));
Dim retryPolicy = Policy.Handle(Of Exception)().WaitAndRetryAsync(3, Function(i) TimeSpan.FromSeconds(2 * i))

Dim circuitBreakerPolicy = Policy.Handle(Of Exception)().CircuitBreakerAsync(2, TimeSpan.FromSeconds(30))
VB   C#

The retryPolicy will retry the failed request up to three times with an exponential backoff strategy, waiting 2 seconds, 4 seconds, and 8 seconds between retries. The circuitBreakerPolicy will open the circuit if two consecutive failures occur within a 30-second time interval.

Now, let's define our IronPDF code to convert a URL to a PDF:

var htmlToPdf = new ChromePdfRenderer();
var pdfBytes = await retryPolicy
    .WrapAsync(circuitBreakerPolicy)
    .ExecuteAsync(() =>
    {
        Console.WriteLine("Attempting to convert URL to PDF...");
// var result
        var result = htmlToPdf.RenderUrlAsPdfAsync("https://example.com");
        Console.WriteLine("Conversion successful!");
        return result;
    });

pdfBytes.SaveAs("output.pdf");
var htmlToPdf = new ChromePdfRenderer();
var pdfBytes = await retryPolicy
    .WrapAsync(circuitBreakerPolicy)
    .ExecuteAsync(() =>
    {
        Console.WriteLine("Attempting to convert URL to PDF...");
// var result
        var result = htmlToPdf.RenderUrlAsPdfAsync("https://example.com");
        Console.WriteLine("Conversion successful!");
        return result;
    });

pdfBytes.SaveAs("output.pdf");
Dim htmlToPdf = New ChromePdfRenderer()
Dim pdfBytes = Await retryPolicy.WrapAsync(circuitBreakerPolicy).ExecuteAsync(Function()
		Console.WriteLine("Attempting to convert URL to PDF...")
' var result
		Dim result = htmlToPdf.RenderUrlAsPdfAsync("https://example.com")
		Console.WriteLine("Conversion successful!")
		Return result
End Function)

pdfBytes.SaveAs("output.pdf")
VB   C#

In the above example code, we wrap our retryPolicy and circuitBreakerPolicy using the WrapAsync method. This allows us to apply multiple policies to new requests sequentially. The ExecuteAsync method executes the provided delegate, which in this above code is the RenderUrlAsPdfAsync method from IronPDF.

By applying Polly policies, we ensure that our code is resilient to transient faults. If a request fails, Polly will automatically retry it according to the retry policy. If the number of consecutive failures crosses the pre-configured threshold, the circuit breaker policy will open the circuit, preventing further requests for a specified duration.

Test Cases for Polly Policies

To test the effectiveness of our Polly policies, let's simulate some failed requests. Modify the URL to a non-existent endpoint and add a few test cases:

var testUrls = new[]
{
                "https://ironpdf.com",
                "https://notexistingdomain.com/",
                "http://httpbin.org/delay/120"
};

foreach (var url in testUrls)
{
    try
    {
        var pdfBytes = await retryPolicy
            .WrapAsync(circuitBreakerPolicy)
            .ExecuteAsync(() => htmlToPdf.RenderUrlAsPdfAsync(url));

        pdfBytes.SaveAs($"{Guid.NewGuid()}.pdf");
        Console.WriteLine($"Successfully converted {url} to PDF.");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Failed to convert {url} to PDF: {ex.Message}");
    }
}
var testUrls = new[]
{
                "https://ironpdf.com",
                "https://notexistingdomain.com/",
                "http://httpbin.org/delay/120"
};

foreach (var url in testUrls)
{
    try
    {
        var pdfBytes = await retryPolicy
            .WrapAsync(circuitBreakerPolicy)
            .ExecuteAsync(() => htmlToPdf.RenderUrlAsPdfAsync(url));

        pdfBytes.SaveAs($"{Guid.NewGuid()}.pdf");
        Console.WriteLine($"Successfully converted {url} to PDF.");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Failed to convert {url} to PDF: {ex.Message}");
    }
}
Dim testUrls = { "https://ironpdf.com", "https://notexistingdomain.com/", "http://httpbin.org/delay/120" }

For Each url In testUrls
	Try
		Dim pdfBytes = Await retryPolicy.WrapAsync(circuitBreakerPolicy).ExecuteAsync(Function() htmlToPdf.RenderUrlAsPdfAsync(url))

		pdfBytes.SaveAs($"{Guid.NewGuid()}.pdf")
		Console.WriteLine($"Successfully converted {url} to PDF.")
	Catch ex As Exception
		Console.WriteLine($"Failed to convert {url} to PDF: {ex.Message}")
	End Try
Next url
VB   C#

In the above code, we iterate over a set of test URLs and attempt to convert each of them to PDF. If a request fails, the exception will be caught and an appropriate message will be displayed in the console.

.NET Core Polly (How It Works For Developers): Figure 1 - URL to PDF Output

Conclusion

Polly is a powerful and flexible library for implementing resilience and transient fault handling in .NET Core applications. By combining policies like retry and circuit breaker, developers can build robust and fault-tolerant systems that gracefully handle failures.

In this tutorial, we explored how to use Polly with IronPDF to convert a URL to PDF. We learned how to define and apply Polly policies, including retry and circuit breaker. We also tested our policies with different URLs. We can also do it for converting HTML to PDF.

IronPDF offers a free trial, and licenses start from $749, allowing you to leverage its capabilities in your projects.