ratelimit.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. // Copyright 2014 Canonical Ltd.
  2. // Licensed under the LGPLv3 with static-linking exception.
  3. // See LICENCE file for details.
  4. // Package ratelimit provides an efficient token bucket implementation
  5. // that can be used to limit the rate of arbitrary things.
  6. // See http://en.wikipedia.org/wiki/Token_bucket.
  7. package ratelimit
  8. import (
  9. "math"
  10. "strconv"
  11. "sync"
  12. "time"
  13. )
  14. // The algorithm that this implementation uses does computational work
  15. // only when tokens are removed from the bucket, and that work completes
  16. // in short, bounded-constant time (Bucket.Wait benchmarks at 175ns on
  17. // my laptop).
  18. //
  19. // Time is measured in equal measured ticks, a given interval
  20. // (fillInterval) apart. On each tick a number of tokens (quantum) are
  21. // added to the bucket.
  22. //
  23. // When any of the methods are called the bucket updates the number of
  24. // tokens that are in the bucket, and it records the current tick
  25. // number too. Note that it doesn't record the current time - by
  26. // keeping things in units of whole ticks, it's easy to dish out tokens
  27. // at exactly the right intervals as measured from the start time.
  28. //
  29. // This allows us to calculate the number of tokens that will be
  30. // available at some time in the future with a few simple arithmetic
  31. // operations.
  32. //
  33. // The main reason for being able to transfer multiple tokens on each tick
  34. // is so that we can represent rates greater than 1e9 (the resolution of the Go
  35. // time package) tokens per second, but it's also useful because
  36. // it means we can easily represent situations like "a person gets
  37. // five tokens an hour, replenished on the hour".
  38. // Bucket represents a token bucket that fills at a predetermined rate.
  39. // Methods on Bucket may be called concurrently.
  40. type Bucket struct {
  41. clock Clock
  42. // startTime holds the moment when the bucket was
  43. // first created and ticks began.
  44. startTime time.Time
  45. // capacity holds the overall capacity of the bucket.
  46. capacity int64
  47. // quantum holds how many tokens are added on
  48. // each tick.
  49. quantum int64
  50. // fillInterval holds the interval between each tick.
  51. fillInterval time.Duration
  52. // mu guards the fields below it.
  53. mu sync.Mutex
  54. // availableTokens holds the number of available
  55. // tokens as of the associated latestTick.
  56. // It will be negative when there are consumers
  57. // waiting for tokens.
  58. availableTokens int64
  59. // latestTick holds the latest tick for which
  60. // we know the number of tokens in the bucket.
  61. latestTick int64
  62. }
  63. // NewBucket returns a new token bucket that fills at the
  64. // rate of one token every fillInterval, up to the given
  65. // maximum capacity. Both arguments must be
  66. // positive. The bucket is initially full.
  67. func NewBucket(fillInterval time.Duration, capacity int64) *Bucket {
  68. return NewBucketWithClock(fillInterval, capacity, nil)
  69. }
  70. // NewBucketWithClock is identical to NewBucket but injects a testable clock
  71. // interface.
  72. func NewBucketWithClock(fillInterval time.Duration, capacity int64, clock Clock) *Bucket {
  73. return NewBucketWithQuantumAndClock(fillInterval, capacity, 1, clock)
  74. }
  75. // rateMargin specifes the allowed variance of actual
  76. // rate from specified rate. 1% seems reasonable.
  77. const rateMargin = 0.01
  78. // NewBucketWithRate returns a token bucket that fills the bucket
  79. // at the rate of rate tokens per second up to the given
  80. // maximum capacity. Because of limited clock resolution,
  81. // at high rates, the actual rate may be up to 1% different from the
  82. // specified rate.
  83. func NewBucketWithRate(rate float64, capacity int64) *Bucket {
  84. return NewBucketWithRateAndClock(rate, capacity, nil)
  85. }
  86. // NewBucketWithRateAndClock is identical to NewBucketWithRate but injects a
  87. // testable clock interface.
  88. func NewBucketWithRateAndClock(rate float64, capacity int64, clock Clock) *Bucket {
  89. // Use the same bucket each time through the loop
  90. // to save allocations.
  91. tb := NewBucketWithQuantumAndClock(1, capacity, 1, clock)
  92. for quantum := int64(1); quantum < 1<<50; quantum = nextQuantum(quantum) {
  93. fillInterval := time.Duration(1e9 * float64(quantum) / rate)
  94. if fillInterval <= 0 {
  95. continue
  96. }
  97. tb.fillInterval = fillInterval
  98. tb.quantum = quantum
  99. if diff := math.Abs(tb.Rate() - rate); diff/rate <= rateMargin {
  100. return tb
  101. }
  102. }
  103. panic("cannot find suitable quantum for " + strconv.FormatFloat(rate, 'g', -1, 64))
  104. }
  105. // nextQuantum returns the next quantum to try after q.
  106. // We grow the quantum exponentially, but slowly, so we
  107. // get a good fit in the lower numbers.
  108. func nextQuantum(q int64) int64 {
  109. q1 := q * 11 / 10
  110. if q1 == q {
  111. q1++
  112. }
  113. return q1
  114. }
  115. // NewBucketWithQuantum is similar to NewBucket, but allows
  116. // the specification of the quantum size - quantum tokens
  117. // are added every fillInterval.
  118. func NewBucketWithQuantum(fillInterval time.Duration, capacity, quantum int64) *Bucket {
  119. return NewBucketWithQuantumAndClock(fillInterval, capacity, quantum, nil)
  120. }
  121. // NewBucketWithQuantumAndClock is like NewBucketWithQuantum, but
  122. // also has a clock argument that allows clients to fake the passing
  123. // of time. If clock is nil, the system clock will be used.
  124. func NewBucketWithQuantumAndClock(fillInterval time.Duration, capacity, quantum int64, clock Clock) *Bucket {
  125. if clock == nil {
  126. clock = realClock{}
  127. }
  128. if fillInterval <= 0 {
  129. panic("token bucket fill interval is not > 0")
  130. }
  131. if capacity <= 0 {
  132. panic("token bucket capacity is not > 0")
  133. }
  134. if quantum <= 0 {
  135. panic("token bucket quantum is not > 0")
  136. }
  137. return &Bucket{
  138. clock: clock,
  139. startTime: clock.Now(),
  140. latestTick: 0,
  141. fillInterval: fillInterval,
  142. capacity: capacity,
  143. quantum: quantum,
  144. availableTokens: capacity,
  145. }
  146. }
  147. // Wait takes count tokens from the bucket, waiting until they are
  148. // available.
  149. func (tb *Bucket) Wait(count int64) {
  150. if d := tb.Take(count); d > 0 {
  151. tb.clock.Sleep(d)
  152. }
  153. }
  154. // WaitMaxDuration is like Wait except that it will
  155. // only take tokens from the bucket if it needs to wait
  156. // for no greater than maxWait. It reports whether
  157. // any tokens have been removed from the bucket
  158. // If no tokens have been removed, it returns immediately.
  159. func (tb *Bucket) WaitMaxDuration(count int64, maxWait time.Duration) bool {
  160. d, ok := tb.TakeMaxDuration(count, maxWait)
  161. if d > 0 {
  162. tb.clock.Sleep(d)
  163. }
  164. return ok
  165. }
  166. const infinityDuration time.Duration = 0x7fffffffffffffff
  167. // Take takes count tokens from the bucket without blocking. It returns
  168. // the time that the caller should wait until the tokens are actually
  169. // available.
  170. //
  171. // Note that if the request is irrevocable - there is no way to return
  172. // tokens to the bucket once this method commits us to taking them.
  173. func (tb *Bucket) Take(count int64) time.Duration {
  174. tb.mu.Lock()
  175. defer tb.mu.Unlock()
  176. d, _ := tb.take(tb.clock.Now(), count, infinityDuration)
  177. return d
  178. }
  179. // TakeMaxDuration is like Take, except that
  180. // it will only take tokens from the bucket if the wait
  181. // time for the tokens is no greater than maxWait.
  182. //
  183. // If it would take longer than maxWait for the tokens
  184. // to become available, it does nothing and reports false,
  185. // otherwise it returns the time that the caller should
  186. // wait until the tokens are actually available, and reports
  187. // true.
  188. func (tb *Bucket) TakeMaxDuration(count int64, maxWait time.Duration) (time.Duration, bool) {
  189. tb.mu.Lock()
  190. defer tb.mu.Unlock()
  191. return tb.take(tb.clock.Now(), count, maxWait)
  192. }
  193. // TakeAvailable takes up to count immediately available tokens from the
  194. // bucket. It returns the number of tokens removed, or zero if there are
  195. // no available tokens. It does not block.
  196. func (tb *Bucket) TakeAvailable(count int64) int64 {
  197. tb.mu.Lock()
  198. defer tb.mu.Unlock()
  199. return tb.takeAvailable(tb.clock.Now(), count)
  200. }
  201. // takeAvailable is the internal version of TakeAvailable - it takes the
  202. // current time as an argument to enable easy testing.
  203. func (tb *Bucket) takeAvailable(now time.Time, count int64) int64 {
  204. if count <= 0 {
  205. return 0
  206. }
  207. tb.adjustavailableTokens(tb.currentTick(now))
  208. if tb.availableTokens <= 0 {
  209. return 0
  210. }
  211. if count > tb.availableTokens {
  212. count = tb.availableTokens
  213. }
  214. tb.availableTokens -= count
  215. return count
  216. }
  217. // Available returns the number of available tokens. It will be negative
  218. // when there are consumers waiting for tokens. Note that if this
  219. // returns greater than zero, it does not guarantee that calls that take
  220. // tokens from the buffer will succeed, as the number of available
  221. // tokens could have changed in the meantime. This method is intended
  222. // primarily for metrics reporting and debugging.
  223. func (tb *Bucket) Available() int64 {
  224. return tb.available(tb.clock.Now())
  225. }
  226. // available is the internal version of available - it takes the current time as
  227. // an argument to enable easy testing.
  228. func (tb *Bucket) available(now time.Time) int64 {
  229. tb.mu.Lock()
  230. defer tb.mu.Unlock()
  231. tb.adjustavailableTokens(tb.currentTick(now))
  232. return tb.availableTokens
  233. }
  234. // Capacity returns the capacity that the bucket was created with.
  235. func (tb *Bucket) Capacity() int64 {
  236. return tb.capacity
  237. }
  238. // Rate returns the fill rate of the bucket, in tokens per second.
  239. func (tb *Bucket) Rate() float64 {
  240. return 1e9 * float64(tb.quantum) / float64(tb.fillInterval)
  241. }
  242. // take is the internal version of Take - it takes the current time as
  243. // an argument to enable easy testing.
  244. func (tb *Bucket) take(now time.Time, count int64, maxWait time.Duration) (time.Duration, bool) {
  245. if count <= 0 {
  246. return 0, true
  247. }
  248. tick := tb.currentTick(now)
  249. tb.adjustavailableTokens(tick)
  250. avail := tb.availableTokens - count
  251. if avail >= 0 {
  252. tb.availableTokens = avail
  253. return 0, true
  254. }
  255. // Round up the missing tokens to the nearest multiple
  256. // of quantum - the tokens won't be available until
  257. // that tick.
  258. // endTick holds the tick when all the requested tokens will
  259. // become available.
  260. endTick := tick + (-avail+tb.quantum-1)/tb.quantum
  261. endTime := tb.startTime.Add(time.Duration(endTick) * tb.fillInterval)
  262. waitTime := endTime.Sub(now)
  263. if waitTime > maxWait {
  264. return 0, false
  265. }
  266. tb.availableTokens = avail
  267. return waitTime, true
  268. }
  269. // currentTick returns the current time tick, measured
  270. // from tb.startTime.
  271. func (tb *Bucket) currentTick(now time.Time) int64 {
  272. return int64(now.Sub(tb.startTime) / tb.fillInterval)
  273. }
  274. // adjustavailableTokens adjusts the current number of tokens
  275. // available in the bucket at the given time, which must
  276. // be in the future (positive) with respect to tb.latestTick.
  277. func (tb *Bucket) adjustavailableTokens(tick int64) {
  278. lastTick := tb.latestTick
  279. tb.latestTick = tick
  280. if tb.availableTokens >= tb.capacity {
  281. return
  282. }
  283. tb.availableTokens += (tick - lastTick) * tb.quantum
  284. if tb.availableTokens > tb.capacity {
  285. tb.availableTokens = tb.capacity
  286. }
  287. return
  288. }
  289. // Clock represents the passage of time in a way that
  290. // can be faked out for tests.
  291. type Clock interface {
  292. // Now returns the current time.
  293. Now() time.Time
  294. // Sleep sleeps for at least the given duration.
  295. Sleep(d time.Duration)
  296. }
  297. // realClock implements Clock in terms of standard time functions.
  298. type realClock struct{}
  299. // Now implements Clock.Now by calling time.Now.
  300. func (realClock) Now() time.Time {
  301. return time.Now()
  302. }
  303. // Now implements Clock.Sleep by calling time.Sleep.
  304. func (realClock) Sleep(d time.Duration) {
  305. time.Sleep(d)
  306. }