Applications need to communicate with many other services and components to function properly. During this communication, temporary faults may arise due to some of the services or components being unable to respond on time. These faults can come in the form of timeouts, overloaded resources, networking hiccups, and so on. Retry and circuit-breaker patterns are […]
CodeGuru content and product recommendations are
editorially independent. We may make money when you click on links
to our partners.
Learn More
Applications need to communicate with many other services and components to function properly. During this communication, temporary faults may arise due to some of the services or components being unable to respond on time. These faults can come in the form of timeouts, overloaded resources, networking hiccups, and so on. Retry and circuit-breaker patterns are useful for solving these temporary faults. In fact, these are the most common approaches when coding for resiliency.
In this article, developers will create a simple example to demonstrate how to use Polly to implement both retry and circuit-breaker policies.
What is Retry in .NET?
Retry in .NET terms basically means “if something goes wrong, try repeating the same operation again for a certain number of times before giving up.” One example of this might be your service calling a third-party API, failing, and then retrying again until a connection is made or until 10 attempts have been made.
Advertisement
What is a Circuit-breaker Pattern in .NET?
A circuit-breaker pattern in .NET programming basically says “if something goes wrong, hit the panic button that prevents any further attempts to repeat the operation.” An example of a circuit-breaker pattern might be an overloaded database that you want your program to quit querying if an overload is detected or occurs.
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 so forth. It is a mature library that is almost synonymous with app resiliency.
How to Implement Polly
Implementing a retry pattern with an HTTP(s) request with .NET is very easy; all developers need to do is write an extension method named AddPolicyHandler in order to add the retry policy for the HttpClient. Refer to the following code snippet to see how this is achieved. Note that the GetRetryPolicy method will be invoked during network failures or if HTTP errors are triggered.
The .NET code below demonstrates how to push the message in a message queue:
Route("api/[controller]")]
[ApiController]
publicclassValuesController : ControllerBase
{
[HttpGet]
public ActionResult<IEnumerable> Get()
{
var message = Encoding.UTF8.GetBytes("My retry pattern");
var retry = Policy
.Handle()
.WaitAndRetry(2, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)));
try
{
retry.Execute(() =>
{
Console.WriteLine($"begin at {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}.");
var factory = new ConnectionFactory
{
HostName = "localhost",
UserName = "Test",
Password = "Tes"
};
var connection = factory.CreateConnection();
var model = connection.CreateModel();
model.ExchangeDeclare("retrypattern", ExchangeType.Topic, true, false, null);
model.BasicPublish("retrypattern", "retrypattern.#", false, null, message);
});
}
catch
{
Console.WriteLine("exception here.");
}
returnnewstring[] { "TestValue1", "TestValue2" };
}
}
Advertisement
Conclusion to Implementing Circuit-breaker with Polly and .NET
In this article, we have introduced Polly circuit breaker policies and showed how to use them with a .NET application that uses the HttpClientFactory pattern to create instances of HttpClient. Be sure to check back often for more .NET programming tutorials and developer articles.
CodeGuru covers topics related to Microsoft-related software development, mobile development, database management, and web application programming. In addition to tutorials and how-tos that teach programmers how to code in Microsoft-related languages and frameworks like C# and .Net, we also publish articles on software development tools, the latest in developer news, and advice for project managers. Cloud services such as Microsoft Azure and database options including SQL Server and MSSQL are also frequently covered.
Advertiser Disclosure: Some of the products that appear on
this site are from companies from which TechnologyAdvice
receives compensation. This compensation may impact how and
where products appear on this site including, for example,
the order in which they appear. TechnologyAdvice does not
include all companies or all types of products available in
the marketplace.