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.

GoResilience

Code

gosnippet
36 lines
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

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.