Test in production without watermarks.
Works wherever you need it to.
Get 30 days of fully functional product.
Have it up and running in minutes.
Full access to our support engineering team during your product trial
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 is thread-safe and supports handling multiple concurrent requests with successful responses.
This tutorial will provide more details about the 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 services with failure responses in a controlled, thread-safe manner.
Transient faults often occur when your application tries to connect with a web service through an 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 expressing policies like Retry Policy, advanced Circuit Breaker Policy, Timeout Policy, Fallback Policy, and Bulkhead Isolation 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.
The Circuit Breaker policy lets your system support a 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 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 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 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 slots.
The 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.
Allows us to wrap multiple policies together, so they can work as a single unit.
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:
// Retry policy for handling HttpRequestException with exponential back-off
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
Console.WriteLine($"Retry {retryCount} after {timeSpan}. Exception: {exception.Message}");
});
// Retry policy for handling HttpRequestException with exponential back-off
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
Console.WriteLine($"Retry {retryCount} after {timeSpan}. Exception: {exception.Message}");
});
The Circuit Breaker policy lets the 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.
// Circuit breaker policy to handle failing requests with open and half-open states
var circuitBreakerPolicy = Policy
.Handle<HttpRequestException>()
.CircuitBreakerAsync(5, TimeSpan.FromMinutes(1));
// Circuit breaker policy to handle failing requests with open and half-open states
var circuitBreakerPolicy = Policy
.Handle<HttpRequestException>()
.CircuitBreakerAsync(5, TimeSpan.FromMinutes(1));
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.
// Timeout policy with a 30-second optimistic timeout
var timeoutPolicy = Policy.TimeoutAsync(30); // 30 seconds
// Timeout policy with a 30-second optimistic timeout
var timeoutPolicy = Policy.TimeoutAsync(30); // 30 seconds
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.
// Bulkhead isolation policy to limit concurrency and queue length
var bulkheadIsolationPolicy = Policy.BulkheadAsync(10, 20); // 10 concurrent actions, 20 queue slots
// Bulkhead isolation policy to limit concurrency and queue length
var bulkheadIsolationPolicy = Policy.BulkheadAsync(10, 20); // 10 concurrent actions, 20 queue slots
Fallback policies are useful when you need to provide a default behavior or substitute value when all else fails.
// Fallback policy to provide a default result on failure
var fallbackPolicy = Policy
.Handle<Exception>()
.FallbackAsync<FallbackResult>(
FallbackResult.SomethingWentWrong,
(exception, context) =>
{
Console.WriteLine($"Fallback triggered due to: {exception.Message}");
return Task.CompletedTask;
});
// Fallback policy to provide a default result on failure
var fallbackPolicy = Policy
.Handle<Exception>()
.FallbackAsync<FallbackResult>(
FallbackResult.SomethingWentWrong,
(exception, context) =>
{
Console.WriteLine($"Fallback triggered due to: {exception.Message}");
return Task.CompletedTask;
});
Multiple policies can be combined flexibly using a PolicyWrap
:
// Combining multiple policies using PolicyWrap
var policyWrap = Policy.WrapAsync(fallbackPolicy, retryPolicy, circuitBreakerPolicy, timeoutPolicy, bulkheadIsolationPolicy);
// Combining multiple policies using PolicyWrap
var policyWrap = Policy.WrapAsync(fallbackPolicy, retryPolicy, circuitBreakerPolicy, timeoutPolicy, bulkheadIsolationPolicy);
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
A prominent feature of IronPDF is its HTML to PDF capability, ensuring layouts and styles are intact. This function turns web content into PDFs, which is perfect for reports, invoices, and documentation. It supports converting HTML files, URLs, and HTML strings to PDFs.
using IronPdf;
class Program
{
static void Main(string[] args)
{
var renderer = new ChromePdfRenderer();
// 1. Convert HTML String to PDF
var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");
// 2. Convert HTML File to PDF
var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");
// 3. Convert URL to PDF
var url = "http://ironpdf.com"; // Specify the URL
var pdfFromUrl = renderer.RenderUrlAsPdf(url);
pdfFromUrl.SaveAs("URLToPDF.pdf");
}
}
using IronPdf;
class Program
{
static void Main(string[] args)
{
var renderer = new ChromePdfRenderer();
// 1. Convert HTML String to PDF
var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");
// 2. Convert HTML File to PDF
var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");
// 3. Convert URL to PDF
var url = "http://ironpdf.com"; // Specify the URL
var pdfFromUrl = renderer.RenderUrlAsPdf(url);
pdfFromUrl.SaveAs("URLToPDF.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;
Next, we'll define our policies. In this example, we'll use a combination of retry and circuit breaker policies to handle failures:
// Retry policy with exponential backoff
var retryPolicy = Policy
.Handle<Exception>()
.WaitAndRetryAsync(3, i => TimeSpan.FromSeconds(2 * i));
// Circuit breaker policy to block requests after consecutive failures
var circuitBreakerPolicy = Policy
.Handle<Exception>()
.CircuitBreakerAsync(2, TimeSpan.FromSeconds(30));
// Retry policy with exponential backoff
var retryPolicy = Policy
.Handle<Exception>()
.WaitAndRetryAsync(3, i => TimeSpan.FromSeconds(2 * i));
// Circuit breaker policy to block requests after consecutive failures
var circuitBreakerPolicy = Policy
.Handle<Exception>()
.CircuitBreakerAsync(2, TimeSpan.FromSeconds(30));
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(async () =>
{
Console.WriteLine("Attempting to convert URL to PDF...");
var result = await 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(async () =>
{
Console.WriteLine("Attempting to convert URL to PDF...");
var result = await htmlToPdf.RenderUrlAsPdfAsync("https://example.com");
Console.WriteLine("Conversion successful!");
return result;
});
pdfBytes.SaveAs("output.pdf");
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 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.
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}");
}
}
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.
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 at competitive pricing, allowing you to leverage its capabilities in your projects.
Polly is a .NET library that provides resilience strategies and transient fault handling capabilities. It allows developers to implement policies such as Retry, Circuit Breakers, Timeout, Bulkhead Isolation, and Fallback to manage transient faults in ASP.NET Core applications.
Polly enhances .NET Core resilience by providing thread-safe mechanisms to handle multiple concurrent requests successfully. It targets ASP.NET Core specifically, making it an essential tool for managing transient faults and ensuring application stability.
A Retry Policy in Polly automatically retries failed requests using configurable retry logic. Developers can set the number of retries, the time interval between retries, or use an exponential back-off strategy to manage transient faults effectively.
The Circuit Breaker Policy in Polly monitors for faults and opens the circuit (blocking requests) if failures exceed a certain threshold within a specified period. This prevents further requests until the circuit resets, allowing for recovery and preventing cascading failures.
Bulkhead Isolation in Polly limits the number of concurrent requests to a service, preventing socket exhaustion and maintaining controlled execution slots. This isolation helps contain failures and manage system resources effectively.
Yes, Polly allows for combining multiple policies using a Policy Wrap. This feature lets different resilience strategies work together as a single unit, enabling more robust and flexible fault handling.
A Fallback Policy in Polly provides a substitute value or behavior in case of a failure. This ensures that a failing service does not halt the entire process, allowing for graceful degradation of functionality.
Polly can be integrated with IronPDF to manage transient faults when converting web content to PDF. By defining and applying Polly policies like retry and circuit breaker, developers can ensure stable PDF generation despite occasional service disruptions.
Using Polly with IronPDF ensures that URL to PDF conversion processes are resilient to transient faults. By applying retry and circuit breaker policies, developers can handle failures gracefully and maintain service reliability.
A Timeout Policy in Polly enforces a maximum execution time for a piece of .NET resilience code. It offers both optimistic and pessimistic timeouts to handle scenarios where services do not respond within a reasonable timeframe.