Giter VIP home page Giter VIP logo

prorate's Introduction

Prorate

Provides a low-level time-based throttle. Is mainly meant for situations where using something like Rack::Attack is not very useful since you need access to more variables. Under the hood, this uses a Lua script that implements the Leaky Bucket algorithm in a single threaded and race condition safe way.

Build Status Gem Version

Installation

Add this line to your application's Gemfile:

gem 'prorate'

And then execute:

bundle install

Or install it yourself as:

gem install prorate

Usage

The simplest mode of operation is throttling an endpoint, using the throttler before the action happens.

Within your Rails controller:

t = Prorate::Throttle.new(
    redis: Redis.new,
    logger: Rails.logger,
    name: "throttle-login-email",
    limit: 20,
    period: 5.seconds
)
# Add all the parameters that function as a discriminator.
t << request.ip << params.require(:email)
# ...and call the throttle! method
t.throttle! # Will raise a Prorate::Throttled exception if the limit has been reached
#
# Your regular action happens after this point

To capture that exception, in the controller

rescue_from Prorate::Throttled do |e|
  response.set_header('Retry-After', e.retry_in_seconds.to_s)
  render nothing: true, status: 429
end

Throttling and checking status

More exquisite control can be achieved by combining throttling (see previous step) and - in subsequent calls - checking the status of the throttle before invoking the throttle. When you call throttle!, you add tokens to the leaky bucket.

Let's say you have an endpoint that not only needs throttling, but you want to ban credential stuffers outright. This is a multi-step process:

  1. Respond with a 429 if the discriminators of the request would land in an already blocking 'credential-stuffing'-throttle
  2. Run your regular throttling
  3. Perform your sign in action
  4. If the sign in was unsuccessful, add the discriminators to the 'credential-stuffing'-throttle

In your controller that would look like this:

t = Prorate::Throttle.new(
    redis: Redis.new,
    logger: Rails.logger,
    name: "credential-stuffing",
    limit: 20,
    period: 20.minutes
)
# Add all the parameters that function as a discriminator.
t << request.ip
# And before anything else, check whether it is throttled
if t.status.throttled?
  response.set_header('Retry-After', t.status.remaining_throttle_seconds.to_s)
  render(nothing: true, status: 429) and return
end

# run your regular throttles for the endpoint
other_throttles.map(:throttle!)
# Perform your sign in logic..

user = YourSignInLogic.valid?(
  email: params[:email],
  password: params[:password]
)

# Add the request to the credential stuffing throttle if we didn't succeed
t.throttle! unless user

# the rest of your action

To capture that exception, in the controller

rescue_from Prorate::Throttled do |e|
  response.set_header('Retry-After', e.retry_in_seconds.to_s)
  render nothing: true, status: 429
end

Using just the leaky bucket

There is also an object for using the heart of Prorate (the leaky bucket) without blocking or exceptions. This is useful if you want to implement a more generic rate limiting solution and customise it in a fancier way. The leaky bucket on it's own provides the following conveniences only:

  • Track the number of tokens added and the number of tokens that have leaked
  • Tracks whether a specific token fillup has overflown the bucket. This is only tracked momentarily if the bucket is limited

Level and leak rate are computed and provided as Floats instead of Integers (in the Throttle class). To use it, employ the LeakyBucket object:

# The leak_rate is in tokens per second
leaky_bucket = Prorate::LeakyBucket.new(redis: Redis.new, redis_key_prefix: "user123", leak_rate: 0.8, bucket_capacity: 2)
leaky_bucket.state.level #=> will return 0.0
leaky_bucket.state.full? #=> will return "false"
state_after_add = leaky_bucket.fillup(2) #=> returns a State object_
state_after_add.full? #=> will return "true"
state_after_add.level #=> will return 2.0

Why Lua?

Prorate is implementing throttling using the "Leaky Bucket" algorithm and is extensively described here. The implementation is using a Lua script, because is the only language available which runs inside Redis. Thanks to the speed benefits of Lua the script runs fast enough to apply it on every throttle call.

Using a Lua script in Prorate helps us achieve the following guarantees:

  • The script will run atomically. The script is evaluated as a single Redis command. This ensures that the commands in the Lua script will never be interleaved with another client: they will always execute together.
  • Any usages of time will use the Redis time. Throttling requires a consistent and monotonic time source. The only monotonic and consistent time source which is usable in the context of Prorate, is the TIME result of Redis itself. We are throttling requests from different machines, which will invariably have clock drift between them. This way using the Redis server TIME helps achieve consistency.

Development

After checking out the repo, run bin/setup to install dependencies. Then, run rake spec to run the tests. You can also 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 release a new version, update the version number in version.rb, and then run bundle exec rake release, which will create a git tag for the version, push git commits and tags, and push the .gem file to rubygems.org.

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/WeTransfer/prorate.

License

The gem is available as open source under the terms of the MIT License.

prorate's People

Contributors

arnofleming avatar bdegomme avatar dependabot[bot] avatar depfu[bot] avatar grdw avatar idanci avatar jeffisabelle avatar julik avatar larryfox avatar lorenzograndi4 avatar luca-suriano avatar martijnvermaat avatar renato-zannon avatar wjwh avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

prorate's Issues

Would you be open to adding a 'throttle' method (without the '!')?

Hi Team. Love the gem

I was wondering if you'd be open to adding a 'throttle' method which calls run_lua_throttler but doesn't raise the exception? I'm happy to create a PR if required.

I was expecting status to do this, but that just returns data about an existing throttle (if one exists). It doesn't execute run_lua_throttler

There are a few reasons for this:

  1. In some cases, I'd like to raise my own exception, rather than catching Prorate::Throttled and immediately raising my own exception.
  2. One scenario I'd like to use the gem for is rate-limiting calls we make out. In this case, exceeding the limit isn't really an exception, just a feedback mechanism for other pieces of the code. It seems ugly to catch an exception when it's not actually an exception.

Most importantly, I have a situation where I'd like to have (say) three rate limits apply to the same connection, with different timeframes. For example, I may have a rate limit over a 10 minute period, but also a slow-burn rate limit over a 24h period.

I was thinking of doing something like this in the controller:

configured_throttlers.each do |throttler|
  throttler.throttle!
end

The problem with is that if I do the above, the second throttler (the slow-burn counter) never increments if the short-term limiting raises an exception, since the second throttler is never reached. So I'd need to do something conceptionally like this:

active_throttlers = false

configured_throttlers.map do |throttler|
  begin
    throttler.throttle!
  rescue Prorate::Throttled
    active_throttlers = true
  end
end

raise MyException if active_throttlers

@julik

ERR value is not an integer or out of rang

When trying the prorate gem, I'm running into redis error:

require "prorate"
require "async"

Async do |task|
  11.times do |i|
    task.async do
      t = Prorate::Throttle.new(
          redis: $redis,
          logger: Rails.logger,
          name: "throttler",
          limit: 10,
          period: 1,
          block_for: 0.5
      )
      t << "counter"
      t.throttle!
    end
  end
end.wait
Applying throttle counter throttler
Applying throttle counter throttler
Applying throttle counter throttler
Applying throttle counter throttler
Applying throttle counter throttler
Applying throttle counter throttler
Applying throttle counter throttler
Applying throttle counter throttler
Applying throttle counter throttler
Applying throttle counter throttler
Applying throttle counter throttler
    8m    error: Async::Task [oid=0xaca8] [ec=0xacbc] [pid=742358] [2022-03-22 15:57:27 +0100]
               |   Redis::CommandError: ERR Error running script (call to f_18f5304b307c1151f10cef5f9757e8cf742c37b7): @user_script:51: ERR value is not an integer or out of range
               |   โ†’ /home/wojtek/.asdf/installs/ruby/3.1.1/lib/ruby/gems/3.1.0/gems/redis-4.6.0/lib/redis/client.rb:162 in `call'
               |     /home/wojtek/.asdf/installs/ruby/3.1.1/lib/ruby/gems/3.1.0/gems/redis-4.6.0/lib/redis.rb:263 in `block in send_command'
               |     /home/wojtek/.asdf/installs/ruby/3.1.1/lib/ruby/gems/3.1.0/gems/redis-4.6.0/lib/redis.rb:262 in `synchronize'
               |     /home/wojtek/.asdf/installs/ruby/3.1.1/lib/ruby/gems/3.1.0/gems/redis-4.6.0/lib/redis.rb:262 in `send_command'
               |     /home/wojtek/.asdf/installs/ruby/3.1.1/lib/ruby/gems/3.1.0/gems/redis-4.6.0/lib/redis/commands/scripting.rb:110 in `_eval'
               |     /home/wojtek/.asdf/installs/ruby/3.1.1/lib/ruby/gems/3.1.0/gems/redis-4.6.0/lib/redis/commands/scripting.rb:97 in `evalsha'
               |     /home/wojtek/.asdf/installs/ruby/3.1.1/lib/ruby/gems/3.1.0/gems/prorate-0.7.1/lib/prorate/throttle.rb:146 in `block in run_lua_throttler'
               |     /home/wojtek/.asdf/installs/ruby/3.1.1/lib/ruby/gems/3.1.0/gems/prorate-0.7.1/lib/prorate/null_pool.rb:4 in `with'
               |     /home/wojtek/.asdf/installs/ruby/3.1.1/lib/ruby/gems/3.1.0/gems/prorate-0.7.1/lib/prorate/throttle.rb:144 in `run_lua_throttler'
               |     /home/wojtek/.asdf/installs/ruby/3.1.1/lib/ruby/gems/3.1.0/gems/prorate-0.7.1/lib/prorate/throttle.rb:91 in `throttle!'
               |     (irb):211 in `block (3 levels) in <top (required)>'
               |     /home/wojtek/.asdf/installs/ruby/3.1.1/lib/ruby/gems/3.1.0/gems/async-2.0.1/lib/async/task.rb:258 in `block in schedule'

so it throws out when it should throttle (on the 11 call).
Do you know what could be the cause?

Redis gem API change for `exists`

Now every use of Prorate prints

`Redis#exists(key)` will return an Integer in redis-rb 4.3. `exists?` returns a boolean, you should use it instead. To opt-in to the new behavior now you can set Redis.exists_returns_integer =  true. To disable this message and keep the current (boolean) behaviour of 'exists' you can set `Redis.exists_returns_integer = false`, but this option will be removed in 5.0. (/Users/julik/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/prorate-0.6.0/lib/prorate/throttle.rb:104:in `block in status')
`Redis#exists(key)` will return an Integer in redis-rb 4.3. `exists?` returns a boolean, you should use it instead. To opt-in to the new behavior now you can set Redis.exists_returns_integer =  true. To disable this message and keep the current (boolean) behaviour of 'exists' you can set `Redis.exists_returns_integer = false`, but this option will be removed in 5.0. (/Users/julik/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/prorate-0.6.0/lib/prorate/throttle.rb:104:in `block in status')

with modern versions of the Redis gem. To make things convenient we might want to use a different call or see how we can suppress the warning only within Prorate - which might be annoyingly difficult since Prorate use is thread-local in the best scenario, but Redis.something = value is program-global and will race.

Document / validate positive value for block_for

Hi!

I noticed that if you use 0 as a value for block_for, then Redis raises the exception ERR invalid expire time in setex as soon as a request gets throttled. That is caused by block_duration reaching 0 here and setex failing.

> setex some_key 1 some_value
OK
> setex some_key 0 some_value
(error) ERR invalid expire time in setex

it would be nice to have validation for block_for or some additional documentation.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.