Overview
Build, in Go, the token-bucket algorithm many APIs use to limit requests: a bucket that refills at a steady rate, caps at its capacity and spends one token per request.
- holds capacity tokens, adds rate per second
- refill from the time elapsed
- cap the bucket at capacity
Short Course
A token bucket holds up to capacity tokens and refills rate of them per
second; each request spends one. Trap: refill from the time elapsed since the
last refill and cap at capacity, or an idle client saves up a flood.
elapsed := now - l.last
l.tokens += elapsed * l.rate
if l.tokens > l.capacity {
l.tokens = l.capacity
}
l.last = now
Task
Write NewLimiter(capacity, rate int) *Limiter (it starts full) and
Allow(now int) bool, where now is the time in whole seconds: refill, then
spend a token if there is one. Example: with capacity 2, Allow(0) three
times gives true, true, false.
Test Suites
Pending
Next
Output