Quantcast
Channel: Active questions tagged retry-logic - Stack Overflow
Viewing all articles
Browse latest Browse all 950

How can I queue HttpClient requests until a Polly retry policy is successful?

$
0
0

I'm using polly to refresh an authorisation token if a http request returns a 401 error. My full solution is based off: Refresh Token using Polly with Named Client, but the relevant parts are:

Retry policy:

static IAsyncPolicy<HttpResponseMessage> GetAuthRefreshPolicy(IServiceProvider serviceProvider){        return Policy<HttpResponseMessage>            .HandleResult(response => response.StatusCode == HttpStatusCode.Unauthorized)            .RetryAsync(async (handler, retry) => await serviceProvider.GetRequiredService<IAuthorisationService>().RefreshTokenAsync());}

AuthorisationService:

public class AuthorisationService : IAuthorisationService{    public String? AuthToken { get; private set; }    private readonly IAuthenticationClient _AuthenticationClient;    private readonly AuthOptions _AuthOptions;    public AuthorisationService(IAuthenticationClient authenticationClient, IOptions<AuthOptions> options)    {        _AuthenticationClient = authenticationClient;        _AuthOptions = options.Value;    }    public async Task RefreshTokenAsync()    {        this.AuthToken = await _AuthenticationClient.LoginAsync(_AuthOptions.User, _AuthOptions.Password);    }}

This works fine in most circumstances. The problem I am having is that if the auth token is currently invalid and multiple requests are made at the same time, because they are executed asynchronously they will all be called with the invalid token, fail and trigger the polly retry policy resulting in multiple unnecessary token refresh requests.

Is there a way to set polly up so that if a request fails with a 401, all subsequent requests will wait until the token has been successfully refreshed? Or to queue up retry attempts and skip requesting a new token if it's already been refreshed?

I have tried looking into polly features like bulkhead circuit breakers, but can't work out if these are right for this use case or if there's a simpler way to lock the token refreshing.


Viewing all articles
Browse latest Browse all 950

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>