Five Algorithms
Token bucket, leaky bucket, fixed window, sliding window log, and sliding window counter
Five rate limiting algorithms, per-key limits, Redis-backed distributed limiters, and net/http middleware — with a zero-dependency core and concurrency-safe, allocation-free hot paths.
go get github.com/KARTIKrocks/go-ratelimitToken bucket, leaky bucket, fixed window, sliding window log, and sliding window counter
Independent limits per user, IP, or API key, with idle cleanup and an LRU cap on tracked keys
Atomic Lua scripts, Redis server time, and Cluster-safe keys for limits shared across instances
Drop-in net/http middleware with standard X-RateLimit-* and Retry-After headers
RemoteAddr by default; opt-in X-Forwarded-For handling that only trusts the proxies you list
Choose what happens when Redis is unreachable, and observe every error through a handler
Combine per-second, per-minute, and per-hour limits that are checked before any is consumed
Instrumented wrappers count allowed, denied, and errored checks per named limiter
The core package is stdlib only; Redis and Prometheus live in their own modules
Every algorithm implements the same interfaces, so switching is a one-line change. The trade-off is how much burst you tolerate against how much state you keep per key.
| Algorithm | Bursts | Memory per key | Redis |
|---|---|---|---|
| Token bucket | Up to burst size | Constant | Available |
| Leaky bucket | Up to capacity | Constant | In-memory only |
| Fixed window | Up to 2× limit at a boundary | Constant | Available |
| Sliding window log | Up to limit, exact window | One timestamp per request | In-memory only |
| Sliding window counter | Approximate smoothing | Constant | Available |
Measured on an Intel i5-11400H (12 cores), Go 1.27, Linux. Once a key exists, every in-memory limiter decides a request without allocating.
50 ns/op
0 allocs, single goroutine
74 ns/op
0 allocs, including the key lookup
104 ns/op
0 allocs, 12 goroutines on one bucket
74 ns/op
0 allocs, single goroutine
Reproduce them yourself with go test -bench=. -benchmem ./... in the repository root. The full benchmark table covers every algorithm and its keyed variant.