Token Bucket Rate Limiter Middleware

Implement a token bucket rate limiter as HTTP middleware for Go API throttling.

GoResilience

Code

gosnippet
30 lines
// middleware: wrap as HTTP middleware with app.use
package main
import ("net/http";"sync";"time")
type Bucket struct {
    mu sync.Mutex
    tokens float64
    rate float64
    capacity float64
    last time.Time
}
func NewBucket(rate, capacity float64) *Bucket {
    return &Bucket{tokens: capacity, rate: rate, capacity: capacity, last: time.Now()}
}
func (b *Bucket) Allow() bool {
    b.mu.Lock(); defer b.mu.Unlock()
    now := time.Now()
    b.tokens += b.rate * now.Sub(b.last).Seconds()
    if b.tokens > b.capacity { b.tokens = b.capacity }
    b.last = now
    if b.tokens >= 1 { b.tokens--; return true }
    return false
}
func RateLimit(bucket *Bucket) func(http.Handler) http.Handler {
    return func(next http.Handler) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            if !bucket.Allow() { http.Error(w, "rate limited", 429); return }
            next.ServeHTTP(w, r)
        })
    }
}

How the snippet works

Count the functions NewBucket, Allow and RateLimit as the entire surface area of Token Bucket Rate Limiter Middleware.

defer schedules the cleanup, and the scheduled call fires no matter how the function exits.

Using it

Signature: func NewBucket(rate, capacity float64) *Bucket

NewBucket is what another module would consume; nothing else here is load-bearing for callers.

Key statements

return &Bucket{tokens: capacity, rate: rate, capacity: capacity, last: time.Now()}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !bucket.Allow() { http.Error(w, "rate limited", 429); return }
next.ServeHTTP(w, r)
})
if b.tokens >= 1 { b.tokens--; return true }

Interactive Tools for This Topic

FAQ

Does this work in a bare project with no dependencies file?
Yes — a bare project runs it as-is, since nothing needs declaring. The file defines `NewBucket`, `Allow`, `RateLimit` at load time.