A flexible and efficient rate limiting library for Go applications with Redis backend support. This library provides a thread-safe, distributed rate limiting implementation suitable for high-concurrency environments.
- Redis-backed distributed rate limiting
- Thread-safe implementation
- Configurable rate limits per namespace
- Atomic operations using Redis Lua scripts
- Customizable time windows and attempt limits
- Concurrent access support
go get github.com/aknEvrnky/rate-limiterpackage main
import (
"context"
"time"
"github.com/redis/go-redis/v9"
"github.com/aknEvrnky/rate-limiter/pkg/ratelimiter/redis"
)
func main() {
// Initialize Redis client
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
DB: 0,
})
// Create a new rate limiter with configurations
limiter := redis.NewLimiter(
"myapp", // prefix for Redis keys
rdb, // Redis client
redis.WithLimit("api", 100, time.Hour), // 100 attempts per hour for "api" namespace
redis.WithLimit("web", 1000, time.Hour), // 1000 attempts per hour for "web" namespace
)
// Use the rate limiter
ctx := context.Background()
err := limiter.Attempt(ctx, "user:123", "api")
if err != nil {
// Handle rate limit exceeded or other errors
}
}The rate limiter can be configured with different limits for different namespaces:
limiter := redis.NewLimiter(
"myapp",
rdb,
redis.WithLimit("api", 100, time.Hour), // 100 attempts per hour
redis.WithLimit("web", 10, time.Minute), // 10 attempts per minute
redis.WithLimit("admin", 1000, time.Day), // 1000 attempts per day
)The rate limiter uses Redis as its backend. Configure the Redis client according to your needs:
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "your-password", // optional
DB: 0, // default DB
})The rate limiter returns specific errors that you can handle in your application:
err := limiter.Attempt(ctx, "user:123", "api")
switch err {
case nil:
// Success
case ratelimiter.ErrorTooManyAttempts:
// Rate limit exceeded
case ratelimiter.ErrorLimitNotFound:
// Namespace not configured
default:
// Other errors (Redis connection issues, etc.)
}The rate limiter is designed to be thread-safe and can handle concurrent requests efficiently. It uses Redis atomic operations and Lua scripts to ensure accurate rate limiting in high-concurrency scenarios.
Contributions are welcome! Please feel free to submit a Pull Request.
This project is licensed under the MIT License - see the LICENSE file for details.