forked from vitessio/vitess
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ratelimiter.go
54 lines (48 loc) · 1.61 KB
/
ratelimiter.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// Copyright 2012, Google Inc. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package ratelimiter implements rate limiting functionality.
package ratelimiter
import (
"sync"
"time"
)
// RateLimiter was inspired by https://github.com/golang/go/wiki/RateLimiting.
// However, the go example is not good for setting high qps limits because
// it will cause the ticker to fire too often. Also, the ticker will continue
// to fire when the system is idle. This new Ratelimiter achieves the same thing,
// but by using just counters with no tickers or channels.
type RateLimiter struct {
maxCount int
interval time.Duration
mu sync.Mutex
curCount int
lastTime time.Time
}
// NewRateLimiter creates a new RateLimiter. maxCount is the max burst allowed
// while interval specifies the duration for a burst. The effective rate limit is
// equal to maxCount/interval. For example, if you want to a max QPS of 5000,
// and want to limit bursts to no more than 500, you'd specify a maxCount of 500
// and an interval of 100*time.Millilsecond.
func NewRateLimiter(maxCount int, interval time.Duration) *RateLimiter {
return &RateLimiter{
maxCount: maxCount,
interval: interval,
}
}
// Allow returns true if a request is within the rate limit norms.
// Otherwise, it returns false.
func (rl *RateLimiter) Allow() bool {
rl.mu.Lock()
defer rl.mu.Unlock()
if time.Now().Sub(rl.lastTime) < rl.interval {
if rl.curCount > 0 {
rl.curCount--
return true
}
return false
}
rl.curCount = rl.maxCount - 1
rl.lastTime = time.Now()
return true
}