Ensuring resilient task execution with Polly
Message sending should always be protected with at least exponential retry and the circuit break strategies that we analyzed in the Resilient task execution subsection of Chapter 2, Demystifying Microservices Applications. In this section, we will first describe the Polly library, which became a kind of standard for handling resilient task execution, and then we will apply it to the SendMessage
method of OutputSendingService
.
The Polly library
Resilient communication and, in general, resilient task execution can be implemented easily with the help of a .NET library called Polly, whose project is a member of the .NET Foundation. Polly is available through the Polly
NuGet package.
In Polly, you define policies and then execute tasks in the context of those policies, as follows:
var myPolicy = Policy
.Handle<HttpRequestException>()
.Or<OperationCanceledException>()
.RetryAsync(3);
....
....
await myPolicy...