Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sweep expired rate limiter buckets #290

Merged
merged 9 commits into from
Aug 28, 2023
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion pkg/ratelimiter/rate_limiter.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ func (l Limit) Refill(entry *Entry, multiplier uint16) {
// TokenBucketRateLimiter implements the RateLimiter interface
type TokenBucketRateLimiter struct {
log *zap.Logger
mutex sync.RWMutex
newBuckets *Buckets // buckets that can be added to
oldBuckets *Buckets // buckets to be swept for expired entries
PriorityMultiplier uint16
Expand Down Expand Up @@ -104,10 +105,14 @@ func (rl *TokenBucketRateLimiter) fillAndReturnEntry(limitType LimitType, bucket
if isPriority {
multiplier = rl.PriorityMultiplier
}
rl.mutex.RLock()
if entry := rl.oldBuckets.getAndRefill(bucket, limit, multiplier, false); entry != nil {
rl.mutex.RUnlock()
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

defer rl.mutex.RUnlock() would work here, since it is always getting unlocked at the end

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would, but I was avoiding defer on these short paths as we do elsewhere.

return entry
}
return rl.newBuckets.getAndRefill(bucket, limit, multiplier, true)
entry := rl.newBuckets.getAndRefill(bucket, limit, multiplier, true)
rl.mutex.RUnlock()
return entry
}

// The Spend function takes a bucket and a boolean asserting whether to apply the PRIORITY or the REGULAR rate limits.
Expand Down Expand Up @@ -140,8 +145,11 @@ func (rl *TokenBucketRateLimiter) Janitor(ctx context.Context, sweepInterval, ex
}

func (rl *TokenBucketRateLimiter) sweepAndSwap(expiresAfter time.Duration) (deletedEntries int) {
// Only the janitor writes to oldBuckets (see below), so we shouldn't need to rlock it here.
deletedEntries = rl.oldBuckets.deleteExpired(expiresAfter)
rl.mutex.Lock()
rl.newBuckets, rl.oldBuckets = rl.oldBuckets, rl.newBuckets
rl.mutex.Unlock()
rl.newBuckets.log.Info("became new buckets")
rl.oldBuckets.log.Info("became old buckets")
return deletedEntries
Expand Down