internal/ratelimit: prevent time drift in TokenBucket refills
The TokenBucket ratelimiter accumulated time drift over multiple refills because I'm an idiot. We were using 'now' as base for lastFill calc. but this could case rate limiting to become inaccurate over time. Now we advance lastFill by *exact* periods from previous value. Signed-off-by: NotAShelf <raf@notashelf.dev> Change-Id: Ia3990b441ab6072f51dfdfa4a2511b5f6a6a6964
This commit is contained in:
parent
4e0b8f0d0a
commit
f46697bd21
2 changed files with 118 additions and 1 deletions
|
|
@ -40,7 +40,8 @@ func (tb *TokenBucket) Allow() bool {
|
|||
if tb.tokens > tb.capacity {
|
||||
tb.tokens = tb.capacity
|
||||
}
|
||||
tb.lastFill = now.Add(-elapsed % tb.interval)
|
||||
// Advance lastFill by exact periods to prevent drift
|
||||
tb.lastFill = tb.lastFill.Add(time.Duration(periods) * tb.interval)
|
||||
}
|
||||
|
||||
// Check if we have tokens available
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue