Retries with jitter in C#, without a library
One of our services calls an upstream API that fails in bursts. We retried with a fixed one-second delay, which meant every worker retried at the same moment and knocked the API over again.
The standard answer is exponential backoff with jitter. This is all it takes:
static async Task<T> RetryAsync<T>(
Func<Task<T>> action, int attempts = 5)
{
for (var i = 0; ; i++)
{
try { return await action(); }
catch (HttpRequestException) when (i < attempts - 1)
{
var cap = TimeSpan.FromSeconds(Math.Pow(2, i));
var delay = Random.Shared.NextDouble() * cap;
await Task.Delay(delay);
}
}
}
The bug in my first version
I caught Exception instead of HttpRequestException, so a cancelled request was retried five times before the caller noticed. Catch only what you know is transient, and let cancellation pass through.