Go Implementation
Practical Rate Limiting in Go
1. Standard Library Approach
Using time.Ticker for Basic Rate Limiting
func rateLimitedFunction() {
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for {
select {
case <-ticker.C:
// Process request
performAction()
}
}
}
2. Advanced Rate Limiting Package
Creating a Comprehensive Rate Limiter
type RateLimiter struct {
mu sync.Mutex
limit rate.Limit
burst int
limiter *rate.Limiter
}
func NewRateLimiter(requestsPerSecond float64, burstSize int) *RateLimiter {
return &RateLimiter{
limit: rate.Limit(requestsPerSecond),
burst: burstSize,
limiter: rate.NewLimiter(rate.Limit(requestsPerSecond), burstSize),
}
}
func (rl *RateLimiter) Allow() bool {
return rl.limiter.Allow()
}
3. Distributed Rate Limiting
Redis-Based Distributed Rate Limiter
type RedisRateLimiter struct {
client *redis.Client
keyPrefix string
limit int
window time.Duration
}
func (r *RedisRateLimiter) IsAllowed(key string) bool {
currentTime := time.Now()
key = fmt.Sprintf("%s:%s", r.keyPrefix, key)
// Atomic increment and check
result, err := r.client.Eval(`
local current = redis.call("INCR", KEYS[1])
if current > tonumber(ARGV[1]) then
return 0
end
if current == 1 then
redis.call("EXPIRE", KEYS[1], ARGV[2])
end
return 1
`, []string{key}, r.limit, int(r.window.Seconds())).Result()
return err == nil && result == int64(1)
}
4. Middleware Implementation
HTTP Request Rate Limiting
func RateLimitMiddleware(limiter *RateLimiter) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !limiter.Allow() {
http.Error(w, "Rate limit exceeded", http.StatusTooManyRequests)
return
}
next.ServeHTTP(w, r)
})
}
}
Rate Limiting Strategies Comparison
Strategy |
Pros |
Cons |
Use Case |
Fixed Window |
Simple implementation |
Can cause burst in border periods |
Simple API protection |
Sliding Window |
More accurate |
Higher computational overhead |
Precise rate control |
Token Bucket |
Handles burst traffic |
Complex implementation |
Network traffic management |
Best Practices
graph TD
A[Rate Limiting Best Practices] --> B[Clear Error Handling]
A --> C[Configurable Limits]
A --> D[Logging and Monitoring]
A --> E[Graceful Degradation]
- Use atomic operations
- Minimize lock contention
- Implement efficient data structures
- Consider caching mechanisms
Error Handling and Resilience
Implementing Robust Error Handling
func (rl *RateLimiter) ExecuteWithRateLimit(fn func() error) error {
if !rl.Allow() {
return errors.New("rate limit exceeded")
}
return fn()
}
At LabEx, we emphasize the importance of flexible and efficient rate limiting strategies tailored to specific system requirements.