Skip to content

Commit afece70

Browse files
authored
Refactor rate limit functions for improved performance (#189)
1 parent 17e4b02 commit afece70

File tree

1 file changed

+16
-6
lines changed

1 file changed

+16
-6
lines changed

dnc/rate_limit.go

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,19 @@
11
package dnc
22

33
import (
4+
"sort"
45
"time"
56
)
67

78
var rateLimitEvents []int64
89

9-
// IsAllowed solves the problem in O(1) time and O(n) space.
10+
// nanoSecond represents one second in nanoseconds.
11+
const nanoSecond = 1e9
12+
13+
// IsAllowed solves the problem in O(log n) time and O(n) space.
1014
func IsAllowed(limitPerSecond int) bool {
11-
now := time.Now().Unix()
12-
removeOldERateLimitEvents(now)
15+
now := time.Now().UnixNano()
16+
removeOldRateLimitEvents(now)
1317
if len(rateLimitEvents) >= limitPerSecond {
1418
return false
1519
}
@@ -18,10 +22,16 @@ func IsAllowed(limitPerSecond int) bool {
1822
return true
1923
}
2024

21-
func removeOldERateLimitEvents(now int64) {
22-
if len(rateLimitEvents) == 0 || now <= rateLimitEvents[0] {
25+
// removeOldRateLimitEvents uses binary search to remove events older than 1 second.
26+
func removeOldRateLimitEvents(now int64) {
27+
if len(rateLimitEvents) == 0 {
2328
return
2429
}
2530

26-
rateLimitEvents = []int64{}
31+
cutoff := now - nanoSecond
32+
idx := sort.Search(len(rateLimitEvents), func(i int) bool {
33+
return rateLimitEvents[i] >= cutoff
34+
})
35+
36+
rateLimitEvents = rateLimitEvents[idx:]
2737
}

0 commit comments

Comments
 (0)