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:
raf 2026-03-01 20:56:11 +03:00
commit f46697bd21
Signed by: NotAShelf
GPG key ID: 29D95B64378DB4BF
2 changed files with 118 additions and 1 deletions

View file

@ -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