As I mentioned before, Polly is a .NET resilience and transient-fault-handling library that allows developers to express policies such as Retry, Circuit Breaker, Timeout, Bulkhead Isolation, and Fallback in a fluent and thread-safe manner.
To use Polly in your application, you will need to install the Polly NuGet package.
Retry Policy
The Retry policy allows you to retry an operation after a specific number of failures or after a specific duration.
Policy.Handle<Exception>()
.WaitAndRetry(3, retryAttempt => TimeSpan.FromSeconds(1))
.Execute(() => {
// Your operation here
});
In the example above, we are handling any exception and retrying the operation 3 times with a delay of 1 second between each retry.
Circuit Breaker Policy
The Circuit Breaker policy allows you to automatically open and close a circuit breaker when certain conditions are met. When the circuit breaker is open, it prevents the operation from being executed and instead returns a failure immediately.
var policy = Policy.Handle<Exception>().CircuitBreaker(2, TimeSpan.FromMinutes(1));
In the example above, we are handling any exception and opening the circuit breaker after 2 failures within 1 minute.
Timeout Policy
The Timeout policy allows you to specify a maximum duration for an operation to complete before timing out.
var policy = Policy.Timeout(TimeSpan.FromSeconds(5));
In the example above, we are specifying a timeout of 5 seconds for the operation. If the operation takes longer than 5 seconds to complete, the policy will throw a TimeoutRejectedException.
Fallback Policy
The Fallback policy allows you to specify an alternate action to be executed when the main operation fails.
var fallback = Policy<string>.Handle<Exception>().Fallback("Hello from fallback!");
In the example above, if the main operation throws an exception, the fallback action specified in the policy will be executed and return "Hello from fallback!"
Combining Policies
Polly also allows you to combine multiple policies together to create more complex fault-handling logic. For example, you can combine a Retry policy with a Circuit Breaker policy to retry an operation a certain number of times before opening the circuit breaker.
var policy = Policy.Handle<Exception>().WaitAndRetry(3, retryAttempt => TimeSpan.FromSeconds(1))
.Wrap(Policy.Handle<Exception>().CircuitBreaker(2, TimeSpan.FromMinutes(1)));
In the example above, we are first retrying the operation 3 times with a delay of 1 second between each retry. If the operation still fails after the retries, the circuit breaker will open after 2 failures within 1 minute.
Conclusion
Polly is a powerful and flexible library that allows developers to easily implement resilience and transient fault-handling in .NET Core applications. The library provides a variety of policies for handling different types of failures and allows developers to create complex fault-handling logic by combining multiple policies.