Build a rate limiter in Go
A token-bucket limiter in 40 lines, safe for concurrent use, then wired into an HTTP middleware.
A reusable Limiter type that allows a burst of 5 requests and then refills one token per second, plus an HTTP middleware that answers 429 Too Many Requests when the bucket is empty.
Prerequisites: Go installed, and basic knowledge of structs and methods. The code in this post was tested with Go 1.18, 1.20, 1.22 and 1.24.
1. The idea: a bucket of tokens
Each request takes one token. Tokens refill at a steady rate, up to a fixed capacity. When the bucket is empty, requests are denied.
That gives you bursts (a full bucket lets 5 requests through at once) and a steady average rate (one per second after that), with only three numbers to track: capacity, rate, and the time of the last refill.
Try the Token Bucket Live
Capacity: 5 tokens · Refills 1 token every 1.5s
Click “Send Request” rapidly to burst through 5 tokens and trigger 429.
Create a new folder and initialise a module:
mkdir limiter && cd limiter
go mod init limiter2. Define the limiter
Start with the struct. The mutex makes it safe to share between goroutines, which matters as soon as it sits behind an HTTP server.
package main
import (
"sync"
"time"
)
// Limiter is a token-bucket rate limiter, safe for concurrent use.
type Limiter struct {
mu sync.Mutex
tokens float64
capacity float64
rate float64 // tokens added per second
last time.Time
}
// NewLimiter returns a limiter that starts full.
func NewLimiter(capacity, rate float64) *Limiter {
return &Limiter{
tokens: capacity,
capacity: capacity,
rate: rate,
last: time.Now(),
}
}3. Refill and take a token
Work out how much time has passed, add that many tokens (capped at capacity), then try to spend one. Add this to limiter.go:
// Allow reports whether one request may proceed right now.
func (l *Limiter) Allow() bool {
l.mu.Lock()
defer l.mu.Unlock()
now := time.Now()
l.tokens += now.Sub(l.last).Seconds() * l.rate
if l.tokens > l.capacity {
l.tokens = l.capacity
}
l.last = now
if l.tokens < 1 {
return false
}
l.tokens--
return true
}Run go build in the folder. It should finish with no output. If it complains about a missing main, that is fine for now: you add one in the next step.
4. Try it
Create main.go and fire eight requests at a bucket of five:
package main
import "fmt"
func main() {
l := NewLimiter(5, 1)
for i := 1; i <= 8; i++ {
fmt.Println("request", i, l.Allow())
}
}go run .You should see requests 1 to 5 print true and requests 6 to 8 print false:
request 1 true
request 2 true
request 3 true
request 4 true
request 5 true
request 6 false
request 7 false
request 8 falseAll eight calls happen in a few microseconds, so almost no tokens refill between them. Add time.Sleep(time.Second) before the last call and request 8 will print true.
5. Use it as HTTP middleware
A limiter is most useful in front of a handler. This middleware wraps any http.Handler and answers 429 when the bucket is empty:
package main
import "net/http"
// Limit wraps a handler and answers 429 when the limiter is empty.
func Limit(l *Limiter, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !l.Allow() {
http.Error(w, "too many requests", http.StatusTooManyRequests)
return
}
next.ServeHTTP(w, r)
})
}Wire it up in main like this:
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "hello")
})
log.Fatal(http.ListenAndServe(":8080", Limit(NewLimiter(5, 1), mux)))Start it with go run ., then hit it from another terminal:
for i in 1 2 3 4 5 6 7 8; do curl -s -o /dev/null -w "%{http_code} " localhost:8080/; doneYou should see five 200 responses followed by three 429 responses. Wait a few seconds and run it again: requests succeed once more as tokens refill.
The status comes from http.StatusTooManyRequests, a constant in the standard library's net/http package.
This shares one bucket across all clients. Limiting per client (for example per IP address) is a natural next step.
6. Test it
Tests give you confidence the bucket behaves, including under concurrency:
package main
import (
"sync"
"testing"
)
func TestBurstThenDeny(t *testing.T) {
l := NewLimiter(3, 0.001)
for i := 0; i < 3; i++ {
if !l.Allow() {
t.Fatalf("request %d should be allowed", i+1)
}
}
if l.Allow() {
t.Fatal("request 4 should be denied")
}
}
func TestConcurrent(t *testing.T) {
l := NewLimiter(100, 0.001)
var wg sync.WaitGroup
for i := 0; i < 50; i++ {
wg.Add(1)
go func() { defer wg.Done(); l.Allow() }()
}
wg.Wait()
}go test -race ./...The output should end with ok and the package name. The -race flag makes Go report any unsynchronised access, so a pass means the mutex is doing its job.
Common errors
- Forgetting to cap tokens at capacity. A client that stays quiet for an hour would build up an unlimited burst. The
if l.tokens > l.capacitycheck prevents that. - Reading
l.tokenswithout the mutex. This is a data race. Rungo test -raceto catch it. - Using integers for tokens. At low rates the fractional part matters, so keep
tokensas afloat64.
Next steps
- Limit per client by keeping a
map[string]*Limiterkeyed by IP address, with a mutex around the map. - Compare with the
golang.org/x/time/ratepackage. Its documentation describes a token bucket of sizeb, refilled atrtokens per second, withAllow,ReserveandWaitmethods, and recommendsWaitfor most callers. In a real project you will likely want to use it instead of your own.