We are going to design a retry policy validator. The validator will check a given retry policy for:
- Idempotency proofs: We need to ensure that the retry policy is safe for idempotent operations. This means that the same request can be retried multiple times without causing unintended side effects.
- Backoff rules: We need to validate that the backoff strategy (e.g., exponential backoff) is correctly implemented and adheres to best practices (min and max delays, jitter, etc.)
- Simulation: We might want to simulate the retry policy under different failure scenarios to see how it behaves (e.g., number of retries, total time, etc.)
Let's break down the requirements:
-
Idempotency proofs:
- We assume that the retry policy is for an idempotent operation (like GET, PUT, DELETE) or that the operation has been made idempotent by the client (e.g., using an idempotency key).
- The validator should check that the retry policy does not retry non-idempotent operations (like POST without an idempotency key) unless explicitly allowed (maybe by the user?).
- However, note: in practice, the idempotency of the operation is not something the retry policy can know. So perhaps we assume the operation is idempotent and the policy is designed for idempotent retries.
- Alternatively, we can have a flag in the retry policy that indicates whether it is for idempotent operations only. Then the validator can check that if the operation is non-idempotent, then the retry policy must have a way to ensure safety (like using an idempotency key). But we don't have the operation context.
Since the problem says "idempotency proofs", maybe we want to generate a proof that the retry policy is safe for idempotent operations? That might be too formal.
Let's simplify: we'll assume that the retry policy is intended for idempotent operations. We'll check:
- The maximum number of retries is bounded (so we don't retry forever).
- The backoff strategy does not cause excessive retries in a short time (but that's more about rate limiting).
Actually, idempotency in retries means that multiple identical requests have the same effect as one. The retry policy itself doesn't break idempotency if the operation is idempotent. But if the operation is not idempotent, then retrying can cause problems.
So perhaps the validator should take as input:
- The retry policy (with backoff rules, max retries, etc.)
- A flag indicating if the operation is idempotent (or if an idempotency key is used).
Then, if the operation is non-idempotent and no idempotency key is used, we should warn or fail.
Alternatively, we can have the retry policy include a field idempotent (boolean) and then the validator checks that if idempotent is false, then the policy must have max_retries=0? That might be too strict.
Given the ambiguity, I'll define:
We are given a retry policy configuration that includes:
- max_retries: integer (>=0)
- backoff_strategy: one of ["fixed", "exponential", "linear", etc.]
- initial_backoff: duration (e.g., 1 second)
- max_backoff: duration (optional, for exponential)
- multiplier: for exponential (e.g., 2)
- jitter: boolean or a jitter strategy (e.g., "full", "none")
And we are also given:
- is_idempotent: boolean (does the operation have idempotency guarantees?)
Then the validator for idempotency proofs would check:
If is_idempotent is false:
- Then the retry policy must have max_retries == 0? Or maybe we require that the operation uses an idempotency key? But we don't have that info.
Alternatively, we can think: even for non-idempotent operations, if we use an idempotency key, then it's safe. So we might need a flag uses_idempotency_key.
Let's change the input to:
retry_policy = {
"max_retries": 3,
"backoff": {
"type": "exponential",
"initial": 1000, // ms
"max": 60000, // ms
"multiplier": 2,
"jitter": "full"
},
"idempotent": true, // or we can have "safe_for_non_idempotent" if we have an idempotency key?
}
But note: the retry policy itself might not know about the operation's idempotency. So perhaps the validator is used in a context where the operation is known.
Given the problem statement, I think we are to design a validator that takes a retry policy and checks:
- For idempotency: we want to ensure that the policy is safe for idempotent operations? Actually, any policy is safe for idempotent operations because retrying an idempotent operation is safe.
The danger is when the operation is not idempotent. So the validator should check that if the operation is non-idempotent, then the retry policy must be set to 0 retries? But then what about operations that are made idempotent by an idempotency key?
Let's assume we have two boolean flags in the retry policy (or in the context):
operation_is_idempotent: false
operation_uses_idempotency_key: true
Then it's safe to retry.
So the validator for idempotency proofs would check:
if not operation_is_idempotent and not operation_uses_idempotency_key:
then retry_policy.max_retries must be 0
But wait, even if we use an idempotency key, we might want to retry. So we don't want to force max_retries=0 in that case.
Actually, the idempotency key makes the operation idempotent. So we can treat:
effective_idempotent = operation_is_idempotent or operation_uses_idempotency_key
Then if effective_idempotent is false, then we must have max_retries=0.
So the validator:
def validate_idempotency(operation_is_idempotent, operation_uses_idempotency_key, retry_policy):
effective_idempotent = operation_is_idempotent or operation_uses_idempotency_key
if not effective_idempotent and retry_policy['max_retries'] > 0:
return False, "Non-idempotent operation without idempotency key cannot have retries"
return True, ""
But note: the retry policy might have conditions (like only retry on certain errors). That doesn't change the idempotency issue.
-
Backoff rules:
We need to validate the backoff strategy:
- The initial_backoff must be positive.
- For exponential: multiplier must be > 1, and max_backoff must be >= initial_backoff.
- For fixed: no multiplier, but we might have jitter? Usually fixed with jitter is allowed.
- The jitter, if present, must be one of the allowed values (e.g., "none", "full", "equal").
Also, we might want to check that the backoff does not exceed a certain total time? But that's more about the simulation.
Alternatively, we can compute the maximum total time for the retries and check it doesn't exceed a threshold? But that threshold might be context dependent.
Let's stick to the structure of the backoff parameters.
We'll validate:
backoff = retry_policy['backoff']
if backoff['type'] == 'exponential':
assert backoff['initial'] > 0
assert backoff['multiplier'] > 1
if 'max' in backoff:
assert backoff['max'] >= backoff['initial']
else:
# if max is not set, then we might get very large backoffs? But that's allowed.
pass
if backoff['type'] == 'fixed':
assert backoff['initial'] > 0
# no multiplier? We can ignore multiplier if present?
if 'jitter' in backoff:
assert backoff['jitter'] in ['none', 'full', 'equal'] # or whatever we support
Also, we might want to check that the backoff for each retry attempt is increasing? That's inherent in exponential and linear.
-
Simulation:
We want to simulate the retry policy to see the total time and the backoff schedule.
Given a sequence of failures (or a probability of failure) we can simulate the retries.
But note: the retry policy might have conditions (like only retry on 5xx). So we need to know the error codes.
Let's assume we are given:
failures: a list of booleans (or error codes) for each attempt? Actually, we don't know how many attempts until we stop.
Alternatively, we can simulate until we either succeed or run out of retries.
We need:
- A function that, given the retry policy and a sequence of errors (or a function that returns whether the request fails and the error code), returns:
- the number of attempts
- the total time elapsed
- the backoff schedule (list of delays before each retry)
But note: the backoff schedule might depend on the attempt number and the jitter.
Let's define:
def simulate_retry(retry_policy, error_func, max_attempts=None):
"""
error_func: a function that takes the attempt number (starting at 1) and returns:
- True if the request succeeds, False if it fails.
- Alternatively, it could return an error code and we check if it's retryable.
We assume that the first attempt is attempt 1.
We retry up to retry_policy['max_retries'] times (so total attempts = 1 + max_retries).
We return:
attempts: list of attempt numbers (starting at 1) that were made.
delays: list of delays (in seconds) before each retry (so len(delays) = len(attempts)-1)
total_time: total time from first attempt to the last response (including the last attempt's duration?).
But note: we don't know the duration of the request itself, only the backoff delays.
We assume each request takes 0 time? Or we can have a fixed request duration? Let's assume we are only interested in the backoff delays.
Alternatively, we can return the schedule of backoff delays and the total backoff time.
We'll return:
schedule: list of (attempt, delay_before_retry) for each retry (so for n retries, we have n delays, and the first attempt has no delay before it).
Actually, we want to see the delays between attempts.
Example:
attempt 1: no delay (start at time 0)
if fails, wait delay1, then attempt 2.
if fails, wait delay2, then attempt 3.
So the delays are the backoff for each retry attempt (i.e., after failure of attempt i, we wait delay_i before attempt i+1).
We'll compute:
delays = []
for i in range(1, retry_policy['max_retries']+1):
if we are going to do a retry (i.e., after failure of attempt i), then compute the backoff for the i-th retry.
How to compute the backoff for the i-th retry?
base_backoff = compute_base_backoff(i, retry_policy['backoff'])
then apply jitter.
We can define:
def compute_base_backoff(attempt, backoff):
if backoff['type'] == 'fixed':
return backoff['initial']
elif backoff['type'] == 'exponential':
# attempt 1 (first retry) uses initial * multiplier^(1-1) = initial
# attempt 2: initial * multiplier^(2-1)
# so for the i-th retry (i starting at 1), we do initial * multiplier^(i-1)
backoff = backoff['initial'] * (backoff['multiplier'] ** (attempt-1))
if 'max' in backoff:
backoff = min(backoff, backoff['max'])
return backoff
elif backoff['type'] == 'linear':
# linear: initial + (attempt-1) * increment? But we don't have increment.
# Let's assume linear is: initial + (attempt-1) * initial? That's just exponential with multiplier 1? Not.
Actually, linear backoff is usually: initial + (attempt-1) * increment.
We don't have an increment field. So maybe we don't support linear? Or we can assume:
linear: backoff = initial * attempt? That's exponential with multiplier 1? No.
Let's change: we'll support:
fixed: constant
exponential: initial * multiplier^(attempt-1)
linear: initial + (attempt-1) * increment
We need an 'increment' for linear.
Given the complexity, let's stick to exponential and fixed for now.
So:
base = backoff['initial'] * (backoff['multiplier'] ** (attempt-1))
if 'max' in backoff and base > backoff['max']:
base = backoff['max']
Then apply jitter:
if backoff['jitter'] == 'none':
delay = base
elif backoff['jitter'] == 'full':
# full jitter: random between 0 and base
delay = random.uniform(0, base)
elif backoff['jitter'] == 'equal':
# equal jitter: base/2 + random between 0 and base/2
delay = base/2 + random.uniform(0, base/2)
But note: jitter is applied per retry.
-
Simulation:
We can run the simulation with a given error function (or a fixed number of consecutive failures) and then:
- Check that the total time (sum of delays) does not exceed a certain threshold? But that threshold might be application specific.
Alternatively, we can run the simulation and output the schedule and total time.
The validator for simulation might be:
def validate_simulation(retry_policy, error_func, max_total_time=None):
attempts, delays, total_backoff_time = simulate_retry(retry_policy, error_func)
if max_total_time is not None and total_backoff_time > max_total_time:
return False, f"Total backoff time {total_backoff_time} exceeds {max_total_time}"
return True, ""
But note: the error_func might be random, so we might want to run multiple simulations.
However, for validation, we might want to check the worst-case (no success until max_retries) and best-case (success on first try) scenarios.
We can have:
validate_simulation_worst_case(retry_policy, max_total_time=None)
which assumes that we fail all the time until max_retries.
Then:
total_backoff_time = sum of delays for all retries (max_retries delays) in the worst case.
But note: in the worst case, we do all retries, so we have max_retries delays.
However, if the backoff is increasing, the last backoff might be capped by max_backoff.
So we can compute the worst-case total backoff time by:
delays = []
for i in range(1, retry_policy['max_retries']+1):
delay = compute_backoff(i, retry_policy['backoff'])
delays.append(delay)
total = sum(delays)
But note: jitter is random. We can take the maximum possible jitter? For full jitter, the maximum is base. For equal jitter, the maximum is base/2 + base/2 = base. So the maximum delay for a given retry is the base.
So worst-case total backoff time = sum of base backoffs for all retries (without jitter reduction).
Alternatively, we can compute the expected total backoff time? But that's more complex.
Given the problem, let's assume we want to check the worst-case (without jitter, or with jitter set to the maximum) for the total time.
But note: the jitter might be set to 'none', then we have exact base.
So:
worst_case_total = 0
for i in range(1, retry_policy['max_retries']+1):
base = compute_base_backoff(i, retry_policy['backoff']) # without jitter
worst_case_total += base
Then compare with max_total_time.
However, if the backoff type is fixed, then base is constant.
So we can have:
def compute_base_backoff(retry_index, backoff):
if backoff['type'] == 'fixed':
return backoff['initial']
elif backoff['type'] == 'exponential':
base = backoff['initial'] * (backoff['multiplier'] ** (retry_index-1))
if 'max' in backoff:
base = min(base, backoff['max'])
return base
else:
raise ValueError()
Then worst_case_total = sum(compute_base_backoff(i, backoff) for i in range(1, max_retries+1))
Putting it all together:
We'll design a class RetryPolicyValidator that takes a retry policy configuration and then has methods:
validate_idempotency(operation_is_idempotent, operation_uses_idempotency_key) -> (bool, str)
validate_backoff_rules() -> (bool, str)
validate_simulation_worst_case(max_total_time) -> (bool, str)
But note: the simulate method might be separate for actually running the simulation (with a given error function).
Alternatively, we can have:
get_worst_case_total_backoff() -> float
and then the user can compare.
Let's design:
class RetryPolicyValidator:
def init(self, retry_policy):
self.retry_policy = retry_policy
def validate_idempotency(self, operation_is_idempotent, operation_uses_idempotency_key):
effective_idempotent = operation_is_idempotent or operation_uses_idempotency_key
if not effective_idempotent and self.retry_policy['max_retries'] > 0:
return False, "Cannot retry non-idempotent operation without idempotency key"
return True, ""
def validate_backoff_rules(self):
backoff = self.retry_policy['backoff']
# Check initial backoff
if backoff['initial'] <= 0:
return False, "initial backoff must be positive"
if backoff['type'] == 'exponential':
if backoff.get('multiplier', 1) <= 1:
return False, "exponential multiplier must be > 1"
if 'max' in backoff and backoff['max'] < backoff['initial']:
return False, "max backoff must be >= initial backoff"
elif backoff['type'] == 'fixed':
# We don't require multiplier, but if present, we ignore? Or we can check that multiplier is not present?
pass
else:
return False, f"Unsupported backoff type: {backoff['type']}"
if 'jitter' in backoff and backoff['jitter'] not in ['none', 'full', 'equal']:
return False, f"Unsupported jitter: {backoff['jitter']}"
return True, ""
def get_worst_case_total_backoff(self):
total = 0
for i in range(1, self.retry_policy['max_retries']+1):
total += self._compute_base_backoff(i)
return total
def _compute_base_backoff(self, retry_index):
backoff = self.retry_policy['backoff']
if backoff['type'] == 'fixed':
return backoff['initial']
elif backoff['type'] == 'exponential':
base = backoff['initial'] * (backoff['multiplier'] ** (retry_index-1))
if 'max' in backoff:
base = min(base, backoff['max'])
return base
else:
raise ValueError(f"Unsupported backoff type: {backoff['type']}")
def validate_simulation_worst_case(self, max_total_time):
total = self.get_worst_case_total_backoff()
if total > max_total_time:
return False, f"Worst-case total backoff time {total} exceeds {max_total_time}"
return True, ""
# Optionally, we can have a simulate method that runs a simulation with a given error function.
def simulate(self, error_func):
"""
error_func: function(attempt_number) -> bool (True for success, False for failure)
Returns: (attempts, delays, success)
attempts: list of attempt numbers (starting at 1) that were made.
delays: list of delays (in the same units as backoff) before each retry (so len(delays) = len(attempts)-1)
success: whether the last attempt succeeded.
"""
attempts = []
delays = []
attempt = 1
while attempt <= self.retry_policy['max_retries']+1:
attempts.append(attempt)
success = error_func(attempt)
if success:
break
if attempt < self.retry_policy['max_retries']+1:
delay = self._compute_backoff(attempt) # delay after failure of attempt `attempt` (which is the retry index = attempt)
delays.append(delay)
attempt += 1
return attempts, delays, success
def _compute_backoff(self, retry_index):
base = self._compute_base_backoff(retry_index)
backoff = self.retry_policy['backoff']
jitter = backoff.get('jitter', 'none')
if jitter == 'none':
return base
elif jitter == 'full':
return random.uniform(0, base)
elif jitter == 'equal':
return base/2 + random.uniform(0, base/2)
else:
return base
However, note: the simulate method uses jitter, so it's random. We might want to run multiple simulations and take the average? But that's beyond validation.
The validator is for checking the policy configuration, not for stochastic analysis.
So we leave the simulation as a helper.
But note: the worst-case total backoff we computed is without jitter (or with maximum jitter, which is the same as base). So it's the maximum possible total backoff.
We can also compute the best-case (no retries) total backoff = 0.
So the worst-case validation is the one that matters for timeouts.
Let's adjust: the worst-case total backoff (with jitter set to maximum) is the sum of base backoffs. But note: with jitter, the actual delay might be less, so the worst-case is without jitter reduction? Actually, with full jitter, the maximum is base. So the worst-case total backoff is the sum of base backoffs.
So we are correct.
Now, let's write the code accordingly.
However, note: the compute_base_backoff for exponential might be very large (exponential growth) and we cap it by max_backoff. So the worst-case total might be:
sum_{i=1}^{max_retries} min(initial * multiplier^(i-1), max_backoff)
This is what we compute.
Let's code accordingly.
We assume the retry_policy dictionary has:
{
"max_retries": 3,
"backoff": {
"type": "exponential",
"initial": 1000,
"max": 60000,
"multiplier": 2,
"jitter": "full"
}
}
And for idempotency, we have separate flags.
We'll create the class as above.
But note: the validate_idempotency method requires operation flags. We can have:
validator = RetryPolicyValidator(policy)
ok, msg = validator.validate_idempotency(operation_is_idempotent, operation_uses_idempotency_key)
Alternatively, we can have the operation flags in the policy? But the problem says "retry policy validator", so the policy is about retries, and the operation properties are separate.
We'll keep them separate.
Let's code accordingly.
However, note: the operation might be considered idempotent by the retry policy? Actually, the retry policy doesn't know.
So the user of the validator must provide the operation's idempotency properties.
We'll do that.
Let's write the code with detailed comments.
We'll also add a method to compute the schedule of backoff delays (without jitter) for the worst-case (all retries) for analysis.
We might want to see the individual delays.
So:
def get_worst_case_schedule(self):
schedule = []
for i in range(1, self.retry_policy['max_retries']+1):
schedule.append(self._compute_base_backoff(i))
return schedule
Then the total is sum(schedule).
Now, note: the backoff for the i-th retry (i from 1 to max_retries) is computed as above.
We are done.
Let's write the code.
We assume the retry_policy is a dictionary.
We'll also add type hints for clarity.
However, the problem says "design", so we are providing an outline.
Let's code accordingly.
I'll design a comprehensive retry policy validator that addresses idempotency safety, backoff validation, and simulation capabilities. This would be useful for systems engineers, SREs, and developers implementing resilient services.
RetryPolicyValidator - Core Design
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from enum import Enum
from typing import List, Optional, Callable, Dict, Any, Tuple
import random
import math
from datetime import datetime, timedelta
import json
# ========== 1. IDEMPOTENCY PROOFS ==========
class IdempotencyKeyStrategy(Enum):
"""How idempotency keys are handled"""
REQUIRED = "required" # Must provide idempotency key
OPTIONAL = "optional" # Can provide but not required
AUTO_GENERATED = "auto" # System generates automatically
UNSUPPORTED = "unsupported" # Not supported for this operation
@dataclass
class IdempotencyProof:
"""Proof that retries are safe for this operation"""
operation_type: str # HTTP method, command name, etc.
is_idempotent: bool # True if operation is inherently idempotent
key_strategy: IdempotencyKeyStrategy
key_location: str # Header name, parameter name, etc.
key_ttl_seconds: Optional[int] # How long key is valid
evidence: str # Documentation link, design doc reference
def validate(self) -> List[str]:
"""Validate idempotency assumptions"""
errors = []
if not self.is_idempotent and self.key_strategy == IdempotencyKeyStrategy.UNSUPPORTED:
errors.append(
f"Operation '{self.operation_type}' is non-idempotent but "
f"idempotency keys are unsupported. Retries could cause duplicates."
)
if self.key_strategy == IdempotencyKeyStrategy.REQUIRED:
if not self.key_location:
errors.append("Idempotency key location must be specified when required")
if self.key_ttl_seconds and self.key_ttl_seconds < 300:
errors.append(
f"Idempotency key TTL ({self.key_ttl_seconds}s) is too short. "
"Recommend at least 300s for network retries."
)
return errors
# ========== 2. BACKOFF RULES ==========
class BackoffType(Enum):
"""Backoff strategies"""
FIXED = "fixed"
LINEAR = "linear"
EXPONENTIAL = "exponential"
EXPONENTIAL_JITTER = "exponential_jitter"
CUSTOM = "custom"
@dataclass
class BackoffConfig:
"""Configuration for backoff strategy"""
type: BackoffType
initial_interval_ms: int
max_interval_ms: int
multiplier: float = 2.0
randomization_factor: float = 0.5 # For jitter: 0 = no jitter, 1 = full jitter
max_elapsed_time_ms: Optional[int] = None
def __post_init__(self):
"""Validate configuration on creation"""
if self.initial_interval_ms <= 0:
raise ValueError("initial_interval_ms must be positive")
if self.max_interval_ms < self.initial_interval_ms:
raise ValueError("max_interval_ms must be >= initial_interval_ms")
if self.type in [BackoffType.EXPONENTIAL, BackoffType.EXPONENTIAL_JITTER]:
if self.multiplier <= 1.0:
raise ValueError("Exponential multiplier must be > 1.0")
if self.randomization_factor < 0 or self.randomization_factor > 1:
raise ValueError("randomization_factor must be between 0 and 1")
@dataclass
class BackoffValidator:
"""Validates backoff configurations against best practices"""
config: BackoffConfig
def validate(self) -> List[str]:
"""Validate backoff configuration"""
errors = []
# Check for common anti-patterns
if self.config.type == BackoffType.FIXED and self.config.max_interval_ms > self.config.initial_interval_ms:
errors.append(
"Fixed backoff with max_interval > initial_interval doesn't make sense. "
"Use exponential instead."
)
# Check for too aggressive retries
if self.config.max_interval_ms < 1000:
errors.append(
f"max_interval_ms ({self.config.max_interval_ms}ms) is very low. "
"Could cause thundering herd problems."
)
# Check for unbounded growth
if self.config.type in [BackoffType.EXPONENTIAL, BackoffType.EXPONENTIAL_JITTER]:
# Calculate if we'll exceed reasonable limits
max_retries = 10
interval = self.config.initial_interval_ms
for i in range(max_retries):
interval = min(
interval * self.config.multiplier,
self.config.max_interval_ms
)
if interval > 3600000: # 1 hour
errors.append(
f"Exponential backoff could reach {interval/1000}s after 10 retries. "
"Consider capping max_interval_ms."
)
# Check jitter configuration
if self.config.type == BackoffType.EXPONENTIAL_JITTER:
if self.config.randomization_factor == 0:
errors.append(
"EXPONENTIAL_JITTER with randomization_factor=0 is just exponential. "
"Use BackoffType.EXPONENTIAL instead."
)
if self.config.randomization_factor > 0.5:
errors.append(
f"randomization_factor ({self.config.randomization_factor}) is high. "
"Could cause very long waits. Consider <= 0.5."
)
# Check max_elapsed_time consistency
if self.config.max_elapsed_time_ms:
# Rough estimate of total backoff time for 10 retries
estimated_total = self._estimate_total_backoff(10)
if estimated_total > self.config.max_elapsed_time_ms:
errors.append(
f"Estimated total backoff for 10 retries ({estimated_total}ms) "
f"exceeds max_elapsed_time_ms ({self.config.max_elapsed_time_ms}ms)."
)
return errors
def _estimate_total_backoff(self, retry_count: int) -> int:
"""Estimate total backoff time for given retry count"""
total = 0
interval = self.config.initial_interval_ms
for _ in range(min(retry_count, 100)): # Cap at 100 to avoid infinite loop
if self.config.type == BackoffType.FIXED:
wait = self.config.initial_interval_ms
elif self.config.type in [BackoffType.EXPONENTIAL, BackoffType.EXPONENTIAL_JITTER]:
wait = min(interval, self.config.max_interval_ms)
interval = interval * self.config.multiplier
else: # LINEAR
wait = interval
interval += self.config.initial_interval_ms
# Apply jitter if configured
if self.config.type == BackoffType.EXPONENTIAL_JITTER:
jitter_range = wait * self.config.randomization_factor
wait = wait - (jitter_range / 2) + (random.random() * jitter_range)
total += wait
if self.config.max_elapsed_time_ms and total > self.config.max_elapsed_time_ms:
break
return int(total)
# ========== 3. SIMULATION ENGINE ==========
@dataclass
class RetryScenario:
"""A scenario to simulate"""
name: str
failure_pattern: List[bool] # True = success, False = failure
# Could also be: Callable[[int], bool] for probabilistic failures
@dataclass
class SimulationResult:
"""Results from a simulation"""
scenario_name: str
total_attempts: int
total_time_ms: float
final_status: str # "success", "exhausted", "canceled"
schedule: List[Dict[str, Any]] # Each retry's details
warnings: List[str] = field(default_factory=list)
def to_dict(self) -> Dict[str, Any]:
return {
"scenario": self.scenario_name,
"total_attempts": self.total_attempts,
"total_time_ms": self.total_time_ms,
"final_status": self.final_status,
"schedule": self.schedule,
"warnings": self.warnings
}
class Simulator:
"""Simulates retry behavior under different scenarios"""
def __init__(
self,
max_retries: int,
backoff_config: BackoffConfig,
request_timeout_ms: int = 1000,
per_request_duration_ms: int = 100
):
self.max_retries = max_retries
self.backoff_config = backoff_config
self.request_timeout_ms = request_timeout_ms
self.per_request_duration_ms = per_request_duration_ms
def simulate_scenario(
self,
scenario: RetryScenario,
stop_on_success: bool = True
) -> SimulationResult:
"""Run a single simulation scenario"""
schedule = []
total_time = 0
attempt = 1
warnings = []
while attempt <= self.max_retries + 1:
# Determine if this attempt succeeds
if attempt - 1 < len(scenario.failure_pattern):
success = scenario.failure_pattern[attempt - 1]
else:
# Default to failure if pattern exhausted
success = False
# Record attempt
attempt_record = {
"attempt": attempt,
"success": success,
"timestamp_ms": total_time,
"duration_ms": self.per_request_duration_ms
}
if success:
total_time += self.per_request_duration_ms
schedule.append(attempt_record)
final_status = "success"
break
# Failed - calculate retry delay if we have retries left
if attempt < self.max_retries + 1:
retry_delay = self._calculate_backoff(attempt)
# Check if delay would exceed timeout
if total_time + retry_delay > self.request_timeout_ms:
warnings.append(
f"Retry {attempt} would exceed timeout. "
f"Current: {total_time}ms + {retry_delay}ms > {self.request_timeout_ms}ms"
)
# In reality, we'd stop here
final_status = "timeout_exceeded"
break
total_time += retry_delay
attempt_record["retry_delay_ms"] = retry_delay
attempt_record["retry_after_ms"] = total_time
schedule.append(attempt_record)
attempt += 1
else:
# Exhausted all retries
final_status = "exhausted"
# Add final request time if we broke on success
if final_status == "success" and schedule:
schedule[-1]["total_request_time_ms"] = total_time
return SimulationResult(
scenario_name=scenario.name,
total_attempts=attempt - 1,
total_time_ms=total_time,
final_status=final_status,
schedule=schedule,
warnings=warnings
)
def _calculate_backoff(self, retry_index: int) -> float:
"""Calculate backoff for given retry index (1-based)"""
base = self._calculate_base_backoff(retry_index)
# Apply jitter if configured
if self.backoff_config.type == BackoffType.EXPONENTIAL_JITTER:
jitter_range = base * self.backoff_config.randomization_factor
return base - (jitter_range / 2) + (random.random() * jitter_range)
return base
def _calculate_base_backoff(self, retry_index: int) -> float:
"""Calculate base backoff without jitter"""
if self.backoff_config.type == BackoffType.FIXED:
return float(self.backoff_config.initial_interval_ms)
elif self.backoff_config.type in [BackoffType.EXPONENTIAL, BackoffType.EXPONENTIAL_JITTER]:
interval = self.backoff_config.initial_interval_ms * (
self.backoff_config.multiplier ** (retry_index - 1)
)
return min(interval, self.backoff_config.max_interval_ms)
elif self.backoff_config.type == BackoffType.LINEAR:
return self.backoff_config.initial_interval_ms * retry_index
else:
raise ValueError(f"Unsupported backoff type: {self.backoff_config.type}")
def compare_scenarios(
self,
scenarios: List[RetryScenario]
) -> Dict[str, List[SimulationResult]]:
"""Run multiple scenarios and compare results"""
results = {}
for scenario in scenarios:
result = self.simulate_scenario(scenario)
results[scenario.name] = result
return results
# ========== 4. MAIN VALIDATOR ==========
@dataclass
class RetryPolicy:
"""Complete retry policy configuration"""
max_retries: int
backoff: BackoffConfig
idempotency: Optional[IdempotencyProof] = None
retryable_errors: List[str] = field(default_factory=list) # HTTP status codes, exception types
non_retryable_errors: List[str] = field(default_factory=list)
per_retry_timeout_ms: Optional[int] = None
total_timeout_ms: Optional[int] = None
def __post_init__(self):
if self.max_retries < 0:
raise ValueError("max_retries must be non-negative")
if self.max_retries > 100:
raise ValueError("max_retries seems excessive (>100)")
class RetryPolicyValidator:
"""Main validator that combines all validation aspects"""
def __init__(self, policy: RetryPolicy):
self.policy = policy
self.backoff_validator = BackoffValidator(policy.backoff)
def validate_all(
self,
operation_context: Optional[Dict[str, Any]] = None
) -> Tuple[bool, List[str], Dict[str, Any]]:
"""
Run all validations
Args:
operation_context: Optional context about the operation (http_method, etc.)
Returns:
(is_valid, errors, metrics)
"""
all_errors = []
metrics = {}
# 1. Validate idempotency
if self.policy.idempotency:
idemp_errors = self.policy.idempotency.validate()
all_errors.extend(idemp_errors)
metrics["idempotency_safe"] = len(idemp_errors) == 0
elif operation_context:
# Infer from context if possible
http_method = operation_context.get("http_method", "").upper()
if http_method in ["POST", "PATCH"] and not operation_context.get("has_idempotency_key", False):
all_errors.append(
f"POST/PATCH without idempotency key detected. "
"Consider adding IdempotencyProof to policy."
)
# 2. Validate backoff rules
backoff_errors = self.backoff_validator.validate()
all_errors.extend(backoff_errors)
metrics["backoff_valid"] = len(backoff_errors) == 0
# 3. Check consistency between max_retries and backoff
total_estimated = self._estimate_max_elapsed_time()
if self.policy.total_timeout_ms and total_estimated > self.policy.total_timeout_ms:
all_errors.append(
f"Estimated max retry time ({total_estimated}ms) exceeds "
f"total_timeout_ms ({self.policy.total_timeout_ms}ms)"
)
metrics["timeout_consistent"] = False
else:
metrics["timeout_consistent"] = True
metrics["estimated_max_time_ms"] = total_estimated
return len(all_errors) == 0, all_errors, metrics
def _estimate_max_elapsed_time(self) -> int:
"""Estimate maximum time for all retries"""
simulator = Simulator(
max_retries=self.policy.max_retries,
backoff_config=self.policy.backoff,
request_timeout_ms=self.policy.per_retry_timeout_ms or 30000
)
# Worst-case scenario: all retries fail
worst_case = RetryScenario(
name="worst_case",
failure_pattern=[False] * (self.policy.max_retries + 1)
)
result = simulator.simulate_scenario(worst_case, stop_on_success=False)
return int(result.total_time_ms)
def simulate_and_validate(
self,
scenarios: List[RetryScenario],
acceptance_criteria: Optional[Dict[str, Any]] = None
) -> Dict[str, Any]:
"""
Run simulations and validate against acceptance criteria
Args:
scenarios: List of scenarios to simulate
acceptance_criteria: Dict with thresholds like:
- max_total_time_ms: Maximum acceptable total time
- min_success_rate: Minimum acceptable success rate
- max_retry_count: Maximum retries in any scenario
"""
simulator = Simulator(
max_retries=self.policy.max_retries,
backoff_config=self.policy.backoff,
request_timeout_ms=self.policy.total_timeout_ms or 300000
)
results = simulator.compare_scenarios(scenarios)
validation_summary = {
"overall_valid": True,
"violations": [],
"statistics": {
"scenarios_tested": len(scenarios),
"max_time_ms": max(r.total_time_ms for r in results.values()),
"min_success_rate": min(
1 if r.final_status == "success" else 0
for r in results.values()
)
}
}
# Check acceptance criteria
if acceptance_criteria:
for criteria_name, threshold in acceptance_criteria.items():
if criteria_name == "max_total_time_ms":
if validation_summary["statistics"]["max_time_ms"] > threshold:
validation_summary["overall_valid"] = False
validation_summary["violations"].append(
f"Max time {validation_summary['statistics']['max_time_ms']}ms "
f"exceeds {threshold}ms"
)
elif criteria_name == "min_success_rate":
success_rate = sum(
1 for r in results.values() if r.final_status == "success"
) / len(results)
if success_rate < threshold:
validation_summary["overall_valid"] = False
validation_summary["violations"].append(
f"Success rate {success_rate:.2%} below {threshold:.2%}"
)
# Add detailed results
validation_summary["detailed_results"] = {
name: result.to_dict() for name, result in results.items()
}
return validation_summary
def generate_report(self, format: str = "json") -> str:
"""Generate validation report in specified format"""
is_valid, errors, metrics = self.validate_all()
report = {
"policy": {
"max_retries": self.policy.max_retries,
"backoff_type": self.policy.backoff.type.value,
"initial_interval_ms": self.policy.backoff.initial_interval_ms,
"max_interval_ms": self.policy.backoff.max_interval_ms
},
"validation": {
"is_valid": is_valid,
"error_count": len(errors),
"errors": errors
},
"metrics": metrics,
"timestamp": datetime.utcnow().isoformat()
}
if format == "json":
return json.dumps(report, indent=2)
elif format == "text":
return self._format_text_report(report)
else:
raise ValueError(f"Unsupported format: {format}")
def _format_text_report(self, report: Dict) -> str:
lines = [
"=" * 60,
"RETRY POLICY VALIDATION REPORT",
"=" * 60,
f"Policy: {report['policy']['backoff_type']} backoff, "
f"max_retries={report['policy']['max_retries']}",
f"Initial: {report['policy']['initial_interval_ms']}ms, "
f"Max: {report['policy']['max_interval_ms']}ms",
"-" * 60,
f"VALIDATION: {'PASS' if report['validation']['is_valid'] else 'FAIL'}",
f"Errors: {report['validation']['error_count']}",
]
for error in report['validation']['errors']:
lines.append(f" • {error}")
lines.extend([
"-" * 60,
"METRICS:",
f" Idempotency safe: {report['metrics'].get('idempotency_safe', 'N/A')}",
f" Backoff valid: {report['metrics'].get('backoff_valid', 'N/A')}",
f" Timeout consistent: {report['metrics'].get('timeout_consistent', 'N/A')}",
f" Est. max time: {report['metrics'].get('estimated_max_time_ms', 0)}ms",
"=" * 60
])
return "\n".join(lines)
Usage Example
# Example: Validate a retry policy for a payment API
from decimal import Decimal
# Define the policy
payment_retry_policy = RetryPolicy(
max_retries=3,
backoff=BackoffConfig(
type=BackoffType.EXPONENTIAL_JITTER,
initial_interval_ms=1000,
max_interval_ms=30000,
multiplier=2.0,
randomization_factor=0.5
),
idempotency=IdempotencyProof(
operation_type="POST /payments",
is_idempotent=False,
key_strategy=IdempotencyKeyStrategy.REQUIRED,
key_location="Idempotency-Key header",
key_ttl_seconds=86400, # 24 hours
evidence="https://docs.example.com/idempotency"
),
retryable_errors=["500", "502", "503", "504", "TIMEOUT"],
total_timeout_ms=60000 # 60 seconds total
)
# Create validator
validator = RetryPolicyValidator(payment_retry_policy)
# 1. Validate configuration
is_valid, errors, metrics = validator.validate_all({
"http_method": "POST",
"has_idempotency_key": True
})
print("Configuration valid:", is_valid)
if errors:
for error in errors:
print(" Error:", error)
# 2. Run simulations
scenarios = [
RetryScenario(
name="transient_errors",
failure_pattern=[False, False, True] # Fail twice, then succeed
),
RetryScenario(
name="persistent_failure",
failure_pattern=[False] * 4 # Always fail
),
RetryScenario(
name="immediate_success",
failure_pattern=[True] # Succeed immediately
)
]
sim_validation = validator.simulate_and_validate(
scenarios,
acceptance_criteria={
"max_total_time_ms": 45000, # 45 seconds max
"min_success_rate": 0.8 # 80% success rate required
}
)
print("\nSimulation Results:")
print(f"Overall valid: {sim_validation['overall_valid']}")
print(f"Max time: {sim_validation['statistics']['max_time_ms']}ms")
# 3. Generate report
print("\n" + validator.generate_report("text"))
Key Features & Design Decisions
1. Idempotency Proofs
- Explicit Declaration: Forces teams to document idempotency strategy
- Key Strategies: Supports various idempotency key patterns
- TTL Validation: Prevents too-short TTLs that could cause duplicate charges
- Evidence Requirement: Links to documentation/design docs
2. Backoff Validation
- Anti-pattern Detection: Catches fixed backoff with variable max, excessive jitter
- Growth Limits: Prevents unbounded exponential growth
- Timeout Consistency: Ensures backoff fits within overall timeout
- Jitter Best Practices: Validates jitter parameters (0.5 is usually optimal)
3. Simulation Engine
- Deterministic Scenarios: Test specific failure patterns
- Realistic Timing: Includes request duration and timeout constraints
- Warning System: Flags scenarios that would exceed timeouts
- Comparative Analysis: Run multiple scenarios and compare
4. Safety Mechanisms
- Hard Limits: Caps on max retries (100), max interval (1 hour default)
- Type Safety: Enums for backoff types, idempotency strategies
- Validation Chain: Configuration → Time estimates → Simulation → Acceptance
Advanced Features (Optional Extensions)
class AdaptiveRetryPolicy(RetryPolicy):
"""Policy that adapts based on recent failure rates"""
failure_rate_threshold: float = 0.5 # Reduce retries if >50% fail
min_retries: int = 1
def should_retry(self, recent_failure_rate: float) -> int:
"""Dynamically adjust retries based on recent performance"""
if recent_failure_rate > self.failure_rate_threshold:
return max(self.min_retries, self.max_retries // 2)
return self.max_retries
class CircuitBreakerIntegration:
"""Integrate with circuit breaker patterns"""
@staticmethod
def validate_combination(
retry_policy: RetryPolicy,
circuit_breaker_config: Dict[str, Any]
) -> List[str]:
"""Ensure retry + circuit breaker work together"""
errors = []
# If circuit opens, retries shouldn't happen
if circuit_breaker_config.get("enabled", False):
if retry_policy.max_retries > 0:
errors.append(
"Circuit breaker enabled with retries > 0. "
"Consider setting max_retries=0 or using retries within circuit half-open."
)
return errors
Validation Checklist
When validating a retry policy, check:
Idempotency
Backoff
Timeouts
Simulation
Integration Points
This validator could integrate with:
- CI/CD Pipeline: Fail builds if retry policy violates standards
- API Gateway: Validate upstream service retry configurations
- Observability: Export metrics about actual vs. simulated behavior
- Policy as Code: Store policies in git, validate on PR
- Chaos Engineering: Compare simulated vs. actual failure responses
This design provides both preventive validation (catching bad configs before deployment) and predictive simulation (understanding behavior under failure). The modular design allows teams to adopt parts incrementally while maintaining safety guarantees.