Introducing a Rate Limiter Library for Go
Source: Dev.to
Overview
In modern backend systems, rate limiting is essential. Without it, APIs are exposed to abuse, resource exhaustion, and unfair usage. This library provides a production‑ready, thread‑safe rate limiter for Go, based on the Token Bucket algorithm.
Why the Token Bucket Algorithm?
- Allows controlled bursts of traffic
- Provides smooth request flow
- Widely used in production systems
- Simple to understand and reason about
Each client gets a bucket of tokens that refills over time. Requests consume tokens — once the bucket is empty, requests are rejected.
Features
- Production‑ready & thread‑safe
- Token Bucket algorithm with burst support
- Fast in‑memory storage
- Detailed rate‑limit results (remaining,
Retry-After, reset time) - Extensive unit tests and race‑condition testing
- Optional cleanup for stale entries
Usage
import (
"fmt"
"time"
"github.com/yasserelgammal/rate-limiter/limiter"
"github.com/yasserelgammal/rate-limiter/store"
)
config := limiter.Config{
Rate: 10,
Duration: time.Second,
Burst: 20,
}
store := store.NewMemoryStore(5 * time.Minute)
rateLimiter, _ := limiter.NewTokenBucket(config, store)
if rateLimiter.Allow("user123") {
fmt.Println("Request allowed")
}
With just a few lines, you get a reliable rate limiter ready for production.
Use Cases
- REST APIs
- Go microservices
- Public‑facing services
- Internal tools
- Anything that needs fair and controlled request handling
License & Contributions
The project is open source under the MIT license and welcomes contributions.
GitHub Repository – rate‑limiter
If you find it useful, feel free to leave a ⭐️. It really helps support open‑source work.