backoff.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. grpcbackoff "google.golang.org/grpc/backoff"
  26. "google.golang.org/grpc/internal/grpcrand"
  27. )
  28. // Strategy defines the methodology for backing off after a grpc connection
  29. // failure.
  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. // DefaultExponential is an exponential backoff implementation using the
  36. // default values for all the configurable knobs defined in
  37. // https://github.com/grpc/grpc/blob/master/doc/connection-backoff.md.
  38. var DefaultExponential = Exponential{Config: grpcbackoff.DefaultConfig}
  39. // Exponential implements exponential backoff algorithm as defined in
  40. // https://github.com/grpc/grpc/blob/master/doc/connection-backoff.md.
  41. type Exponential struct {
  42. // Config contains all options to configure the backoff algorithm.
  43. Config grpcbackoff.Config
  44. }
  45. // Backoff returns the amount of time to wait before the next retry given the
  46. // number of retries.
  47. func (bc Exponential) Backoff(retries int) time.Duration {
  48. if retries == 0 {
  49. return bc.Config.BaseDelay
  50. }
  51. backoff, max := float64(bc.Config.BaseDelay), float64(bc.Config.MaxDelay)
  52. for backoff < max && retries > 0 {
  53. backoff *= bc.Config.Multiplier
  54. retries--
  55. }
  56. if backoff > max {
  57. backoff = max
  58. }
  59. // Randomize backoff delays so that if a cluster of requests start at
  60. // the same time, they won't operate in lockstep.
  61. backoff *= 1 + bc.Config.Jitter*(grpcrand.Float64()*2-1)
  62. if backoff < 0 {
  63. return 0
  64. }
  65. return time.Duration(backoff)
  66. }