concept Polly in category .net

appears as: Polly
Microservices in .NET Core: with examples in Nancy

This is an excerpt from Manning's book Microservices in .NET Core: with examples in Nancy.

  • Polly is a library that makes it easy to implement one of the more common policies for handling remote-call failures. Out of the box, Polly has support for various retry and circuit breaker policies. I’ll discuss circuit breakers in chapter 6.
  • The result of these simple rules is a state machine that stops making HTTP requests when they’re likely to fail anyway. Later in this chapter, I’ll show you how to use Polly to create circuit breakers around HTTP requests.

    6.3.2. Implementing a circuit breaker with Polly

    Now you’ll add a circuit breaker to the API Gateway microservice’s queries to the Loyalty Program microservice. This time, you’ll use Polly’s built-in support for circuit breaker policies.

    Example 6.3. Polly circuit breaker policy

    Even though the circuit breaker pattern may seem more complicated than retrying, Polly makes it just as easy to set up a circuit breaker policy as a retry policy. Using a policy is the same no matter what the policy is, so wrapping queries to the Loyalty Program microservice in the circuit breaker policy is just like the code for wrapping register-user commands in the retry policy.

    First, you need to add the Polly NuGet package to the API Gateway microservice. The code that sends the commands to the Loyalty Program microservice is in LoyaltyProgramClient. You use Polly to set up a retry policy that uses an exponential backoff. Polly splits the setup of a policy from the execution of the policy: that is, Polly allows you to set up different policies—a retry policy, for instance—and then later execute a piece of code under the policy. In the case of a retry strategy, that means retrying the piece of code if it fails. The retry policy for the register-user command is set up as shown next.