We are going to design a library for retry policies using the strategy pattern.
The idea is to define an interface (or abstract class) for a retry policy, and then provide different implementations (strategies) for various retry behaviors.
We'll design it in a language-agnostic way and then show how it can be implemented in Java, Kotlin, and C#.
Steps:
- Define the RetryPolicy interface (or abstract class) that declares a method to decide whether to retry and possibly how long to wait.
- The interface might also include context about the current attempt, the exception that caused the failure, etc.
- Implement various strategies:
- Fixed interval: wait a fixed time between retries.
- Exponential backoff: wait exponentially longer between retries.
- Random interval: wait a random time between retries.
- etc.
- We might also want to have a composite policy (e.g., combine conditions) or a policy that can be configured with parameters.
However, note that the strategy pattern is about encapsulating the algorithm (the retry decision) and making it interchangeable.
Let's define a common interface:
In all languages, we'll have:
interface RetryPolicy {
// We need to decide whether to retry and also how long to wait.
// We can return a RetryDecision that contains:
// - shouldRetry: boolean
// - waitDuration: duration (optional, if shouldRetry is true then we wait, else we don't)
// But note: sometimes we might want to retry immediately? So we can return an optional duration.
// Alternatively, we can have two methods:
// boolean shouldRetry(int retryCount, Throwable lastException);
// Duration getWaitDuration(int retryCount, Throwable lastException);
// But then the two methods are coupled. What if shouldRetry returns true but getWaitDuration returns something? They must be consistent.
// Let's design a class RetryDecision that holds:
// boolean retry
// long waitMillis (if retry is true, then wait this long; if false, ignore)
// Then the policy method:
// RetryDecision decide(int retryCount, Throwable lastException);
// However, note that sometimes we don't have an exception (like on the first try we haven't failed yet).
// We can pass null for lastException on the first call? Or we can design differently.
// Alternatively, we can have:
// boolean shouldRetry(RetryContext context);
// Duration getWaitDuration(RetryContext context);
// But again, two methods.
// Another idea: the policy is called after a failure. So we have:
// RetryDecision afterFailure(int retryCount, Throwable cause);
// and maybe also a method for the first try? Actually, we might want to decide whether to even try the first time?
// But typically we try at least once. So we can assume that we are only called after a failure.
// Let's do:
// RetryDecision afterFailure(int retryCount, Throwable cause);
// The retryCount is the number of attempts so far (including the one that just failed). So if we are about to do the first retry, retryCount=1?
// Actually, if we have failed once and are deciding whether to retry, then retryCount=1 (meaning we have failed once and are considering the first retry).
// Alternatively, we can think:
// attempt 1: success or failure?
// if failure, then we are at retryCount=0? and we are going to do retry 1?
// Let's define:
// retryCount: the number of retry attempts that have been made so far.
// So when we are about to make the first retry, we have made 0 retry attempts and had 1 failure.
// But the method is called after the first failure, so retryCount=0.
// However, in many systems, the first call is attempt 1, then if it fails we do retry 1, then retry 2, etc.
// So if we are after the first failure, we are about to do the first retry, so the number of retries so far is 0?
// Or we can say the number of attempts so far (including the initial) is 1, and we are considering the second attempt (first retry).
// Let's clarify:
// Attempt 1: initial call -> if fails, then we call the policy with retryCount=1? meaning we have attempted once and are about to retry (the second attempt).
// Then after the second attempt fails, we call with retryCount=2?
// Actually, in the standard retry pattern, we count the number of attempts (including the initial one). So:
// After the first failure (initial attempt failed), we are at attempt 1, and we are considering the second attempt (first retry).
// Then after the second failure, we are at attempt 2, and we consider the third attempt (second retry).
// But in the policy, we are only concerned with how many retries we have done?
// Let me re-read: the typical retry pattern is:
// for (int i = 0; i < maxRetries; i++) {
// try {
// // do work
// break;
// } catch (Exception e) {
// if (i == maxRetries - 1) throw e;
// // wait
// }
// }
// In this case, after the first failure, i=0 (we have done 0 retries so far, and the initial attempt failed).
// So when we are about to retry for the first time, we have done 0 retries.
// So in the policy, we can be given:
// int retryCount: the number of retry attempts that have been made (so initially 0, then after first retry 1, etc.)
// But note: the initial call is not a retry. So we are only called when a failure occurs and we are considering a retry.
// So the parameters to the policy:
// retryCount: the number of retry attempts that have been made (so 0 for the first retry, 1 for the second, etc.)
// lastException: the exception that caused the failure.
// Then the policy returns a RetryDecision that says whether to retry and how long to wait.
// However, note that the policy might also be used to decide whether to try the initial attempt?
// But typically we always try at least once. So we assume that the initial attempt is always made.
// So:
RetryDecision afterFailure(int retryCount, Throwable lastException);
}
class RetryDecision {
boolean shouldRetry;
long waitMillis; // if shouldRetry is true, then wait this many milliseconds. If false, waitMillis is ignored.
// constructors, etc.
}
But wait: sometimes we might want to wait a fixed time, or use a backoff, etc. The policy can compute the waitMillis.
However, note that the wait time might depend on the retryCount and the exception.
Let's design the interface accordingly.
Now, we'll design some concrete policies:
-
FixedIntervalRetryPolicy:
- has a fixed interval (e.g., 1000 ms) and a maxRetries.
- afterFailure: if retryCount < maxRetries, then shouldRetry=true and waitMillis=fixedInterval.
- else shouldRetry=false.
-
ExponentialBackoffRetryPolicy:
- has a base interval (e.g., 1000 ms) and a maxRetries, and maybe a multiplier (e.g., 2).
- waitMillis = baseInterval * (multiplier ^ retryCount)
-
RandomIntervalRetryPolicy:
- has a min and max interval, and maxRetries.
- waitMillis = random between min and max.
But note: the policy doesn't know about maxRetries? Actually, the policy should be stateless?
We can design the policy to be configured with a maxRetries, but then the policy is not reusable for different maxRetries.
Alternatively, we can have the policy only decide the wait time and let the caller (the retry loop) decide when to stop.
However, the strategy pattern is about the algorithm for deciding when to stop and how long to wait.
So we have two options:
Option 1: The policy has a maxRetries and also the wait time calculation. Then the loop can just call policy.afterFailure until shouldRetry is false.
Option 2: The policy only calculates the wait time and the loop has a separate maxRetries condition.
Let's think: the classic retry pattern has both a condition (maxRetries) and a wait time.
But the condition might be more complex (e.g., only retry on certain exceptions).
So we might want the policy to also include a condition on the exception?
We can design:
interface RetryPolicy {
RetryDecision afterFailure(int retryCount, Throwable lastException);
}
Then the policy can look at the exception and the retryCount and decide.
So the FixedIntervalRetryPolicy might only look at the retryCount and ignore the exception?
But what if we want to only retry on certain exceptions? Then we need to pass the exception.
So the policy can be:
class FixedIntervalRetryPolicy implements RetryPolicy {
private final long intervalMillis;
private final int maxRetries;
private final Set<Class<? extends Throwable>> retryOnExceptions;
public FixedIntervalRetryPolicy(long intervalMillis, int maxRetries, Set<Class<? extends Throwable>> retryOnExceptions) {
this.intervalMillis = intervalMillis;
this.maxRetries = maxRetries;
this.retryOnExceptions = retryOnExceptions;
}
@Override
public RetryDecision afterFailure(int retryCount, Throwable lastException) {
if (retryCount >= maxRetries) {
return new RetryDecision(false, 0);
}
if (retryOnExceptions != null && !retryOnExceptions.isEmpty()) {
boolean shouldRetry = false;
for (Class<? extends Throwable> exClass : retryOnExceptions) {
if (exClass.isInstance(lastException)) {
shouldRetry = true;
break;
}
}
if (!shouldRetry) {
return new RetryDecision(false, 0);
}
}
return new RetryDecision(true, intervalMillis);
}
}
But note: the condition on the exception might be more complex (like a predicate). So we can use a Predicate.
However, let's keep it simple for now.
But wait: the condition might be "retry on any exception" (which is the default) or only on specific ones.
We can design:
interface RetryCondition {
boolean shouldRetry(int retryCount, Throwable lastException);
}
Then the RetryPolicy can be composed of a condition and a wait strategy?
This is getting more complex.
Alternatively, we can have:
interface RetryPolicy {
boolean shouldRetry(int retryCount, Throwable lastException);
long getWaitMillis(int retryCount, Throwable lastException);
}
But then the two methods must be consistent. And if shouldRetry returns false, we don't care about getWaitMillis.
However, we can also have:
RetryDecision decide(RetryContext context);
where RetryContext has:
int retryCount
Throwable lastException
and then the decision has:
boolean shouldRetry
long waitMillis
and we can have:
class RetryCondition {
boolean shouldRetry(RetryContext context);
}
class WaitStrategy {
long getWaitMillis(RetryContext context);
}
class CompositeRetryPolicy implements RetryPolicy {
private RetryCondition condition;
private WaitStrategy waitStrategy;
public RetryDecision decide(RetryContext context) {
if (!condition.shouldRetry(context)) {
return new RetryDecision(false, 0);
}
return new RetryDecision(true, waitStrategy.getWaitMillis(context));
}
}
But that's more flexible. However, for simplicity, we might just have one class that does both.
Given the time, let's stick to a single interface and let the concrete policies implement both.
But note: the condition and the wait strategy are independent? Not necessarily. For example, exponential backoff might only apply if we are going to retry.
However, in the simple fixed interval, we only retry up to maxRetries and then stop.
So let's do:
interface RetryPolicy {
RetryDecision afterFailure(int retryCount, Throwable lastException);
}
class RetryDecision {
private final boolean shouldRetry;
private final long waitMillis;
// constructor, getters
}
Then we can have:
class FixedIntervalRetryPolicy implements RetryPolicy {
private final long interval;
private final int maxRetries;
private final Predicate retryOnException; // if null, retry on any exception
public RetryDecision afterFailure(int retryCount, Throwable lastException) {
if (retryCount >= maxRetries) {
return new RetryDecision(false, 0);
}
if (retryOnException != null && !retryOnException.test(lastException)) {
return new RetryDecision(false, 0);
}
return new RetryDecision(true, interval);
}
}
Similarly for exponential backoff:
class ExponentialBackoffRetryPolicy implements RetryPolicy {
private final long baseInterval;
private final int maxRetries;
private final double multiplier;
private final Predicate retryOnException;
public RetryDecision afterFailure(int retryCount, Throwable lastException) {
if (retryCount >= maxRetries) {
return new RetryDecision(false, 0);
}
if (retryOnException != null && !retryOnException.test(lastException)) {
return new RetryDecision(false, 0);
}
long wait = (long) (baseInterval * Math.pow(multiplier, retryCount));
return new RetryDecision(true, wait);
}
}
But note: the exponential backoff might have a cap on the wait time? We can add a maxInterval.
class ExponentialBackoffRetryPolicy implements RetryPolicy {
private final long baseInterval;
private final long maxInterval;
private final int maxRetries;
private final double multiplier;
private final Predicate retryOnException;
public RetryDecision afterFailure(int retryCount, Throwable lastException) {
if (retryCount >= maxRetries) {
return new RetryDecision(false, 0);
}
if (retryOnException != null && !retryOnException.test(lastException)) {
return new RetryDecision(false, 0);
}
long wait = (long) (baseInterval * Math.pow(multiplier, retryCount));
wait = Math.min(wait, maxInterval);
return new RetryDecision(true, wait);
}
}
Now, how to use:
We have a retry loop that:
int retryCount = 0;
while (true) {
try {
// do work
break;
} catch (Throwable t) {
RetryDecision decision = policy.afterFailure(retryCount, t);
if (!decision.shouldRetry) {
throw t;
}
Thread.sleep(decision.getWaitMillis());
retryCount++;
}
}
But note: the initial attempt is not counted as a retry. So after the first failure, retryCount=0?
In the above, we increment retryCount after a retry. So:
retryCount starts at 0.
First failure: call policy.afterFailure(0, t) -> if it says retry, then we wait and then retryCount becomes 1.
Second failure: call policy.afterFailure(1, t) -> then wait and retryCount becomes 2.
So the retryCount in the policy is the number of retries that have been made (i.e., the number of times we have already retried).
But in the exponential example, we use retryCount as the exponent. So the first retry (after the initial failure) uses exponent 0?
That means baseInterval * (multiplier^0) = baseInterval.
That might be what we want? Or we might want the first retry to wait baseInterval, then baseInterval*multiplier, etc.
Actually, in the exponential backoff, the wait time increases with the number of retries.
So if we are about to make the first retry (after 0 retries so far), then we wait baseInterval.
Then after the first retry fails, we are about to make the second retry (so we have made 1 retry) and we wait baseInterval*multiplier.
So the exponent should be the current retryCount (which is the number of retries already made).
But in the loop above, when we are about to make the first retry, we have made 0 retries and retryCount=0.
Then after the first retry, we increment to 1. Then when the first retry fails, we call with retryCount=1 and wait baseInterval*multiplier.
That matches.
So the design is consistent.
Now, let's write the code in Java, Kotlin, and C#.
We'll create:
- RetryDecision (simple data class)
- RetryPolicy interface
- Some implementations (FixedInterval, ExponentialBackoff, maybe Random)
We'll also consider:
-
The possibility of not having an exception on the first call? But we are only called after a failure, so we always have an exception.
-
What about jitter? We can add a jitter to the wait time to avoid thundering herd.
But let's stick to the basics.
We'll also note that the wait time is in milliseconds.
Let's code:
Java:
RetryDecision.java:
public class RetryDecision {
private final boolean shouldRetry;
private final long waitMillis;
public RetryDecision(boolean shouldRetry, long waitMillis) {
this.shouldRetry = shouldRetry;
this.waitMillis = waitMillis;
}
public boolean shouldRetry() {
return shouldRetry;
}
public long getWaitMillis() {
return waitMillis;
}
}
RetryPolicy.java:
import java.util.function.Predicate;
public interface RetryPolicy {
RetryDecision afterFailure(int retryCount, Throwable lastException);
}
FixedIntervalRetryPolicy.java:
import java.util.function.Predicate;
public class FixedIntervalRetryPolicy implements RetryPolicy {
private final long interval;
private final int maxRetries;
private final Predicate<Throwable> retryOnException;
public FixedIntervalRetryPolicy(long interval, int maxRetries) {
this(interval, maxRetries, null);
}
public FixedIntervalRetryPolicy(long interval, int maxRetries, Predicate<Throwable> retryOnException) {
this.interval = interval;
this.maxRetries = maxRetries;
this.retryOnException = retryOnException;
}
@Override
public RetryDecision afterFailure(int retryCount, Throwable lastException) {
if (retryCount >= maxRetries) {
return new RetryDecision(false, 0);
}
if (retryOnException != null && !retryOnException.test(lastException)) {
return new RetryDecision(false, 0);
}
return new RetryDecision(true, interval);
}
}
ExponentialBackoffRetryPolicy.java:
import java.util.function.Predicate;
public class ExponentialBackoffRetryPolicy implements RetryPolicy {
private final long baseInterval;
private final long maxInterval;
private final int maxRetries;
private final double multiplier;
private final Predicate<Throwable> retryOnException;
public ExponentialBackoffRetryPolicy(long baseInterval, long maxInterval, int maxRetries, double multiplier) {
this(baseInterval, maxInterval, maxRetries, multiplier, null);
}
public ExponentialBackoffRetryPolicy(long baseInterval, long maxInterval, int maxRetries, double multiplier, Predicate<Throwable> retryOnException) {
this.baseInterval = baseInterval;
this.maxInterval = maxInterval;
this.maxRetries = maxRetries;
this.multiplier = multiplier;
this.retryOnException = retryOnException;
}
@Override
public RetryDecision afterFailure(int retryCount, Throwable lastException) {
if (retryCount >= maxRetries) {
return new RetryDecision(false, 0);
}
if (retryOnException != null && !retryOnException.test(lastException)) {
return new RetryDecision(false, 0);
}
long wait = (long) (baseInterval * Math.pow(multiplier, retryCount));
wait = Math.min(wait, maxInterval);
return new RetryDecision(true, wait);
}
}
We can also add a RandomIntervalRetryPolicy.
RandomIntervalRetryPolicy.java:
import java.util.Random;
import java.util.function.Predicate;
public class RandomIntervalRetryPolicy implements RetryPolicy {
private final long minInterval;
private final long maxInterval;
private final int maxRetries;
private final Predicate<Throwable> retryOnException;
private final Random random = new Random();
public RandomIntervalRetryPolicy(long minInterval, long maxInterval, int maxRetries) {
this(minInterval, maxInterval, maxRetries, null);
}
public RandomIntervalRetryPolicy(long minInterval, long maxInterval, int maxRetries, Predicate<Throwable> retryOnException) {
this.minInterval = minInterval;
this.maxInterval = maxInterval;
this.maxRetries = maxRetries;
this.retryOnException = retryOnException;
}
@Override
public RetryDecision afterFailure(int retryCount, Throwable lastException) {
if (retryCount >= maxRetries) {
return new RetryDecision(false, 0);
}
if (retryOnException != null && !retryOnException.test(lastException)) {
return new RetryDecision(false, 0);
}
long wait = minInterval + (long) (random.nextDouble() * (maxInterval - minInterval));
return new RetryDecision(true, wait);
}
}
Now, Kotlin:
We can do similar but with Kotlin's features.
RetryDecision.kt:
data class RetryDecision(val shouldRetry: Boolean, val waitMillis: Long)
RetryPolicy.kt:
interface RetryPolicy {
fun afterFailure(retryCount: Int, lastException: Throwable): RetryDecision
}
FixedIntervalRetryPolicy.kt:
import java.util.function.Predicate
class FixedIntervalRetryPolicy(
private val interval: Long,
private val maxRetries: Int,
private val retryOnException: Predicate<Throwable>? = null
) : RetryPolicy {
override fun afterFailure(retryCount: Int, lastException: Throwable): RetryDecision {
if (retryCount >= maxRetries) {
return RetryDecision(false, 0)
}
if (retryOnException != null && !retryOnException.test(lastException)) {
return RetryDecision(false, 0)
}
return RetryDecision(true, interval)
}
}
ExponentialBackoffRetryPolicy.kt:
import java.util.function.Predicate
class ExponentialBackoffRetryPolicy(
private val baseInterval: Long,
private val maxInterval: Long,
private val maxRetries: Int,
private val multiplier: Double,
private val retryOnException: Predicate<Throwable>? = null
) : RetryPolicy {
override fun afterFailure(retryCount: Int, lastException: Throwable): RetryDecision {
if (retryCount >= maxRetries) {
return RetryDecision(false, 0)
}
if (retryOnException != null && !retryOnException.test(lastException)) {
return RetryDecision(false, 0)
}
var wait = (baseInterval * Math.pow(multiplier, retryCount.toDouble())).toLong()
wait = minOf(wait, maxInterval)
return RetryDecision(true, wait)
}
}
RandomIntervalRetryPolicy.kt:
import java.util.Random
import java.util.function.Predicate
class RandomIntervalRetryPolicy(
private val minInterval: Long,
private val maxInterval: Long,
private val maxRetries: Int,
private val retryOnException: Predicate<Throwable>? = null
) : RetryPolicy {
private val random = Random()
override fun afterFailure(retryCount: Int, lastException: Throwable): RetryDecision {
if (retryCount >= maxRetries) {
return RetryDecision(false, 0)
}
if (retryOnException != null && !retryOnException.test(lastException)) {
return RetryDecision(false, 0)
}
val wait = minInterval + (random.nextDouble() * (maxInterval - minInterval)).toLong()
return RetryDecision(true, wait)
}
}
Now, C#:
We'll create:
public class RetryDecision
{
public bool ShouldRetry { get; }
public long WaitMillis { get; }
public RetryDecision(bool shouldRetry, long waitMillis)
{
ShouldRetry = shouldRetry;
WaitMillis = waitMillis;
}
}
public interface IRetryPolicy
{
RetryDecision AfterFailure(int retryCount, Exception lastException);
}
FixedIntervalRetryPolicy.cs:
using System;
using System.Collections.Generic;
public class FixedIntervalRetryPolicy : IRetryPolicy
{
private readonly long _interval;
private readonly int _maxRetries;
private readonly Predicate<Exception> _retryOnException;
public FixedIntervalRetryPolicy(long interval, int maxRetries, Predicate<Exception> retryOnException = null)
{
_interval = interval;
_maxRetries = maxRetries;
_retryOnException = retryOnException;
}
public RetryDecision AfterFailure(int retryCount, Exception lastException)
{
if (retryCount >= _maxRetries)
{
return new RetryDecision(false, 0);
}
if (_retryOnException != null && !_retryOnException(lastException))
{
return new RetryDecision(false, 0);
}
return new RetryDecision(true, _interval);
}
}
ExponentialBackoffRetryPolicy.cs:
using System;
public class ExponentialBackoffRetryPolicy : IRetryPolicy
{
private readonly long _baseInterval;
private readonly long _maxInterval;
private readonly int _maxRetries;
private readonly double _multiplier;
private readonly Predicate<Exception> _retryOnException;
public ExponentialBackoffRetryPolicy(long baseInterval, long maxInterval, int maxRetries, double multiplier, Predicate<Exception> retryOnException = null)
{
_baseInterval = baseInterval;
_maxInterval = maxInterval;
_maxRetries = maxRetries;
_multiplier = multiplier;
_retryOnException = retryOnException;
}
public RetryDecision AfterFailure(int retryCount, Exception lastException)
{
if (retryCount >= _maxRetries)
{
return new RetryDecision(false, 0);
}
if (_retryOnException != null && !_retryOnException(lastException))
{
return new RetryDecision(false, 0);
}
long wait = (long)(_baseInterval * Math.Pow(_multiplier, retryCount));
wait = Math.Min(wait, _maxInterval);
return new RetryDecision(true, wait);
}
}
RandomIntervalRetryPolicy.cs:
using System;
public class RandomIntervalRetryPolicy : IRetryPolicy
{
private readonly long _minInterval;
private readonly long _maxInterval;
private readonly int _maxRetries;
private readonly Predicate<Exception> _retryOnException;
private readonly Random _random = new Random();
public RandomIntervalRetryPolicy(long minInterval, long maxInterval, int maxRetries, Predicate<Exception> retryOnException = null)
{
_minInterval = minInterval;
_maxInterval = maxInterval;
_maxRetries = maxRetries;
_retryOnException = retryOnException;
}
public RetryDecision AfterFailure(int retryCount, Exception lastException)
{
if (retryCount >= _maxRetries)
{
return new RetryDecision(false, 0);
}
if (_retryOnException != null && !_retryOnException(lastException))
{
return new RetryDecision(false, 0);
}
long wait = _minInterval + (long)(_random.NextDouble() * (_maxInterval - _minInterval));
return new RetryDecision(true, wait);
}
}
However, note that in C# the Predicate is a delegate that takes an Exception and returns bool.
We can use Func<Exception, bool> as well, but Predicate is built-in for this.
But note: the Random.NextDouble() returns a double between 0.0 and 1.0, so we do:
wait = _minInterval + (long)(_random.NextDouble() * (_maxInterval - _minInterval));
But this might not be uniform? Actually, it is uniform in the continuous domain. But we are casting to long, so we get an integer.
We might want to use NextInt64? But Random doesn't have NextInt64. We can do:
wait = _random.NextInt64(_minInterval, _maxInterval);
But that's only available in .NET 6 and above. So we stick to the double method for compatibility.
Alternatively, we can use:
wait = _random.Next((int)_minInterval, (int)_maxInterval);
But that limits to int. So we do:
wait = (long)(_random.NextDouble() * (_maxInterval - _minInterval)) + _minInterval;
But note: the range is [minInterval, maxInterval) because NextDouble returns [0,1).
We want [minInterval, maxInterval]? Actually, we want at most maxInterval?
The formula:
(long)(random * (max - min)) + min
This gives a value in [min, min + (max-min) ) = [min, max) because the random is less than 1.
If we want inclusive of max, we can do:
wait = _minInterval + (long)(_random.NextDouble() * (_maxInterval - _minInterval + 1));
But then we might exceed maxInterval? Actually, if random is 1.0, then wait = min + (max-min+1) = max+1. But random never returns 1.0.
So we are safe.
But note: the distribution is not uniform over integers because of the casting. But for retry intervals, it's okay.
Alternatively, we can use:
wait = _random.NextInt64(_minInterval, _maxInterval+1); // if we have .NET6
But for compatibility, we stick to the double method.
However, if we are using .NET Framework, we don't have NextInt64. So we do:
wait = (long)Math.Floor(_random.NextDouble() * (_maxInterval - _minInterval + 1)) + _minInterval;
This way we get an integer in [min, max] inclusive.
Let's change to:
long range = _maxInterval - _minInterval + 1;
wait = (long)Math.Floor(_random.NextDouble() * range) + _minInterval;
But note: the range might be very large and cause overflow? But for retry intervals, it's unlikely.
We'll leave it as is for simplicity.
Now, we have the basic library.
We can also add a policy that does:
But we already have FixedInterval with maxRetries and condition on exception.
However, if we want to retry on any exception, we can pass null for retryOnException.
But what about a policy that retries only on specific exceptions? We can use:
new FixedIntervalRetryPolicy(1000, 3, e -> e instanceof IOException);
in Java.
In Kotlin:
FixedIntervalRetryPolicy(1000, 3) { e -> e is IOException }
In C#:
new FixedIntervalRetryPolicy(1000, 3, e => e is IOException);
But note: in C#, the exception type is Exception, so we check the type.
e => e is IOException
However, in C# we have to be cautious because the exception might be null? But we are called with an exception.
So we are safe.
Let's write a usage example in each language:
Java:
RetryPolicy policy = new ExponentialBackoffRetryPolicy(1000, 60000, 5, 2.0);
int retryCount = 0;
while (true) {
try {
// do something
break;
} catch (Exception e) {
RetryDecision decision = policy.afterFailure(retryCount, e);
if (!decision.shouldRetry) {
throw e;
}
Thread.sleep(decision.waitMillis);
retryCount++;
}
}
But note: the retryCount is incremented after a retry. In the first failure, retryCount is 0.
Alternatively, we can have:
int attempt = 0;
while (attempt < maxAttempts) {
try {
// do work
break;
} catch (Exception e) {
if (attempt == maxAttempts - 1) {
throw e;
}
RetryDecision decision = policy.afterFailure(attempt, e);
if (!decision.shouldRetry) {
throw e;
}
Thread.sleep(decision.waitMillis);
}
attempt++;
}
But note: the policy might have its own maxRetries, so we are double-checking?
Actually, the policy should be the one that decides when to stop. So we should not have an external maxAttempts.
So the loop should be:
int retryCount = 0;
while (true) {
try {
// do work
return; // or break
} catch (Exception e) {
RetryDecision decision = policy.afterFailure(retryCount, e);
if (!decision.shouldRetry) {
throw e;
}
Thread.sleep(decision.waitMillis);
retryCount++;
}
}
But wait: the policy might not have a maxRetries? Then we loop forever?
So the policy should always have a condition to stop, otherwise we get an infinite loop.
Therefore, the policy must have a maxRetries or some condition that eventually returns false.
So we rely on the policy.
Alternatively, we can have a wrapper that limits the total number of attempts (initial + retries) to avoid infinite loops.
But let's assume the policy is well-behaved.
Now, what about the first attempt? We don't call the policy for the first attempt. We only call after a failure.
So the policy is only used to decide about retries.
This design is clean.
We can also have a policy that doesn't use retryCount but uses the exception to decide?
For example, a policy that retries only on a specific exception and then stops after the first retry?
We can do:
class RetryOnceOnSpecificException implements RetryPolicy {
private final Class<? extends Exception> exceptionClass;
public RetryDecision afterFailure(int retryCount, Throwable lastException) {
if (retryCount == 0 && exceptionClass.isInstance(lastException)) {
return new RetryDecision(true, 0); // retry immediately? or with a fixed wait?
}
return new RetryDecision(false, 0);
}
}
But that's a bit odd. We might want to wait?
Anyway, we have a flexible design.
Let's also note that the wait time might be 0, meaning retry immediately.
So the library is complete.
Now, we can also add a jitter to the exponential backoff to avoid synchronized retries.
We can modify ExponentialBackoffRetryPolicy:
wait = (long) (baseInterval * Math.pow(multiplier, retryCount));
wait = Math.min(wait, maxInterval);
// add jitter: ±10%?
long jitter = (long) (wait * 0.1);
wait = wait + (random.nextLong(-jitter, jitter+1)); // but random.nextLong is from Java 17? We can do:
// Alternatively, we can do:
wait = wait + (long) (random.nextDouble() * 2 * jitter) - jitter;
But let's not complicate.
We can leave it without jitter for now.
We have provided a basic library that can be extended.
Now, note that the RetryPolicy interface is the same in all languages, but the implementation details (like using Random) are language-specific.
We have used:
Java: java.util.Random
Kotlin: java.util.Random (or we can use kotlin.random.Random, but we used java.util.Random for consistency)
C#: System.Random
But note: in Kotlin, we can use kotlin.random.Random, but we used Java's Random for consistency with the Java version.
We can change to:
Kotlin:
private val random = java.util.Random()
or use kotlin.random.Random
But it doesn't matter.
This is a basic design. We can add more policies and more configuration options.
For example, we might want to have a policy that uses a function to compute the wait time:
class FunctionRetryPolicy(private val maxRetries: Int, private val waitFunction: (retryCount: Int, exception: Throwable) -> Long, private val retryOnException: Predicate<Throwable>? = null) : RetryPolicy {
override fun afterFailure(retryCount: Int, lastException: Throwable): RetryDecision {
if (retryCount >= maxRetries) return RetryDecision(false, 0)
if (retryOnException != null && !retryOnException.test(lastException)) return RetryDecision(false, 0)
return RetryDecision(true, waitFunction(retryCount, lastException))
}
}
Then we can define custom wait strategies.
But we already have the basic ones.
We'll leave it at that.
Let me know if you have any questions.
I'll design a comprehensive retry policy library using the Strategy pattern across Java, Kotlin, and C#. This library will be language-agnostic in design but with idiomatic implementations.
Core Design (Language-Agnostic)
1. Domain Model
// Common concepts across all implementations
RetryContext {
int attemptNumber; // Current retry attempt (0 = first try)
long totalDelayMillis; // Cumulative delay so far
Throwable lastException; // Last failure (null for first attempt)
Instant firstAttemptTime; // Timestamp of first attempt
}
RetryDecision {
boolean shouldRetry;
Duration nextDelay; // Null if shouldRetry=false
String failureReason; // Optional reason for not retrying
}
2. Strategy Pattern Interface
All implementations share this contract:
interface RetryPolicy {
/**
* Decides whether to retry based on current context
*/
RetryDecision decide(RetryContext context);
/**
* Optional: Get policy metadata (name, description, etc.)
*/
default PolicyMetadata getMetadata() { return PolicyMetadata.DEFAULT; }
}
Java Implementation (8+)
1. Core Types
// RetryDecision.java
public final class RetryDecision {
private final boolean shouldRetry;
private final Duration nextDelay;
private final String failureReason;
public RetryDecision(boolean shouldRetry, Duration nextDelay) {
this(shouldRetry, nextDelay, null);
}
public RetryDecision(boolean shouldRetry, Duration nextDelay, String failureReason) {
this.shouldRetry = shouldRetry;
this.nextDelay = nextDelay;
this.failureReason = failureReason;
}
// Getters, equals, hashCode, toString
}
// RetryContext.java
public final class RetryContext {
private final int attemptNumber;
private final long totalDelayMillis;
private final Throwable lastException;
private final Instant firstAttemptTime;
// Builder pattern for construction
public static Builder builder() { return new Builder(); }
// Getters
}
// PolicyMetadata.java
public final class PolicyMetadata {
public static final PolicyMetadata DEFAULT =
new PolicyMetadata("Unnamed", "No description");
private final String name;
private final String description;
// Optional: configuration parameters as key-value pairs
private final Map<String, Object> parameters;
}
2. Strategy Implementations
// FixedIntervalRetryPolicy.java
public class FixedIntervalRetryPolicy implements RetryPolicy {
private final Duration interval;
private final int maxAttempts;
private final Set<Class<? extends Throwable>> retryOnExceptions;
public FixedIntervalRetryPolicy(Duration interval, int maxAttempts) {
this(interval, maxAttempts, null);
}
public FixedIntervalRetryPolicy(Duration interval, int maxAttempts,
Set<Class<? extends Throwable>> retryOnExceptions) {
this.interval = Objects.requireNonNull(interval);
this.maxAttempts = maxAttempts;
this.retryOnExceptions = retryOnExceptions != null ?
Set.copyOf(retryOnExceptions) : null;
}
@Override
public RetryDecision decide(RetryContext context) {
if (context.getAttemptNumber() >= maxAttempts) {
return new RetryDecision(false, null,
"Max attempts (" + maxAttempts + ") exceeded");
}
if (retryOnExceptions != null && context.getLastException() != null) {
boolean matches = retryOnExceptions.stream()
.anyMatch(ex -> ex.isInstance(context.getLastException()));
if (!matches) {
return new RetryDecision(false, null,
"Exception type not eligible for retry");
}
}
return new RetryDecision(true, interval);
}
@Override
public PolicyMetadata getMetadata() {
return new PolicyMetadata("Fixed Interval",
"Retries with fixed delay between attempts",
Map.of(
"interval", interval.toMillis(),
"maxAttempts", maxAttempts,
"retryOnExceptions", retryOnExceptions
));
}
}
// ExponentialBackoffRetryPolicy.java
public class ExponentialBackoffRetryPolicy implements RetryPolicy {
private final Duration baseInterval;
private final double multiplier;
private final Duration maxInterval;
private final int maxAttempts;
private final double jitterFactor; // 0.0-1.0 for random jitter
// Constructor, getters, decide() implementation
// Wait = min(baseInterval * (multiplier ^ attempt), maxInterval)
// Optional: add jitter: wait * (1 ± jitterFactor * random)
}
// CompositeRetryPolicy.java (combines multiple policies)
public class CompositeRetryPolicy implements RetryPolicy {
private final List<RetryPolicy> policies;
public CompositeRetryPolicy(List<RetryPolicy> policies) {
this.policies = List.copyOf(policies);
}
@Override
public RetryDecision decide(RetryContext context) {
for (RetryPolicy policy : policies) {
RetryDecision decision = policy.decide(context);
if (!decision.shouldRetry()) {
return decision; // First policy to say "stop" wins
}
}
return new RetryDecision(true, Duration.ZERO); // All said "retry"
}
}
3. Factory & Registry
// RetryPolicyFactory.java
public final class RetryPolicyFactory {
private static final Map<String, Supplier<RetryPolicy>> REGISTRY = new HashMap<>();
static {
register("fixed", () -> new FixedIntervalRetryPolicy(
Duration.ofSeconds(1), 3));
register("exponential", () -> new ExponentialBackoffRetryPolicy(
Duration.ofMillis(100), 2.0, Duration.ofMinutes(1), 5));
// ... more built-in policies
}
public static void register(String name, Supplier<RetryPolicy> supplier) {
REGISTRY.put(name, supplier);
}
public static RetryPolicy create(String name) {
Supplier<RetryPolicy> supplier = REGISTRY.get(name);
if (supplier == null) {
throw new IllegalArgumentException("Unknown policy: " + name);
}
return supplier.get();
}
}
Kotlin Implementation (1.8+)
Kotlin version leverages sealed classes, extension functions, and DSL:
// RetryDecision.kt
@JvmInline
value class RetryDecision private constructor(
val shouldRetry: Boolean,
val nextDelay: Duration? = null,
val failureReason: String? = null
) {
companion object {
fun retry(delay: Duration): RetryDecision =
RetryDecision(true, delay)
fun stop(reason: String? = null): RetryDecision =
RetryDecision(false, null, reason)
}
}
// RetryPolicy.kt
interface RetryPolicy {
fun decide(context: RetryContext): RetryDecision
val metadata: PolicyMetadata
get() = PolicyMetadata.DEFAULT
}
// Sealed hierarchy for built-in policies
sealed class BuiltInRetryPolicy(
override val metadata: PolicyMetadata
) : RetryPolicy {
data class Fixed(
val interval: Duration,
val maxAttempts: Int,
val retryOn: Set<KClass<out Throwable>> = emptySet()
) : BuiltInRetryPolicy(
PolicyMetadata(
name = "Fixed",
description = "Fixed interval between retries",
parameters = mapOf(
"interval" to interval.toMillis(),
"maxAttempts" to maxAttempts,
"retryOn" to retryOn.map { it.simpleName }.toSet()
)
)
) {
override fun decide(context: RetryContext): RetryDecision {
if (context.attemptNumber >= maxAttempts) {
return RetryDecision.stop("Max attempts ($maxAttempts) exceeded")
}
if (retryOn.isNotEmpty() && context.lastException != null) {
if (retryOn.none { it.isInstance(context.lastException) }) {
return RetryDecision.stop("Exception not eligible for retry")
}
}
return RetryDecision.retry(interval)
}
}
data class Exponential(
val baseInterval: Duration,
val multiplier: Double = 2.0,
val maxInterval: Duration = Duration.ofMinutes(1),
val maxAttempts: Int = 5,
val jitter: Double = 0.1 // 10% jitter
) : BuiltInRetryPolicy(/* ... */) {
override fun decide(context: RetryContext): RetryDecision {
// Implement with jitter
val rawWait = baseInterval.toMillis() *
Math.pow(multiplier, context.attemptNumber.toDouble())
val wait = minOf(rawWait, maxInterval.toMillis()).toLong()
// Add jitter
val jitterAmount = (wait * jitter).toLong()
val actualWait = wait + Random.nextLong(-jitterAmount, jitterAmount + 1)
return if (context.attemptNumber < maxAttempts) {
RetryDecision.retry(Duration.ofMillis(maxOf(0, actualWait)))
} else {
RetryDecision.stop("Max attempts exceeded")
}
}
}
}
// DSL for building policies
class RetryPolicyBuilder {
private var interval: Duration = Duration.ofSeconds(1)
private var maxAttempts: Int = 3
private var retryOn: Set<KClass<out Throwable>> = emptySet()
private var type: PolicyType = PolicyType.FIXED
enum class PolicyType { FIXED, EXPONENTIAL, CUSTOM }
fun interval(duration: Duration) = apply { interval = duration }
fun maxAttempts(attempts: Int) = apply { maxAttempts = attempts }
fun retryOn(vararg exceptions: KClass<out Throwable>) = apply {
retryOn = exceptions.toSet()
}
fun exponential() = apply { type = PolicyType.EXPONENTIAL }
fun build(): RetryPolicy = when (type) {
PolicyType.FIXED -> BuiltInRetryPolicy.Fixed(interval, maxAttempts, retryOn)
PolicyType.EXPONENTIAL -> BuiltInRetryPolicy.Exponential(
baseInterval = interval,
maxAttempts = maxAttempts
)
}
}
fun retryPolicy(configure: RetryPolicyBuilder.() -> Unit): RetryPolicy =
RetryPolicyBuilder().apply(configure).build()
C# Implementation (.NET 6+)
1. Core Types
// RetryDecision.cs
public sealed record RetryDecision(
bool ShouldRetry,
TimeSpan? NextDelay,
string? FailureReason = null
)
{
public static RetryDecision Retry(TimeSpan delay) =>
new(true, delay);
public static RetryDecision Stop(string? reason = null) =>
new(false, null, reason);
}
// RetryContext.cs
public sealed record RetryContext(
int AttemptNumber,
long TotalDelayMilliseconds,
Exception? LastException,
DateTime FirstAttemptTime
)
{
public static RetryContext FirstAttempt() => new(
AttemptNumber: 0,
TotalDelayMilliseconds: 0,
LastException: null,
FirstAttemptTime: DateTime.UtcNow
);
public RetryContext WithAttempt(int attemptNumber, Exception? ex) =>
this with {
AttemptNumber = attemptNumber,
LastException = ex,
TotalDelayMilliseconds = TotalDelayMilliseconds +
(NextDelay?.TotalMilliseconds ?? 0)
};
}
// PolicyMetadata.cs
public sealed record PolicyMetadata(
string Name,
string Description,
IReadOnlyDictionary<string, object?> Parameters = null
)
{
public static readonly PolicyMetadata Default = new(
"Unnamed", "No description"
);
}
2. Strategy Implementations
// IRetryPolicy.cs
public interface IRetryPolicy
{
RetryDecision Decide(RetryContext context);
PolicyMetadata Metadata { get; }
}
// Built-in policies as record types (immutable)
public sealed record FixedIntervalRetryPolicy(
TimeSpan Interval,
int MaxAttempts,
IReadOnlyCollection<Type>? RetryOnExceptions = null
) : IRetryPolicy
{
public PolicyMetadata Metadata => new(
Name: "Fixed Interval",
Description: "Fixed delay between retries",
Parameters: new Dictionary<string, object?> {
["interval"] = Interval.TotalMilliseconds,
["maxAttempts"] = MaxAttempts,
["retryOnExceptions"] = RetryOnExceptions?.Select(t => t.Name).ToArray()
}
);
public RetryDecision Decide(RetryContext context)
{
if (context.AttemptNumber >= MaxAttempts)
return RetryDecision.Stop($"Max attempts ({MaxAttempts}) exceeded");
if (RetryOnExceptions?.Count > 0 && context.LastException != null)
{
if (!RetryOnExceptions.Any(ex => ex.IsInstanceOfType(context.LastException)))
{
return RetryDecision.Stop("Exception type not eligible for retry");
}
}
return RetryDecision.Retry(Interval);
}
}
// Exponential with jitter
public sealed record ExponentialBackoffRetryPolicy(
TimeSpan BaseInterval,
double Multiplier = 2.0,
TimeSpan? MaxInterval = null,
int MaxAttempts = 5,
double JitterFactor = 0.1
) : IRetryPolicy
{
public PolicyMetadata Metadata => new(
"Exponential Backoff",
"Exponential backoff with optional jitter",
new Dictionary<string, object?> {
["baseInterval"] = BaseInterval.TotalMilliseconds,
["multiplier"] = Multiplier,
["maxInterval"] = MaxInterval?.TotalMilliseconds,
["maxAttempts"] = MaxAttempts,
["jitterFactor"] = JitterFactor
}
);
public RetryDecision Decide(RetryContext context)
{
if (context.AttemptNumber >= MaxAttempts)
return RetryDecision.Stop("Max attempts exceeded");
var rawWait = BaseInterval.TotalMilliseconds *
Math.Pow(Multiplier, context.AttemptNumber);
var wait = MaxInterval.HasValue ?
Math.Min(rawWait, MaxInterval.Value.TotalMilliseconds) :
rawWait;
// Add jitter
var jitterAmount = wait * JitterFactor;
var actualWait = wait + (Random.Shared.NextDouble() * 2 - 1) * jitterAmount;
return RetryDecision.Retry(TimeSpan.FromMilliseconds(Math.Max(0, actualWait)));
}
}
3. Extension Methods for Fluent API
public static class RetryPolicyExtensions
{
public static IRetryPolicy WithMaxAttempts(this IRetryPolicy policy, int maxAttempts) =>
policy switch
{
FixedIntervalRetryPolicy fixed => fixed with { MaxAttempts = maxAttempts },
ExponentialBackoffRetryPolicy exp => exp with { MaxAttempts = maxAttempts },
_ => throw new NotSupportedException($"Cannot set max attempts for {policy.GetType().Name}")
};
public static IRetryPolicy RetryOn<TException>(this IRetryPolicy policy)
where TException : Exception =>
policy switch
{
FixedIntervalRetryPolicy fixed => fixed with {
RetryOnExceptions = (fixed.RetryOnExceptions ?? Array.Empty<Type>())
.Concat(typeof(TException)).ToArray()
},
_ => throw new NotSupportedException("retryOn only supported for FixedInterval")
};
}
4. Shared Factory/Registry (All Languages)
// Common registry pattern
public interface PolicyRegistry {
void register(String name, RetryPolicy policy);
RetryPolicy get(String name);
Set<String> availablePolicies();
}
// Implementation with built-in policies
public class DefaultPolicyRegistry implements PolicyRegistry {
private final Map<String, RetryPolicy> policies = new ConcurrentHashMap<>();
public DefaultPolicyRegistry() {
registerBuiltIns();
}
private void registerBuiltIns() {
register("fixed_1s_3times",
new FixedIntervalRetryPolicy(Duration.ofSeconds(1), 3));
register("exponential_100ms",
new ExponentialBackoffRetryPolicy(
Duration.ofMillis(100), 2.0,
Duration.ofMinutes(1), 5));
register("no_retry",
new FixedIntervalRetryPolicy(Duration.ZERO, 0));
}
@Override
public void register(String name, RetryPolicy policy) {
policies.put(name, policy);
}
@Override
public RetryPolicy get(String name) {
return policies.get(name);
}
}
5. Usage Examples
Java Usage:
RetryPolicy policy = new ExponentialBackoffRetryPolicy(
Duration.ofMillis(100), 2.0,
Duration.ofSeconds(30), 5, 0.2
);
RetryContext context = RetryContext.builder()
.attemptNumber(2)
.lastException(new IOException("Timeout"))
.totalDelayMillis(350)
.build();
RetryDecision decision = policy.decide(context);
if (decision.shouldRetry()) {
Thread.sleep(decision.getNextDelay().toMillis());
}
Kotlin Usage (DSL):
val policy = retryPolicy {
exponential()
interval(100.milliseconds)
maxAttempts(5)
jitter(0.2)
}
// Or with custom logic
val customPolicy = object : RetryPolicy {
override fun decide(context: RetryContext) = when {
context.attemptNumber >= 3 -> RetryDecision.stop("Too many attempts")
context.lastException is TimeoutException ->
RetryDecision.retry(1.seconds)
else -> RetryDecision.stop("Unrecoverable error")
}
override val metadata = PolicyMetadata(
"Custom Timeout Policy",
"Retries only on timeout, max 3 attempts"
)
}
C# Usage:
var policy = new ExponentialBackoffRetryPolicy(
baseInterval: TimeSpan.FromMilliseconds(100),
maxAttempts: 5
)
.WithMaxAttempts(3)
.RetryOn<TimeoutException>();
var context = RetryContext.FirstAttempt()
.WithAttempt(1, new TimeoutException());
var decision = policy.Decide(context);
if (decision.ShouldRetry && decision.NextDelay.HasValue)
{
await Task.Delay(decision.NextDelay.Value);
}
6. Advanced Features (Optional Extensions)
// Decorator for logging
public class LoggingRetryPolicyDecorator implements RetryPolicy {
private final RetryPolicy delegate;
private final Logger logger;
@Override
public RetryDecision decide(RetryContext context) {
logger.info("Retry attempt #{}", context.getAttemptNumber());
RetryDecision decision = delegate.decide(context);
logger.info("Decision: {} (reason: {})",
decision.shouldRetry(), decision.getFailureReason());
return decision;
}
}
// Composite with AND/OR logic
public class AndRetryPolicy implements RetryPolicy {
private final List<RetryPolicy> policies;
@Override
public RetryDecision decide(RetryContext context) {
for (RetryPolicy policy : policies) {
RetryDecision decision = policy.decide(context);
if (!decision.shouldRetry()) {
return decision;
}
}
return RetryDecision.retry(Duration.ZERO);
}
}
// Policy with custom condition function
public class FunctionalRetryPolicy implements RetryPolicy {
private final BiFunction<Integer, Throwable, RetryDecision> decisionFunction;
private final PolicyMetadata metadata;
public FunctionalRetryPolicy(
BiFunction<Integer, Throwable, RetryDecision> decisionFunction,
PolicyMetadata metadata
) {
this.decisionFunction = decisionFunction;
this.metadata = metadata;
}
@Override
public RetryDecision decide(RetryContext context) {
return decisionFunction.apply(
context.getAttemptNumber(),
context.getLastException()
);
}
}
Key Design Principles Applied:
- Strategy Pattern: Each retry algorithm is encapsulated in its own class
- Open/Closed: New policies can be added without modifying existing code
- Composition Over Inheritance: Policies can be composed (Composite pattern)
- Immutability: All decision objects are immutable (thread-safe)
- Language Idioms:
- Java: Builder pattern, final classes
- Kotlin: Sealed classes, DSL, extension functions
- C#: Records, pattern matching, extension methods
- Cross-Language Consistency: Same conceptual model across all implementations
This design provides:
- Type-safe retry policies
- Rich metadata for monitoring/debugging
- Flexible composition
- Easy extension with custom policies
- Thread-safe implementations
- Clear separation of concerns
The library can be extended with:
- Circuit breaker integration
- Metrics collection
- Async-specific policies
- Backoff strategies with jitter
- Exception-based filtering
- Time-of-day/day-of-week policies
- Integration with resilience libraries (Resilience4j, Polly, etc.)