Configure retry policy

Sometimes, communication between services can get interrupted or requests might fail for various reasons. It is a common practice to configure so called retry policies. This sample shows how to configure some retry policies when using the DHI.Platform.SDK. Typically, you should configure retry policies at a point where you add platform clients into the dependency injection container (so, usually in Program.cs or Startup.cs files).

The most common policies for handling errors such as failing communication between services are Retry, Fallback, CircuitBreaker, and combinations of these approaches.

By default, the DHI.Platform.SDK is configured with a retry policy so that requests failed due to network failures, errors 5XXn and error 408 should re-send up to 3 times. You don't need to do anything to apply this policy:

HttpPolicyExtensions.HandleTransientHttpError().RetryAsync(3);

That is a good starting point, but you may need an entirely different policy to be applied in your application, like handling a very special exception by calling your fallback service method:

var fallback = Policy.Handle<MySpecialException>()
    .FallbackAsync(async (context, cancellationToken) => await _myFallbackService.HandleFallback() );

builder.Services.AddPlatformClients(o =>
{
    o.ConfigureRetryPolicy(fallback);
    o.ConfigureAccessToken();
});

Or even combining the concept of a retry with a fallback under certain conditions:

var myRetry = HttpPolicyExtensions.HandleTransientHttpError().RetryAsync(3, async (result, retryIndex, pollyContext) =>
{
    var isSpecificEndpoint = result.Result.RequestMessage?.RequestUri?.AbsolutePath.ToLower().Contains("/flaky-endpoint/") ?? false;
    var isTimeout = result.Result.StatusCode == System.Net.HttpStatusCode.RequestTimeout;
    if (isSpecificEndpoint && isTimeout && retryIndex == 3)
    {
        await _myFallbackService.HandleFallback();
    }
});

builder.Services.AddPlatformClients(o =>
{
    o.ConfigureRetryPolicy(myRetry);
    o.ConfigureAccessToken();
});