Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions pkg/time/delay.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ package time

import (
"context"
"math/bits"
"math/rand"
"time"
)
Expand All @@ -39,8 +40,17 @@ func LinearDelay(ctx context.Context, attempt uint, increment, maxDelay time.Dur
// ExponentialDelayWithJitter is an exponential backoff strategy with jitter for retries. It calculates delay based on the attempt number,
// adds jitter, and sleeps for that duration, capped at maxDelay.
func ExponentialDelayWithJitter(ctx context.Context, attempt uint, baseDelay, maxDelay time.Duration) error {
delay := baseDelay * time.Duration(1<<attempt)
delay = min(delay, maxDelay)
// Compute baseDelay * 2^attempt, capped at maxDelay. The shift is only applied when it
// cannot overflow time.Duration; otherwise the result would exceed maxDelay anyway, so
// the cap is used directly. Without this guard a large attempt overflows int64 before the
// cap is applied, yielding a negative or zero delay that silently skips the backoff.
var delay time.Duration
if baseDelay > 0 {
delay = maxDelay
if attempt < uint(bits.LeadingZeros64(uint64(baseDelay))) {
delay = min(baseDelay<<attempt, maxDelay)
}
}

if delay > 0 {
jitter := time.Duration(rand.Int63n(int64(delay)))
Expand Down
24 changes: 24 additions & 0 deletions pkg/time/delay_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,30 @@ func TestExponentialDelayWithJitter(t *testing.T) {
expectedMin: 650 * time.Millisecond,
expectedMax: 3000 * time.Millisecond,
},
{
name: "overflow attempt stays capped at maxDelay",
attempt: 39,
baseDelay: 30 * time.Millisecond,
maxDelay: 1 * time.Second,
expectedMin: 380 * time.Millisecond,
expectedMax: 1500 * time.Millisecond,
},
{
name: "shift overflow attempt stays capped at maxDelay",
attempt: 62,
baseDelay: 30 * time.Millisecond,
maxDelay: 1 * time.Second,
expectedMin: 380 * time.Millisecond,
expectedMax: 1500 * time.Millisecond,
},
{
name: "huge attempt stays capped at maxDelay",
attempt: 100,
baseDelay: 30 * time.Millisecond,
maxDelay: 1 * time.Second,
expectedMin: 380 * time.Millisecond,
expectedMax: 1500 * time.Millisecond,
},
{
name: "zero baseDelay with jitter",
attempt: 5,
Expand Down
Loading