ejfinneran / ratelimit

A Redis-backed rate limiter written in Ruby
MIT License
257 stars 55 forks source link

The count won't be correct when the interval is set close to span #17

Open cc26 opened 8 years ago

cc26 commented 8 years ago

Hi, I have read the source code and found out that it deletes the field in bucket + 1, and bucket + 2. Would this cause any issue when we set the interval to the bucket_span?

ratelimit = Ratelimit.new("messages", bucket_span : 60, bucket_interval : 20 ) 5.times do ratelimit.add(phone_number) end ratelimit.count(phone_number, 60)

Using the example in the document for example and set the span to 60 interval to 20, if we set add the phone number in the first 20 second and add the phone number in the next 20 sec and so on, the count will always be 5.

Thanks!

karellm commented 7 years ago

I confirm that count is not accurate is some cases. It caused me quite a little headache and should be documented better imo:

ratelimit = Ratelimit.new('email')
ratelimit.add(email)
ratelimit.count(email, 30)
> 1
ratelimit.count(email, 3600)
> 6 # wtf??

This is easily fixed with the bucket_span:

ratelimit = Ratelimit.new('updates_sent', bucket_span: 3600)
ratelimit.add(email)
ratelimit.count(email, 3600)
> 1