| Abhay Kumar | 40252eb | 2025-10-13 13:25:53 +0000 | [diff] [blame] | 1 | package backoff |
| 2 | |
| 3 | import ( |
| 4 | "math/rand" |
| 5 | "time" |
| 6 | ) |
| 7 | |
| 8 | /* |
| 9 | ExponentialBackOff is a backoff implementation that increases the backoff |
| 10 | period for each retry attempt using a randomization function that grows exponentially. |
| 11 | |
| 12 | NextBackOff() is calculated using the following formula: |
| 13 | |
| 14 | randomized interval = |
| 15 | RetryInterval * (random value in range [1 - RandomizationFactor, 1 + RandomizationFactor]) |
| 16 | |
| 17 | In other words NextBackOff() will range between the randomization factor |
| 18 | percentage below and above the retry interval. |
| 19 | |
| 20 | For example, given the following parameters: |
| 21 | |
| 22 | RetryInterval = 2 |
| 23 | RandomizationFactor = 0.5 |
| 24 | Multiplier = 2 |
| 25 | |
| 26 | the actual backoff period used in the next retry attempt will range between 1 and 3 seconds, |
| 27 | multiplied by the exponential, that is, between 2 and 6 seconds. |
| 28 | |
| 29 | Note: MaxInterval caps the RetryInterval and not the randomized interval. |
| 30 | |
| 31 | If the time elapsed since an ExponentialBackOff instance is created goes past the |
| 32 | MaxElapsedTime, then the method NextBackOff() starts returning backoff.Stop. |
| 33 | |
| 34 | The elapsed time can be reset by calling Reset(). |
| 35 | |
| 36 | Example: Given the following default arguments, for 10 tries the sequence will be, |
| 37 | and assuming we go over the MaxElapsedTime on the 10th try: |
| 38 | |
| 39 | Request # RetryInterval (seconds) Randomized Interval (seconds) |
| 40 | |
| 41 | 1 0.5 [0.25, 0.75] |
| 42 | 2 0.75 [0.375, 1.125] |
| 43 | 3 1.125 [0.562, 1.687] |
| 44 | 4 1.687 [0.8435, 2.53] |
| 45 | 5 2.53 [1.265, 3.795] |
| 46 | 6 3.795 [1.897, 5.692] |
| 47 | 7 5.692 [2.846, 8.538] |
| 48 | 8 8.538 [4.269, 12.807] |
| 49 | 9 12.807 [6.403, 19.210] |
| 50 | 10 19.210 backoff.Stop |
| 51 | |
| 52 | Note: Implementation is not thread-safe. |
| 53 | */ |
| 54 | type ExponentialBackOff struct { |
| 55 | InitialInterval time.Duration |
| 56 | RandomizationFactor float64 |
| 57 | Multiplier float64 |
| 58 | MaxInterval time.Duration |
| 59 | // After MaxElapsedTime the ExponentialBackOff returns Stop. |
| 60 | // It never stops if MaxElapsedTime == 0. |
| 61 | MaxElapsedTime time.Duration |
| 62 | Stop time.Duration |
| 63 | Clock Clock |
| 64 | |
| 65 | currentInterval time.Duration |
| 66 | startTime time.Time |
| 67 | } |
| 68 | |
| 69 | // Clock is an interface that returns current time for BackOff. |
| 70 | type Clock interface { |
| 71 | Now() time.Time |
| 72 | } |
| 73 | |
| 74 | // ExponentialBackOffOpts is a function type used to configure ExponentialBackOff options. |
| 75 | type ExponentialBackOffOpts func(*ExponentialBackOff) |
| 76 | |
| 77 | // Default values for ExponentialBackOff. |
| 78 | const ( |
| 79 | DefaultInitialInterval = 500 * time.Millisecond |
| 80 | DefaultRandomizationFactor = 0.5 |
| 81 | DefaultMultiplier = 1.5 |
| 82 | DefaultMaxInterval = 60 * time.Second |
| 83 | DefaultMaxElapsedTime = 15 * time.Minute |
| 84 | ) |
| 85 | |
| 86 | // NewExponentialBackOff creates an instance of ExponentialBackOff using default values. |
| 87 | func NewExponentialBackOff(opts ...ExponentialBackOffOpts) *ExponentialBackOff { |
| 88 | b := &ExponentialBackOff{ |
| 89 | InitialInterval: DefaultInitialInterval, |
| 90 | RandomizationFactor: DefaultRandomizationFactor, |
| 91 | Multiplier: DefaultMultiplier, |
| 92 | MaxInterval: DefaultMaxInterval, |
| 93 | MaxElapsedTime: DefaultMaxElapsedTime, |
| 94 | Stop: Stop, |
| 95 | Clock: SystemClock, |
| 96 | } |
| 97 | for _, fn := range opts { |
| 98 | fn(b) |
| 99 | } |
| 100 | b.Reset() |
| 101 | return b |
| 102 | } |
| 103 | |
| 104 | // WithInitialInterval sets the initial interval between retries. |
| 105 | func WithInitialInterval(duration time.Duration) ExponentialBackOffOpts { |
| 106 | return func(ebo *ExponentialBackOff) { |
| 107 | ebo.InitialInterval = duration |
| 108 | } |
| 109 | } |
| 110 | |
| 111 | // WithRandomizationFactor sets the randomization factor to add jitter to intervals. |
| 112 | func WithRandomizationFactor(randomizationFactor float64) ExponentialBackOffOpts { |
| 113 | return func(ebo *ExponentialBackOff) { |
| 114 | ebo.RandomizationFactor = randomizationFactor |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | // WithMultiplier sets the multiplier for increasing the interval after each retry. |
| 119 | func WithMultiplier(multiplier float64) ExponentialBackOffOpts { |
| 120 | return func(ebo *ExponentialBackOff) { |
| 121 | ebo.Multiplier = multiplier |
| 122 | } |
| 123 | } |
| 124 | |
| 125 | // WithMaxInterval sets the maximum interval between retries. |
| 126 | func WithMaxInterval(duration time.Duration) ExponentialBackOffOpts { |
| 127 | return func(ebo *ExponentialBackOff) { |
| 128 | ebo.MaxInterval = duration |
| 129 | } |
| 130 | } |
| 131 | |
| 132 | // WithMaxElapsedTime sets the maximum total time for retries. |
| 133 | func WithMaxElapsedTime(duration time.Duration) ExponentialBackOffOpts { |
| 134 | return func(ebo *ExponentialBackOff) { |
| 135 | ebo.MaxElapsedTime = duration |
| 136 | } |
| 137 | } |
| 138 | |
| 139 | // WithRetryStopDuration sets the duration after which retries should stop. |
| 140 | func WithRetryStopDuration(duration time.Duration) ExponentialBackOffOpts { |
| 141 | return func(ebo *ExponentialBackOff) { |
| 142 | ebo.Stop = duration |
| 143 | } |
| 144 | } |
| 145 | |
| 146 | // WithClockProvider sets the clock used to measure time. |
| 147 | func WithClockProvider(clock Clock) ExponentialBackOffOpts { |
| 148 | return func(ebo *ExponentialBackOff) { |
| 149 | ebo.Clock = clock |
| 150 | } |
| 151 | } |
| 152 | |
| 153 | type systemClock struct{} |
| 154 | |
| 155 | func (t systemClock) Now() time.Time { |
| 156 | return time.Now() |
| 157 | } |
| 158 | |
| 159 | // SystemClock implements Clock interface that uses time.Now(). |
| 160 | var SystemClock = systemClock{} |
| 161 | |
| 162 | // Reset the interval back to the initial retry interval and restarts the timer. |
| 163 | // Reset must be called before using b. |
| 164 | func (b *ExponentialBackOff) Reset() { |
| 165 | b.currentInterval = b.InitialInterval |
| 166 | b.startTime = b.Clock.Now() |
| 167 | } |
| 168 | |
| 169 | // NextBackOff calculates the next backoff interval using the formula: |
| 170 | // Randomized interval = RetryInterval * (1 ± RandomizationFactor) |
| 171 | func (b *ExponentialBackOff) NextBackOff() time.Duration { |
| 172 | // Make sure we have not gone over the maximum elapsed time. |
| 173 | elapsed := b.GetElapsedTime() |
| 174 | next := getRandomValueFromInterval(b.RandomizationFactor, rand.Float64(), b.currentInterval) |
| 175 | b.incrementCurrentInterval() |
| 176 | if b.MaxElapsedTime != 0 && elapsed+next > b.MaxElapsedTime { |
| 177 | return b.Stop |
| 178 | } |
| 179 | return next |
| 180 | } |
| 181 | |
| 182 | // GetElapsedTime returns the elapsed time since an ExponentialBackOff instance |
| 183 | // is created and is reset when Reset() is called. |
| 184 | // |
| 185 | // The elapsed time is computed using time.Now().UnixNano(). It is |
| 186 | // safe to call even while the backoff policy is used by a running |
| 187 | // ticker. |
| 188 | func (b *ExponentialBackOff) GetElapsedTime() time.Duration { |
| 189 | return b.Clock.Now().Sub(b.startTime) |
| 190 | } |
| 191 | |
| 192 | // Increments the current interval by multiplying it with the multiplier. |
| 193 | func (b *ExponentialBackOff) incrementCurrentInterval() { |
| 194 | // Check for overflow, if overflow is detected set the current interval to the max interval. |
| 195 | if float64(b.currentInterval) >= float64(b.MaxInterval)/b.Multiplier { |
| 196 | b.currentInterval = b.MaxInterval |
| 197 | } else { |
| 198 | b.currentInterval = time.Duration(float64(b.currentInterval) * b.Multiplier) |
| 199 | } |
| 200 | } |
| 201 | |
| 202 | // Returns a random value from the following interval: |
| 203 | // [currentInterval - randomizationFactor * currentInterval, currentInterval + randomizationFactor * currentInterval]. |
| 204 | func getRandomValueFromInterval(randomizationFactor, random float64, currentInterval time.Duration) time.Duration { |
| 205 | if randomizationFactor == 0 { |
| 206 | return currentInterval // make sure no randomness is used when randomizationFactor is 0. |
| 207 | } |
| 208 | var delta = randomizationFactor * float64(currentInterval) |
| 209 | var minInterval = float64(currentInterval) - delta |
| 210 | var maxInterval = float64(currentInterval) + delta |
| 211 | |
| 212 | // Get a random value from the range [minInterval, maxInterval]. |
| 213 | // The formula used below has a +1 because if the minInterval is 1 and the maxInterval is 3 then |
| 214 | // we want a 33% chance for selecting either 1, 2 or 3. |
| 215 | return time.Duration(minInterval + (random * (maxInterval - minInterval + 1))) |
| 216 | } |