Token Bucket Rate Limiter in Go
Implement a token bucket rate limiter that refills at a configured rate and allows a burst, guarding handlers against traffic spikes.
Code
package limiter
import (
"sync"
"time"
)
type TokenBucket struct {
mu sync.Mutex
capacity float64
tokens float64
refillRate float64
last time.Time
}
func NewTokenBucket(capacity, refillPerSecond float64) *TokenBucket {
return &TokenBucket{
capacity: capacity,
tokens: capacity,
refillRate: refillPerSecond,
last: time.Now(),
}
}
func (b *TokenBucket) Allow(cost float64) bool {
b.mu.Lock()
defer b.mu.Unlock()
now := time.Now()
b.tokens = min(b.capacity, b.tokens+now.Sub(b.last).Seconds()*b.refillRate)
b.last = now
if b.tokens >= cost {
b.tokens -= cost
return true
}
return false
}Report a problem with this exampleOpens a pre-filled issue on GitHub.