Rate limiting library for Go with support for the next algorithms:
- Token Bucket Algorithm: Efficient rate limiting with burst capacity
go get github.com/Murolando/m_rps_limiterpackage main
import (
"log"
"net/http"
"time"
"github.com/Murolando/m_rps_limiter/pkg/limiter"
)
func main() {
// Create a rate limiter with 10 requests per refill interval
rateLimiter, err := limiter.NewLimiter(
10, // limit
limiter.TokenBucket, // algorithm
time.NewTicker(time.Millisecond*100), // refill every 100ms
)
if err != nil {
log.Fatal("Failed to create limiter:", err)
}
defer rateLimiter.Stop()
// Apply rate limiting to HTTP handlers
http.Handle("/api", rateLimiter.Limit(http.HandlerFunc(apiHandler)))
log.Println("Server starting on :8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
func apiHandler(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("API Response"))
}The Token Bucket algorithm maintains a bucket of tokens that are consumed by incoming requests:
- Initialization: Bucket starts full with
limittokens - Request Processing: Each request consumes 1 token
- Token Refill: Tokens are added back at regular intervals
- Rate Limiting: Requests are rejected when no tokens are available
The library uses efficient design patterns:
- Atomic Operations: Thread-safe token management without mutexes
- Simple Logic: Minimal operations in the hot path
- Background Refill: Separate goroutine handles token replenishment
Note: While optimized for correctness and simplicity, this implementation prioritizes readability over maximum performance. For extremely high-throughput scenarios, consider benchmarking against your specific requirements.
Run benchmarks:
go test -bench=. ./pkg/limiter/Run the test suite:
go test ./pkg/limiter/- Fork the repository
- Create a feature branch
- Add tests for new functionality
- Ensure all tests pass
- Submit a pull request
This project is licensed under the MIT License - see the LICENSE file for details.
- Sliding Window algorithm
- Fixed Window algorithm
- Leaky Bucket algorithm
- Concurrency rate limiting
- Metrics and monitoring