blob: ad35f09a87fec164ba06432d3b6367133d88441d [file] [log] [blame]
nikesh.krishnan6dd882b2023-03-14 10:02:41 +05301// Copyright 2016 Michal Witkowski. All Rights Reserved.
2// See LICENSE for licensing terms.
3
4package grpc_retry
5
6import (
7 "time"
8
9 "github.com/grpc-ecosystem/go-grpc-middleware/util/backoffutils"
10)
11
12// BackoffLinear is very simple: it waits for a fixed period of time between calls.
13func BackoffLinear(waitBetween time.Duration) BackoffFunc {
14 return func(attempt uint) time.Duration {
15 return waitBetween
16 }
17}
18
19// BackoffLinearWithJitter waits a set period of time, allowing for jitter (fractional adjustment).
20//
21// For example waitBetween=1s and jitter=0.10 can generate waits between 900ms and 1100ms.
22func BackoffLinearWithJitter(waitBetween time.Duration, jitterFraction float64) BackoffFunc {
23 return func(attempt uint) time.Duration {
24 return backoffutils.JitterUp(waitBetween, jitterFraction)
25 }
26}
27
28// BackoffExponential produces increasing intervals for each attempt.
29//
30// The scalar is multiplied times 2 raised to the current attempt. So the first
31// retry with a scalar of 100ms is 100ms, while the 5th attempt would be 1.6s.
32func BackoffExponential(scalar time.Duration) BackoffFunc {
33 return func(attempt uint) time.Duration {
34 return scalar * time.Duration(backoffutils.ExponentBase2(attempt))
35 }
36}
37
38// BackoffExponentialWithJitter creates an exponential backoff like
39// BackoffExponential does, but adds jitter.
40func BackoffExponentialWithJitter(scalar time.Duration, jitterFraction float64) BackoffFunc {
41 return func(attempt uint) time.Duration {
42 return backoffutils.JitterUp(scalar*time.Duration(backoffutils.ExponentBase2(attempt)), jitterFraction)
43 }
44}