Dead simple distributed redis-based rate limiter.
Uses redis ZSET structure for storing events.
Basically the algorithm does this:
- Remove events older than window time interval with
ZREMRANGEBYSCORE
. - Count elements with
ZCARD
. - If the number of elements is less than limit, than add event (allow it). Otherwise - deny.
See full lua script in the source code.
import "github.com/tetafro/rate"
// 1000 events per second
limit := NewLimit("localhost:6379", "rate-limiter", 1000)
for event := range events {
if !limit.Allow() {
continue // denied
}
doSomething() // allowed
}