rate_limiter.go 3.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // Copyright (c) 2016 Uber Technologies, Inc.
  2. //
  3. // Permission is hereby granted, free of charge, to any person obtaining a copy
  4. // of this software and associated documentation files (the "Software"), to deal
  5. // in the Software without restriction, including without limitation the rights
  6. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. // copies of the Software, and to permit persons to whom the Software is
  8. // furnished to do so, subject to the following conditions:
  9. //
  10. // The above copyright notice and this permission notice shall be included in
  11. // all copies or substantial portions of the Software.
  12. //
  13. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. // THE SOFTWARE.
  20. package utils
  21. import (
  22. "sync"
  23. "time"
  24. )
  25. // RateLimiter is a filter used to check if a message that is worth itemCost units is within the rate limits.
  26. type RateLimiter interface {
  27. CheckCredit(itemCost float64) bool
  28. }
  29. type rateLimiter struct {
  30. sync.Mutex
  31. creditsPerSecond float64
  32. balance float64
  33. maxBalance float64
  34. lastTick time.Time
  35. timeNow func() time.Time
  36. }
  37. // NewRateLimiter creates a new rate limiter based on leaky bucket algorithm, formulated in terms of a
  38. // credits balance that is replenished every time CheckCredit() method is called (tick) by the amount proportional
  39. // to the time elapsed since the last tick, up to max of creditsPerSecond. A call to CheckCredit() takes a cost
  40. // of an item we want to pay with the balance. If the balance exceeds the cost of the item, the item is "purchased"
  41. // and the balance reduced, indicated by returned value of true. Otherwise the balance is unchanged and return false.
  42. //
  43. // This can be used to limit a rate of messages emitted by a service by instantiating the Rate Limiter with the
  44. // max number of messages a service is allowed to emit per second, and calling CheckCredit(1.0) for each message
  45. // to determine if the message is within the rate limit.
  46. //
  47. // It can also be used to limit the rate of traffic in bytes, by setting creditsPerSecond to desired throughput
  48. // as bytes/second, and calling CheckCredit() with the actual message size.
  49. func NewRateLimiter(creditsPerSecond, maxBalance float64) RateLimiter {
  50. return &rateLimiter{
  51. creditsPerSecond: creditsPerSecond,
  52. balance: maxBalance,
  53. maxBalance: maxBalance,
  54. lastTick: time.Now(),
  55. timeNow: time.Now}
  56. }
  57. func (b *rateLimiter) CheckCredit(itemCost float64) bool {
  58. b.Lock()
  59. defer b.Unlock()
  60. // calculate how much time passed since the last tick, and update current tick
  61. currentTime := b.timeNow()
  62. elapsedTime := currentTime.Sub(b.lastTick)
  63. b.lastTick = currentTime
  64. // calculate how much credit have we accumulated since the last tick
  65. b.balance += elapsedTime.Seconds() * b.creditsPerSecond
  66. if b.balance > b.maxBalance {
  67. b.balance = b.maxBalance
  68. }
  69. // if we have enough credits to pay for current item, then reduce balance and allow
  70. if b.balance >= itemCost {
  71. b.balance -= itemCost
  72. return true
  73. }
  74. return false
  75. }