typestar

Retry policies in C#

Transient failure, meet declarative persistence.

using Polly;
using Polly.Retry;

var pipeline = new ResiliencePipelineBuilder()
    .AddRetry(new RetryStrategyOptions
    {
        MaxRetryAttempts = 3,
        Delay = TimeSpan.FromMilliseconds(50),
        BackoffType = DelayBackoffType.Exponential,
    })
    .Build();

var attempts = 0;
pipeline.Execute(() =>
{
    attempts++;
    if (attempts < 3) throw new TimeoutException("flaky");
});
Console.WriteLine($"succeeded on attempt {attempts}");

How it works

  1. A ResiliencePipeline is built once and reused.
  2. MaxRetryAttempts, Delay and exponential backoff are options.
  3. The flaky callback succeeds on attempt three, inside the budget.

Keywords and builtins used here

The run, in numbers

Lines
19
Characters to type
404
Tokens
84
Three-star pace
85 tpm

At the three-star pace of 85 tokens a minute, this run takes about 59 seconds.

Type this snippet

Step 1 of 2 in Resilience with Polly, step 8 of 16 in The open ecosystem.

← Previous Next →