rate_limiter.go 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. // Copyright (c) 2017 Uber Technologies, Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package utils
  15. import (
  16. "sync"
  17. "time"
  18. )
  19. // RateLimiter is a filter used to check if a message that is worth itemCost units is within the rate limits.
  20. //
  21. // TODO (breaking change) remove this interface in favor of public struct below
  22. //
  23. // Deprecated, use ReconfigurableRateLimiter.
  24. type RateLimiter interface {
  25. CheckCredit(itemCost float64) bool
  26. }
  27. // ReconfigurableRateLimiter is a rate limiter based on leaky bucket algorithm, formulated in terms of a
  28. // credits balance that is replenished every time CheckCredit() method is called (tick) by the amount proportional
  29. // to the time elapsed since the last tick, up to max of creditsPerSecond. A call to CheckCredit() takes a cost
  30. // of an item we want to pay with the balance. If the balance exceeds the cost of the item, the item is "purchased"
  31. // and the balance reduced, indicated by returned value of true. Otherwise the balance is unchanged and return false.
  32. //
  33. // This can be used to limit a rate of messages emitted by a service by instantiating the Rate Limiter with the
  34. // max number of messages a service is allowed to emit per second, and calling CheckCredit(1.0) for each message
  35. // to determine if the message is within the rate limit.
  36. //
  37. // It can also be used to limit the rate of traffic in bytes, by setting creditsPerSecond to desired throughput
  38. // as bytes/second, and calling CheckCredit() with the actual message size.
  39. //
  40. // TODO (breaking change) rename to RateLimiter once the interface is removed
  41. type ReconfigurableRateLimiter struct {
  42. lock sync.Mutex
  43. creditsPerSecond float64
  44. balance float64
  45. maxBalance float64
  46. lastTick time.Time
  47. timeNow func() time.Time
  48. }
  49. // NewRateLimiter creates a new ReconfigurableRateLimiter.
  50. func NewRateLimiter(creditsPerSecond, maxBalance float64) *ReconfigurableRateLimiter {
  51. return &ReconfigurableRateLimiter{
  52. creditsPerSecond: creditsPerSecond,
  53. balance: maxBalance,
  54. maxBalance: maxBalance,
  55. lastTick: time.Now(),
  56. timeNow: time.Now,
  57. }
  58. }
  59. // CheckCredit tries to reduce the current balance by itemCost provided that the current balance
  60. // is not lest than itemCost.
  61. func (rl *ReconfigurableRateLimiter) CheckCredit(itemCost float64) bool {
  62. rl.lock.Lock()
  63. defer rl.lock.Unlock()
  64. // if we have enough credits to pay for current item, then reduce balance and allow
  65. if rl.balance >= itemCost {
  66. rl.balance -= itemCost
  67. return true
  68. }
  69. // otherwise check if balance can be increased due to time elapsed, and try again
  70. rl.updateBalance()
  71. if rl.balance >= itemCost {
  72. rl.balance -= itemCost
  73. return true
  74. }
  75. return false
  76. }
  77. // updateBalance recalculates current balance based on time elapsed. Must be called while holding a lock.
  78. func (rl *ReconfigurableRateLimiter) updateBalance() {
  79. // calculate how much time passed since the last tick, and update current tick
  80. currentTime := rl.timeNow()
  81. elapsedTime := currentTime.Sub(rl.lastTick)
  82. rl.lastTick = currentTime
  83. // calculate how much credit have we accumulated since the last tick
  84. rl.balance += elapsedTime.Seconds() * rl.creditsPerSecond
  85. if rl.balance > rl.maxBalance {
  86. rl.balance = rl.maxBalance
  87. }
  88. }
  89. // Update changes the main parameters of the rate limiter in-place, while retaining
  90. // the current accumulated balance (pro-rated to the new maxBalance value). Using this method
  91. // instead of creating a new rate limiter helps to avoid thundering herd when sampling
  92. // strategies are updated.
  93. func (rl *ReconfigurableRateLimiter) Update(creditsPerSecond, maxBalance float64) {
  94. rl.lock.Lock()
  95. defer rl.lock.Unlock()
  96. rl.updateBalance() // get up to date balance
  97. rl.balance = rl.balance * maxBalance / rl.maxBalance
  98. rl.creditsPerSecond = creditsPerSecond
  99. rl.maxBalance = maxBalance
  100. }