Skip to content

Instantly share code, notes, and snippets.

@reisenberger
Last active September 25, 2019 20:15
Show Gist options
  • Save reisenberger/a8d5806a95523f936d56a6d1dedc70a1 to your computer and use it in GitHub Desktop.
Save reisenberger/a8d5806a95523f936d56a6d1dedc70a1 to your computer and use it in GitHub Desktop.
Demonstrates decorrelated jitter with Polly (issue 245)
using System;
using System.Collections.Generic;
using Polly;
namespace DecorrelatedJitter
{
class Program
{
static void Main(string[] args)
{
TimeSpan maxDelay = TimeSpan.FromSeconds(2);
TimeSpan seedDelay = TimeSpan.FromMilliseconds(100);
int maxRetries = 20;
Policy retryWithDecorrelatedJitter = Policy
.Handle<DivideByZeroException>()
.WaitAndRetry(DecorrelatedJitter(maxRetries, seedDelay, maxDelay), onRetry: (e, t) => Console.WriteLine($"Retry delay: {t.TotalMilliseconds} ms."));
try
{
retryWithDecorrelatedJitter.Execute(() => { throw new DivideByZeroException(); });
}
catch
{
// intentionally empty to swallow final exception. This is only a console app to display retry delays generated by a jitter strategy with Polly.
}
Console.WriteLine("Done");
Console.ReadKey();
}
public static IEnumerable<TimeSpan> DecorrelatedJitter(int maxRetries, TimeSpan seedDelay, TimeSpan maxDelay)
{
Random jitterer = new Random();
int retries = 0;
double seed = seedDelay.TotalMilliseconds;
double max = maxDelay.TotalMilliseconds;
double current = seed;
while (++retries <= maxRetries)
{
current = Math.Min(max, Math.Max(seed, current * 3 * jitterer.NextDouble())); // adopting the 'Decorrelated Jitter' formula from https://www.awsarchitectureblog.com/2015/03/backoff.html. Can be between seedMs and previousMs * 3. Mustn't exceed maxDelay.
yield return TimeSpan.FromMilliseconds(current);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment