One of the easiest cloud design pattern that one can try out is the Retry Pattern. I wanted to show how to use an Retry Pattern using Polly in C# as a example. So what does the Retry Pattern achieves?

Problem Statement – What is the issue the pattern solves?

When building applications you always have some sort of outside/external service including another MicroService that you have to consume or call. Sometimes there could be momentary loss of network connectivity, or a temporary unavailability, or timeouts that occur when that service is busy. You may be calling a database or a restful service that may be busy and fail but if you try back again it will pass. These types of faults are usually self-correcting, and most of the time require some type of delay in calling it again, which will have a success response.

Retry Pattern

  • Enable an application to handle transient failures
  • When the applications tries to connect to a service or network resource
  • By transparently retrying a failed operation
  • Improves the stability of your application
  • Typical Application

    Below is a typical application diagram, where you a service or web app.

    TypicalApplication

    TypicalApplication

    But when the connection to the service fails we usually get an error on our application.

    TypicalApplication-Network-Failure

    Typical-Application-Network-Failure

    When to use Retry Pattern

    • Use retry for only transient failure that is more than likely to resolve themselves quickly
    • Match the retry policies with the application
    • Otherwise use the circuit break pattern

    When not to use Retry Pattern

    • Don’t cause a chain reaction to all components
    • For internal exceptions caused by business logic
    • Log all retry attempts to the service

    Sample Code

    Below is a sample dotnet core Console Application that shows the usage using Polly. The code tries to call https://httpbin.org/status/200,408 with a POST which gives us a status of 200 or 408 randomly. First, lets create our code and add the package Polly into it.

    Without Polly

    We will write a sample application that will call the the web service without polly to get 408 errors.

    I am not using a logger but you should be using a logger when you do retry pattern.

    If you have issues with 7.0 C# change your csproj to include <LangVersion>7.1</LangVersion>

    After couple of runs you will see it response back with 408 RequestTimeout

    Using Polly

    Now we will introduce Polly into our code with an incremental delay of 1 second to 3 seconds and lastly 9 seconds.

    Output

    Below you will see three runs of the application with sample output.

    Summary

    As you can see Retry Pattern is quite useful for transient and self correcting failure, not to mention it is quite simple to implement in C# with the help of Polly. If you are looking for Java solutions you can look at Hysterix or even roll your own.