Skip to content

Checkpoint: Retry with Backoff

The Course
•
40 min study

Networks and services fail briefly all the time. Retrying is the standard answer, and doing it badly makes outages worse: retrying instantly and forever piles load on a struggling service. This checkpoint builds the retry core that the Day 7 job runner is based on. (The runner changes one rule, treating a timeout as final; its brief explains why.)

Exponential backoff

Each retry waits longer: 10 ms, then 20, then 40. A real system also adds jitter, a little randomness, so that many clients don't all retry at the same instant. Predict the delays, and notice the difference between retrying and giving up.

Doubling delays C#
TimeSpan baseDelay = TimeSpan.FromMilliseconds(10);

for (int attempt = 1; attempt <= 4; attempt++)
{
    TimeSpan delay = baseDelay * Math.Pow(2, attempt - 1);
    Console.WriteLine(delay.TotalMilliseconds);
}
Check your prediction
Text
10
20
40
80

Which failures are worth retrying?

A timeout or a busy server might work next time. A bad password won't. Retrying a permanent failure just wastes time. A distinct exception type makes that choice clear, and any other exception type passes straight out.

Only some failures retry C#
foreach (Exception failure in new Exception[] { new TransientException(), new ArgumentException("bad") })
{
    int calls = 0;
    try
    {
        await RetryAsync(() =>
        {
            calls++;
            throw failure;
        }, 3);
    }
    catch (Exception e)
    {
        Console.WriteLine($"{e.GetType().Name} after {calls}");
    }
}

static async Task RetryAsync(Action action, int attempts)
{
    for (int attempt = 1; ; attempt++)
    {
        try
        {
            action();
            return;
        }
        catch (TransientException) when (attempt < attempts)
        {
            await Task.Yield();
        }
    }
}

class TransientException : Exception;
Check your prediction
Text
TransientException after 3
ArgumentException after 1

Don't wait in tests

A test that really waits for backoff is slow, and it can't check timing precisely. As with the clock on the Intermediate course's Day 6, you make the wait a dependency. A fake IDelayer returns at once and records what it was asked for. Tests then run instantly and can check the exact delays.

Build it yourself

Exercise

A retry helper

Write Retrier, which receives an IDelayer, a maxAttempts and a baseDelay. Its method is:

Task<RetryResult<T>> RunAsync<T>(Func<CancellationToken, Task<T>> action, TimeSpan timeout, CancellationToken token)

  • Each attempt gets its own timeout, through a linked token.
  • TransientException is retried after a delay that doubles each time, up to maxAttempts.
  • An attempt that times out counts as a transient failure.
  • Caller cancellation stops at once, during an attempt or during a delay.
  • Any other exception ends the run.

RetryResult<T> is a closed hierarchy with Success(T Value, int Attempts), GaveUp(string Reason, int Attempts) and Cancelled(int Attempts).

Test with a FakeDelayer: two failures then success (printing the result and delays), always failing, a permanent failure, a timeout (using RealDelayer, or a fake action waiting on its token), and cancelling during the delay.

Build it one rule at a time, adding the matching test each time, in the order the rules are listed. The success path, transient retries and the delays are the core. If you run out of time, stop there and add the timeout and cancellation rules in a later session.

When it works, it prints the lines below. Each Name { … } line is a record's built-in ToString, so print the record itself rather than formatting it:

Text
Success { Value = done, Attempts = 3 }
10,20
GaveUp { Reason = busy, Attempts = 3 }
GaveUp { Reason = bad input, Attempts = 1 }
GaveUp { Reason = timed out, Attempts = 3 }
Cancelled { Attempts = 1 }
Your workspace C#
var delays = new FakeDelayer();
await delays.DelayAsync(TimeSpan.FromMilliseconds(10), CancellationToken.None);
Console.WriteLine(delays.Requested.Count);

interface IDelayer
{
    Task DelayAsync(TimeSpan duration, CancellationToken token);
}

class FakeDelayer : IDelayer
{
    public List<TimeSpan> Requested { get; } = new();

    public Task DelayAsync(TimeSpan duration, CancellationToken token)
    {
        Requested.Add(duration);
        return Task.CompletedTask;
    }
}
Hint 1: the idea

The order of the catch clauses is the design: first caller cancellation, then this attempt's timeout, then transient, then everything else. The first three use the patterns from the last lesson.

Hint 2: a first step

Write the loop with a Success path and TransientException, and check the recorded delays. Add the timeout next, and finally the cancellation paths, with a test for each.

Show one solution
C#
var delays = new FakeDelayer();
var retrier = new Retrier(delays, 3, TimeSpan.FromMilliseconds(10));

int calls = 0;
Console.WriteLine(await retrier.RunAsync(async token =>
{
    await Task.Yield();
    calls++;
    return calls < 3 ? throw new TransientException("busy") : "done";
}, TimeSpan.FromSeconds(5), CancellationToken.None));
Console.WriteLine(string.Join(",", delays.Requested.Select(delay => delay.TotalMilliseconds)));

Console.WriteLine(await retrier.RunAsync<string>(token => throw new TransientException("busy"), TimeSpan.FromSeconds(5), CancellationToken.None));
Console.WriteLine(await retrier.RunAsync<string>(token => throw new ArgumentException("bad input"), TimeSpan.FromSeconds(5), CancellationToken.None));

Console.WriteLine(await retrier.RunAsync(async token =>
{
    await Task.Delay(5000, token);
    return "late";
}, TimeSpan.FromMilliseconds(5), CancellationToken.None));

using var caller = new CancellationTokenSource(20);
var real = new Retrier(new RealDelayer(), 3, TimeSpan.FromSeconds(30));
Console.WriteLine(await real.RunAsync<string>(token => throw new TransientException("busy"), TimeSpan.FromSeconds(5), caller.Token));

class TransientException(string message) : Exception(message);

abstract record RetryResult<T>
{
    private RetryResult()
    {
    }

    public sealed record Success(T Value, int Attempts) : RetryResult<T>;

    public sealed record GaveUp(string Reason, int Attempts) : RetryResult<T>;

    public sealed record Cancelled(int Attempts) : RetryResult<T>;
}

class Retrier(IDelayer delayer, int maxAttempts, TimeSpan baseDelay)
{
    public async Task<RetryResult<T>> RunAsync<T>(Func<CancellationToken, Task<T>> action, TimeSpan timeout, CancellationToken token)
    {
        for (int attempt = 1; ; attempt++)
        {
            string reason;
            using var linked = CancellationTokenSource.CreateLinkedTokenSource(token);
            linked.CancelAfter(timeout);
            try
            {
                return new RetryResult<T>.Success(await action(linked.Token), attempt);
            }
            catch (OperationCanceledException) when (token.IsCancellationRequested)
            {
                return new RetryResult<T>.Cancelled(attempt);
            }
            catch (OperationCanceledException)
            {
                reason = "timed out";
            }
            catch (TransientException e)
            {
                reason = e.Message;
            }
            catch (Exception e)
            {
                return new RetryResult<T>.GaveUp(e.Message, attempt);
            }

            if (attempt >= maxAttempts)
            {
                return new RetryResult<T>.GaveUp(reason, attempt);
            }
            try
            {
                await delayer.DelayAsync(baseDelay * Math.Pow(2, attempt - 1), token);
            }
            catch (OperationCanceledException)
            {
                return new RetryResult<T>.Cancelled(attempt);
            }
        }
    }
}

interface IDelayer
{
    Task DelayAsync(TimeSpan duration, CancellationToken token);
}

class RealDelayer : IDelayer
{
    public Task DelayAsync(TimeSpan duration, CancellationToken token) => Task.Delay(duration, token);
}

class FakeDelayer : IDelayer
{
    public List<TimeSpan> Requested { get; } = new();

    public Task DelayAsync(TimeSpan duration, CancellationToken token)
    {
        Requested.Add(duration);
        return Task.CompletedTask;
    }
}
Text
Success { Value = done, Attempts = 3 }
10,20
GaveUp { Reason = busy, Attempts = 3 }
GaveUp { Reason = bad input, Attempts = 1 }
GaveUp { Reason = timed out, Attempts = 3 }
Cancelled { Attempts = 1 }

The timed-out run really did spend three 5 ms attempts, with fake delays between them. Tomorrow you'll add many of these at once, with limited capacity.

Was this article helpful?

Your response is saved on this device.