backoff.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package grpc
  2. import (
  3. "math/rand"
  4. "time"
  5. )
  6. // DefaultBackoffConfig uses values specified for backoff in
  7. // https://github.com/grpc/grpc/blob/master/doc/connection-backoff.md.
  8. var (
  9. DefaultBackoffConfig = &BackoffConfig{
  10. MaxDelay: 120 * time.Second,
  11. baseDelay: 1.0 * time.Second,
  12. factor: 1.6,
  13. jitter: 0.2,
  14. }
  15. )
  16. // backoffStrategy defines the methodology for backing off after a grpc
  17. // connection failure.
  18. //
  19. // This is unexported until the GRPC project decides whether or not to allow
  20. // alternative backoff strategies. Once a decision is made, this type and its
  21. // method may be exported.
  22. type backoffStrategy interface {
  23. // backoff returns the amount of time to wait before the next retry given
  24. // the number of consecutive failures.
  25. backoff(retries int) time.Duration
  26. }
  27. // BackoffConfig defines the parameters for the default GRPC backoff strategy.
  28. type BackoffConfig struct {
  29. // MaxDelay is the upper bound of backoff delay.
  30. MaxDelay time.Duration
  31. // TODO(stevvooe): The following fields are not exported, as allowing changes
  32. // baseDelay is the amount of time to wait before retrying after the first
  33. // failure.
  34. baseDelay time.Duration
  35. // factor is applied to the backoff after each retry.
  36. factor float64
  37. // jitter provides a range to randomize backoff delays.
  38. jitter float64
  39. }
  40. func (bc *BackoffConfig) backoff(retries int) (t time.Duration) {
  41. if retries == 0 {
  42. return bc.baseDelay
  43. }
  44. backoff, max := float64(bc.baseDelay), float64(bc.MaxDelay)
  45. for backoff < max && retries > 0 {
  46. backoff *= bc.factor
  47. retries--
  48. }
  49. if backoff > max {
  50. backoff = max
  51. }
  52. // Randomize backoff delays so that if a cluster of requests start at
  53. // the same time, they won't operate in lockstep.
  54. backoff *= 1 + bc.jitter*(rand.Float64()*2-1)
  55. if backoff < 0 {
  56. return 0
  57. }
  58. return time.Duration(backoff)
  59. }