sparkling/retry

Retry logic with exponential backoff and jitter for resilient operations. Used by the repo layer to handle transient failures.

Note on time units: erlang:monotonic_time/0 and erlang:system_time/0 return native units. On OTP 18+ (Linux/macOS/Windows) native = nanoseconds. This is a safe assumption for OTP 27+ as used by this library.

Types

Configuration for retry behavior

pub type RetryConfig {
  RetryConfig(
    max_attempts: Int,
    base_delay_ms: Int,
    max_delay_ms: Int,
    jitter_factor: Float,
  )
}

Constructors

  • RetryConfig(
      max_attempts: Int,
      base_delay_ms: Int,
      max_delay_ms: Int,
      jitter_factor: Float,
    )

    Arguments

    max_attempts

    Maximum total number of attempts (first attempt + retries). E.g. max_attempts=3 → 1 initial try + up to 2 retries = 3 total.

    base_delay_ms

    Base delay in milliseconds for exponential backoff

    max_delay_ms

    Maximum delay between retries in milliseconds

    jitter_factor

    Jitter factor (0.0 = no jitter, 1.0 = full jitter)

Values

pub fn default_config() -> RetryConfig

Default retry configuration suitable for most operations

pub fn network_config() -> RetryConfig

Configuration optimized for network operations (longer delays)

pub fn with_retry(
  config: RetryConfig,
  operation: fn() -> Result(a, b),
  is_retryable_error: fn(b) -> Bool,
  on_retry: fn(Int, b) -> Nil,
) -> Result(a, b)

Execute an operation with retry logic. on_retry(attempt, error) is called before each retry, where attempt starts at 1. Returns the first successful result or the last error.

Search Document