Module: Philiprehberger::RetryKit::Backoff

Defined in:
lib/philiprehberger/retry_kit/backoff.rb

Overview

Backoff strategy calculators.

Class Method Summary collapse

Class Method Details

.constant(_attempt, delay: 1) ⇒ Numeric

Constant backoff: always the same delay.

Parameters:

  • _attempt (Integer)

    ignored

  • delay (Numeric) (defaults to: 1)

    the constant delay in seconds

Returns:

  • (Numeric)

    delay in seconds



36
37
38
# File 'lib/philiprehberger/retry_kit/backoff.rb', line 36

def constant(_attempt, delay: 1)
  delay
end

.decorrelated(last_delay, base_delay: 0.5, max_delay: 30) ⇒ Float

Compute decorrelated jitter delay (AWS-style).

Parameters:

  • last_delay (Numeric)

    the previous sleep duration

  • base_delay (Numeric) (defaults to: 0.5)

    the base delay in seconds

  • max_delay (Numeric) (defaults to: 30)

    the maximum delay cap in seconds

Returns:

  • (Float)

    decorrelated jitter delay



64
65
66
# File 'lib/philiprehberger/retry_kit/backoff.rb', line 64

def decorrelated(last_delay, base_delay: 0.5, max_delay: 30)
  [max_delay, rand(base_delay.to_f..(last_delay * 3).to_f)].min
end

.exponential(attempt, base_delay: 0.5, max_delay: 30) ⇒ Numeric

Exponential backoff: base_delay * 2^attempt

Parameters:

  • attempt (Integer)

    the current attempt number (0-based)

  • base_delay (Numeric) (defaults to: 0.5)

    the base delay in seconds

  • max_delay (Numeric) (defaults to: 30)

    the maximum delay cap in seconds

Returns:

  • (Numeric)

    delay in seconds



15
16
17
18
# File 'lib/philiprehberger/retry_kit/backoff.rb', line 15

def exponential(attempt, base_delay: 0.5, max_delay: 30)
  delay = base_delay * (2**attempt)
  [delay, max_delay].min
end

.jitter(delay, mode: :full) ⇒ Float

Add jitter to a delay value.

Parameters:

  • delay (Numeric)

    the base delay

  • mode (Symbol) (defaults to: :full)

    jitter mode — :full, :equal, or :none

Returns:

  • (Float)

    jittered delay



45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/philiprehberger/retry_kit/backoff.rb', line 45

def jitter(delay, mode: :full)
  case mode
  when :full
    rand * delay
  when :equal
    (delay / 2.0) + (rand * delay / 2.0)
  when :none
    delay.to_f
  else
    raise ArgumentError, "Unknown jitter mode: #{mode}. Use :full, :equal, or :none"
  end
end

.linear(attempt, base_delay: 0.5, max_delay: 30) ⇒ Numeric

Linear backoff: base_delay * (attempt + 1)

Parameters:

  • attempt (Integer)

    the current attempt number (0-based)

  • base_delay (Numeric) (defaults to: 0.5)

    the base delay in seconds

  • max_delay (Numeric) (defaults to: 30)

    the maximum delay cap in seconds

Returns:

  • (Numeric)

    delay in seconds



26
27
28
29
# File 'lib/philiprehberger/retry_kit/backoff.rb', line 26

def linear(attempt, base_delay: 0.5, max_delay: 30)
  delay = base_delay * (attempt + 1)
  [delay, max_delay].min
end