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
}The pass through the program
Count the functions NewTokenBucket and Allow as the entire surface area of Token Bucket Rate Limiter in Go.
defer schedules the cleanup, and the scheduled call fires no matter how the function exits.
Putting it to use
Signature: func NewTokenBucket(capacity, refillPerSecond float64) *TokenBucket
The surface worth importing is NewTokenBucket; the helpers around it are private to the snippet.
Core lines
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
}
mu sync.Mutex
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.Levenshtein Distance CalculatorCompute the classic edit distance between two strings with a space-optimized DP and a normalized similarity percentage.
FAQ
- Anything to download besides the language toolchain?
- Nothing beyond the toolchain you already have for this language. Every import resolves inside the standard library — `sync`, `time`. The file defines `NewTokenBucket`, `Allow` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.