Last active
December 17, 2015 13:19
-
-
Save abevoelker/5615778 to your computer and use it in GitHub Desktop.
Basic rate limiter using Celluloid
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class RateLimiter | |
include Celluloid | |
def initialize(actions_per, seconds) | |
@bucket, @nice = actions_per, seconds | |
end | |
def request | |
wait :bucket_increment unless @bucket > 0 | |
@bucket -= 1 | |
after(@nice) { @bucket += 1; signal :bucket_increment } | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
r = RateLimiter.new(5, 10) # 5 actions allowed within any 10 second period | |
# make 6 requests in rapid fire: | |
r.request # => #<Timers::Timer:de353c fires in 9.999746148 seconds> | |
r.request # => #<Timers::Timer:dedaf0 fires in 9.999815019 seconds> | |
r.request # => #<Timers::Timer:df2dac fires in 9.999770345 seconds> | |
r.request # => #<Timers::Timer:e02a40 fires in 9.999726619 seconds> | |
r.request # => #<Timers::Timer:56dc04 fires in 9.999643746 seconds> | |
# the next one blocks for ~10s: | |
r.request # => #<Timers::Timer:68b8ac fires in 9.999792257 seconds> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment