Retry Failed Requests in C# Without Retrying Every Error
A useful retry loop is selective.
It repeats only failures that may clear on their own, stops as soon as a request succeeds, and gives up after a clear limit instead of looping indefinitely.
Retry only failures that may be temporary
Most requests succeed on the first try. When one does not, the first decision is classification, not repetition. Codes 400, 401 and 403 usually point to a malformed request, an authentication problem or an access restriction. Sending the identical request again will not repair those causes, so the program should report the status and stop. A 500 response is different: it can reflect a temporary server-side problem, making a later attempt worthwhile. That distinction keeps retries from masking configuration errors.
How the five-attempt loop behaves
The worked example makes five attempts in total, not five retries after an initial call. A successful response ends the loop immediately and its body is written to an HTML file. A non-500 status ends the loop with a message that the error is not retryable. Only a 500, a timeout or a network exception continues to the next attempt. If every attempt fails, the program prints a final message naming the attempt limit.
Set the three environment variables before running this modern .NET console example. It preserves the documented GET /api/v1/ request, Bearer header, five attempts, 30-second timeout and delays of 2, 4, 8 and 16 seconds. Only HTTP 500, timeouts and transport errors enter the retry path; other unsuccessful statuses stop immediately.
using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
string apiOrigin = Environment.GetEnvironmentVariable("API_BASE_URL")
?? throw new InvalidOperationException("Set API_BASE_URL");
string token = Environment.GetEnvironmentVariable("API_KEY")
?? throw new InvalidOperationException("Set API_KEY");
string siteOrigin = Environment.GetEnvironmentVariable("SITE_BASE_URL")
?? throw new InvalidOperationException("Set SITE_BASE_URL");
string endpoint = apiOrigin.TrimEnd('/') + "/api/v1/?url="
+ Uri.EscapeDataString(siteOrigin.TrimEnd('/') + "/blog/");
using var transport = new HttpClient { Timeout = TimeSpan.FromSeconds(30) };
transport.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", token);
for (int attempt = 1; attempt <= 5; attempt++)
{
try
{
using var result = await transport.GetAsync(endpoint);
if (result.IsSuccessStatusCode)
{
await File.WriteAllTextAsync("page.html", await result.Content.ReadAsStringAsync());
return;
}
if ((int)result.StatusCode != 500)
{
Console.Error.WriteLine("Non-retryable HTTP status: " + (int)result.StatusCode);
return;
}
}
catch (TaskCanceledException) { Console.Error.WriteLine("Request timed out"); }
catch (HttpRequestException error) { Console.Error.WriteLine(error.Message); }
if (attempt < 5)
await Task.Delay(TimeSpan.FromSeconds(1 << attempt));
}
Console.Error.WriteLine("All five attempts failed");Why the delay grows between attempts
Waiting a fixed short interval after every failure can hammer a struggling service. Exponential backoff spreads the attempts out instead: the example waits 2 seconds, then 4, 8 and 16 seconds. Each pause is calculated from the attempt number, so the spacing grows automatically as failures continue. Use the same idea whenever you add retries, but tune the starting delay and attempt cap to the service you are calling.
Timeouts and network errors
Two exception types cover the non-HTTP failures. TaskCanceledException handles a request that times out, and HttpRequestException covers network-related problems. Both are logged and then treated as a failed attempt, so the backoff and retry logic still apply. Before running the example, replace the configuration tokens with your own base addresses and supply a valid API key; the client sends that key as a Bearer token and allows 30 seconds per request.
Decision checklist
Use this checklist before adding retry logic to any C# client: confirm which status codes are genuinely temporary; stop immediately on success; set a maximum number of total attempts; increase the delay after each failure; handle timeouts separately from HTTP responses; and print a clear final message when the limit is exhausted. If a failure is caused by the request itself, fix the request rather than repeating it.
Frequently asked questions
Which status codes are worth retrying?
A 500 response is treated as potentially temporary, so the loop can try again after a pause. A 400, 401 or 403 points to a problem with the request or account, so repeating the same request is unlikely to change the outcome.
How long does the code wait between attempts?
The pause doubles after each unsuccessful attempt. In the worked example the waits are 2, 4, 8 and 16 seconds before the final attempt.
What happens on a timeout or network error?
Timeouts are caught through TaskCanceledException, while network-related failures are caught through HttpRequestException. Both fall through to the next attempt unless the attempt limit has been reached.