Project

ratelimit

0.21
Low commit activity in last 3 years
There's a lot of open issues
A long-lived project that still receives updates
This library uses Redis to track the number of actions for a given subject over a flexible time frame.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Development

>= 1.6
>= 0
>= 0
>= 0
>= 0
>= 0

Runtime

>= 3.0.0
 Project Readme

Ratelimit: Slow your roll

Code Climate Coverage Status

Ratelimit provides a way to rate limit actions across multiple servers using Redis. This is a port of RateLimit.js found here and inspired by this post.

Installation

Add this line to your application's Gemfile:

gem 'ratelimit'

And then execute:

$ bundle

Or install it yourself as:

$ gem install ratelimit

Usage

My example use case is bulk processing data against an external API. This will allow you to limit multiple processes across multiple servers as long as they all use the same Redis database.

Add to the count for a given subject via add with a unique key. I've used the example of a phone number below but anything unique would work (URL, email address, etc.)

You can then fetch the number of executions for given interval in seconds via the count method.

ratelimit = Ratelimit.new("messages")
5.times do
  ratelimit.add(phone_number)
end
ratelimit.count(phone_number, 30)
# => 5

You can check if a given threshold has been exceeded or not. The following code checks if the currently rate is over 10 executions in the last 30 seconds or not.

ratelimit.exceeded?(phone_number, threshold: 10, interval: 30)
# => false
ratelimit.within_bounds?(phone_number, threshold: 10, interval: 30)
# => true

You can also pass a block that will only get executed if the given threshold is within bounds. Beware, this code blocks until the block can be run.

ratelimit.exec_within_threshold phone_number, threshold: 10, interval: 30 do
  some_rate_limited_code
  ratelimit.add(phone_number)
end

Documentation

Full documentation can be found here.

Contributing

  1. Fork it ( https://github.com/ejfinneran/ratelimit/fork )
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create a new Pull Request