Advertisement
Advanced ASP.NET Core, Background Tasks & Hosted Services

How would you implement retry logic with exponential backoff for a background service that calls a potentially-flaky external API?

Short answer

Combine a retry policy (hand-rolled, or via a library like Polly) wrapping each unit of work with exponentially increasing delays between attempts, distinguishing between transient failures (worth retrying, like network timeouts) and permanent failures (should be logged and…

Save ASP.NET Core mock interview
Advertisement
AModel answer
Combine a retry policy (hand-rolled, or via a library like Polly) wrapping each unit of work with exponentially increasing delays between attempts, distinguishing between transient failures (worth retrying, like network timeouts) and permanent failures (should be logged and skipped, not retried indefinitely) to avoid an infinite retry loop on genuinely unrecoverable errors.
var retryPolicy = Policy
    .Handle<HttpRequestException>()
    .WaitAndRetryAsync(3, attempt => TimeSpan.FromSeconds(Math.Pow(2, attempt)));

protected override async Task ExecuteAsync(CancellationToken stoppingToken) {
    while (!stoppingToken.IsCancellationRequested) {
        await retryPolicy.ExecuteAsync(() => CallExternalApiAsync());
        await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken);
    }
}
Real-world example
A background service integrating with a flaky third-party payment provider uses Polly's exponential backoff to gracefully absorb transient network issues, only escalating to an alert after three consecutive failed attempts.
Likely follow-ups
  • How do you distinguish transient from permanent failures programmatically?
  • What is a dead-letter mechanism and how does it complement retry logic?
Related topics