Skip to content

Commit 90506ef

Browse files
committed
Change condition of rate limiter to gte; fix limit time calculation
1 parent d3c6aae commit 90506ef

File tree

1 file changed

+10
-5
lines changed

1 file changed

+10
-5
lines changed

ratelimiter.go

+10-5
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ func New(dataStore LimitStore, requestsLimit int64, windowSize time.Duration) *R
2121
}
2222
}
2323

24-
// Inc increments limiter counter for a given key or returns error when it's not possible. Inc should be called when a request for a given limited resource has been fulfilled
24+
// Inc increments limiter counter for a given key or returns error when it's not possible
2525
func (r *RateLimiter) Inc(key string) error {
2626
currentWindow := time.Now().UTC().Truncate(r.windowSize)
2727
return r.dataStore.Inc(key, currentWindow)
@@ -49,7 +49,7 @@ func (r *RateLimiter) Check(key string) (limitStatus *LimitStatus, err error) {
4949

5050
rate := float64((float64(r.windowSize)-float64(timeFromCurrWindow))/float64(r.windowSize))*float64(prevValue) + float64(currentValue)
5151
limitStatus = &LimitStatus{}
52-
if rate > float64(r.requestsLimit) {
52+
if rate >= float64(r.requestsLimit) {
5353
limitStatus.IsLimited = true
5454
limitDuration := r.calcLimitDuration(prevValue, currentValue, timeFromCurrWindow)
5555
limitStatus.LimitDuration = &limitDuration
@@ -73,9 +73,14 @@ func (r *RateLimiter) calcLimitDuration(prevValue, currValue int64, timeFromCurr
7373
var limitDuration time.Duration
7474
if prevValue == 0 {
7575
// unblock in the next window where prevValue is currValue and currValue is zero (assuming that since limit start all requests are blocked)
76-
nextWindowUnblockPoint := float64(r.windowSize) * (1.0 - (float64(r.requestsLimit) / float64(currValue)))
77-
timeToNextWindow := r.windowSize - timeFromCurrWindow
78-
limitDuration = timeToNextWindow + time.Duration(int64(nextWindowUnblockPoint)+1)
76+
if currValue != 0 {
77+
nextWindowUnblockPoint := float64(r.windowSize) * (1.0 - (float64(r.requestsLimit) / float64(currValue)))
78+
timeToNextWindow := r.windowSize - timeFromCurrWindow
79+
limitDuration = timeToNextWindow + time.Duration(int64(nextWindowUnblockPoint)+1)
80+
} else {
81+
// when requestsLimit is 0 we want to block all requests - set limitDuration to -1
82+
limitDuration = -1
83+
}
7984
} else {
8085
currWindowUnblockPoint := float64(r.windowSize) * (1.0 - (float64(r.requestsLimit-currValue) / float64(prevValue)))
8186
limitDuration = time.Duration(int64(currWindowUnblockPoint+1)) - timeFromCurrWindow

0 commit comments

Comments
 (0)