A Redis rate limiter that provides both time-based limits and quantity-based limits based on classdojo/rolling-rate-limiter.
Add this line to your application's Gemfile:
gem'congestion'And then execute:
$ bundle
Or install it yourself as:
$ gem install congestion
limiter=Congestion.request'some_key'Where 'some_key' is an identifier for this request.
A common use case might be to set rate limits per user with something like "#{ user.id }_some_key".
Congestion.request returns an an instance that provides information about the request:
limiter.allowed?# => true if the request is permittedlimiter.rejected?# => true if the request is not permittedlimiter.too_many?# => true if there are too many requests in the intervallimiter.too_frequent?# => true if the requests are arriving too quicklylimiter.backoff# => the number of seconds before a request will be permittedA proc provides a Redis connection:
Congestion.redis=->{Redis.newurl: 'redis://:password@host:port/db'}To pool, your Redis connections:
require'congestion/redis_pool'Congestion::RedisPool.redis_config={url: 'redis://:password@host:port/db'}Congestion::RedisPool.pool_size=10# number of connections to useCongestion::RedisPool.timeout=10# seconds before timing out an operationCongestion.redis=Congestion::RedisPool.instanceGlobal options can be set with:
Congestion.default_options={namespace: 'congestion'# The Redis key prefix (e.g. 'congestion:some_key')interval: 1,# The timeframe to limit within in secondsmax_in_interval: 1,# The number of allowed requests within the intervalmin_delay: 0.0,# The minimum amount of time in seconds between requeststrack_rejected: true# True if rejected request count towards the limit}Per-request options can be set as well:
Congestion.request'some_key',interval: 60,min_delay: 1After checking out the repo, run bin/setup to install dependencies. Then, run bin/console for an interactive prompt that will allow you to experiment.
To install this gem onto your local machine, run bundle exec rake install. To run the specs, run bundle exec rake.
- Fork it ( https://github.com/parrish/congestion/fork )
- Create your feature branch (
git checkout -b my-new-feature) - Commit your changes (
git commit -am 'Add some feature') - Push to the branch (
git push origin my-new-feature) - Create a new Pull Request