backoff.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /*
  2. *
  3. * Copyright 2017 gRPC authors.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. // Package backoff implement the backoff strategy for gRPC.
  19. //
  20. // This is kept in internal until the gRPC project decides whether or not to
  21. // allow alternative backoff strategies.
  22. package backoff
  23. import (
  24. "time"
  25. "google.golang.org/grpc/internal/grpcrand"
  26. )
  27. // Strategy defines the methodology for backing off after a grpc connection
  28. // failure.
  29. //
  30. type Strategy interface {
  31. // Backoff returns the amount of time to wait before the next retry given
  32. // the number of consecutive failures.
  33. Backoff(retries int) time.Duration
  34. }
  35. const (
  36. // baseDelay is the amount of time to wait before retrying after the first
  37. // failure.
  38. baseDelay = 1.0 * time.Second
  39. // factor is applied to the backoff after each retry.
  40. factor = 1.6
  41. // jitter provides a range to randomize backoff delays.
  42. jitter = 0.2
  43. )
  44. // Exponential implements exponential backoff algorithm as defined in
  45. // https://github.com/grpc/grpc/blob/master/doc/connection-backoff.md.
  46. type Exponential struct {
  47. // MaxDelay is the upper bound of backoff delay.
  48. MaxDelay time.Duration
  49. }
  50. // Backoff returns the amount of time to wait before the next retry given the
  51. // number of retries.
  52. func (bc Exponential) Backoff(retries int) time.Duration {
  53. if retries == 0 {
  54. return baseDelay
  55. }
  56. backoff, max := float64(baseDelay), float64(bc.MaxDelay)
  57. for backoff < max && retries > 0 {
  58. backoff *= factor
  59. retries--
  60. }
  61. if backoff > max {
  62. backoff = max
  63. }
  64. // Randomize backoff delays so that if a cluster of requests start at
  65. // the same time, they won't operate in lockstep.
  66. backoff *= 1 + jitter*(grpcrand.Float64()*2-1)
  67. if backoff < 0 {
  68. return 0
  69. }
  70. return time.Duration(backoff)
  71. }