-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathbackoff.go
More file actions
58 lines (48 loc) · 1.6 KB
/
Copy pathbackoff.go
File metadata and controls
58 lines (48 loc) · 1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// Copyright (c) 2026 Onur Cinar.
// The source code is provided under MIT License.
// https://github.com/cinar/resile
package resile
import (
"math"
"math/rand/v2"
"time"
)
// Backoff defines the interface for temporal distribution of retries.
type Backoff interface {
// Next calculates the duration to wait before the specified attempt.
// The attempt parameter is 0-indexed.
Next(attempt uint) time.Duration
}
// fullJitter implements the AWS "Full Jitter" algorithm.
// See: https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/
type fullJitter struct {
base time.Duration
cap time.Duration
}
// NewFullJitter returns a Backoff implementation using the AWS Full Jitter algorithm.
// The base duration dictates the initial delay, and the cap defines the absolute maximum.
func NewFullJitter(base, cap time.Duration) Backoff {
return &fullJitter{
base: base,
cap: cap,
}
}
// Next calculates the next sleep duration.
// Formula: delay = random(0, min(cap, base * 2^attempt))
func (f *fullJitter) Next(attempt uint) time.Duration {
// Calculate the exponential maximum for this attempt.
// We use float64 to prevent overflow during the power operation.
exp := math.Pow(2, float64(attempt))
maxDelay := float64(f.base) * exp
// Ensure the calculated maximum does not exceed the cap.
if maxDelay > float64(f.cap) {
maxDelay = float64(f.cap)
}
if maxDelay <= 0 {
return 0
}
// Generate a random duration between 0 and the calculated maximum.
// math/rand/v2 Int64N is used for better distribution.
randomDelay := rand.Int64N(int64(maxDelay))
return time.Duration(randomDelay)
}