Skip to content

Instantly share code, notes, and snippets.

@abevoelker
Last active December 17, 2015 13:19
Show Gist options
  • Save abevoelker/5615778 to your computer and use it in GitHub Desktop.
Save abevoelker/5615778 to your computer and use it in GitHub Desktop.
Basic rate limiter using Celluloid
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
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