ASP.NET Core Interview Question #169

How should retry logic be designed for background work?

Logging, Error Handling & Background Services Mid-Level Intermediate

Quick Interview Answer

Retries should be used only for failures that are plausibly transient, such as a temporary network or service outage. Permanent validation errors, authentication failures, or invalid business data should not be retried indefinitely.

Detailed Explanation

Retries should be used only for failures that are plausibly transient, such as a temporary network or service outage. Permanent validation errors, authentication failures, or invalid business data should not be retried indefinitely.

A retry strategy should usually include a limited attempt count, delay or exponential backoff, cancellation support, and logging. Jitter can help prevent many instances from retrying at exactly the same time.

Operations that can be retried should be designed to tolerate repeated execution where possible, especially when the failure occurred after an external side effect may already have succeeded.

Code Example

for (var attempt = 1; attempt <= 3; attempt++)
{
    try
    {
        await SendAsync(cancellationToken);
        break;
    }
    catch (HttpRequestException) when (attempt < 3)
    {
        await Task.Delay(
            TimeSpan.FromSeconds(attempt * 2),
            cancellationToken);
    }
}