ExHammer / hammer

An Elixir rate-limiter with pluggable backends
https://hexdocs.pm/hammer/
MIT License
749 stars 42 forks source link

Add the hits parameters #22

Closed robsonpeixoto closed 6 years ago

robsonpeixoto commented 6 years ago

Some solutions has the concept of query complexity/cost and I'd like to this value to rate limite the customer.

If change the api to add the hits parameter will be possible to use hammer to rate limit

  @spec check_rate(id :: String.t(), scale_ms :: integer, limit :: integer, hits :: integer) ::
          {:allow, count :: integer}
          | {:deny, limit :: integer}
          | {:error, reason :: any}
  def check_rate(id, scale_ms, limit, hits \\ 1) do
    check_rate(:single, id, scale_ms, limit, hits)
  end

Does that make sense to you?

JuneKelly commented 6 years ago

Ah, I see, this does make sense.

Just to to totally clear, this change would allow you to specify the number to be added to the bucket, rather than the constant 1 that it is now?

robsonpeixoto commented 6 years ago

Perfect!

JuneKelly commented 6 years ago

Cool, I'll take a swing at it in the next week or so. Or, PRs welcome. :+1:

JuneKelly commented 6 years ago

Ok, I've found that adding a default parameter to check_rate causes a conflict between the two existing function-heads (check_rate/3 and check_rate/4), so this feature will be added as a new function: check_rate_inc.

JuneKelly commented 6 years ago

@robsonpeixoto I have released version 5.0.0-rc1 of both hammer and hammer-backend-redis.

They include a new check_rate_inc function that can be used to supply a custom increment. Example:

# Bulk file upload
user_id = get_user_id_somehow()
n = get_number_of_files()
case Hammer.check_rate_inc("upload_file_bulk:#{user_id}", 60_000, 10, n) do
  {:allow, _count} ->
    # upload all of the files
  {:deny, _limit} ->
    # deny the request
end

If this looks ok, I can proceed with a final release for 5.0.0, or if there's any issues just let me know! :)

(docs here: https://hexdocs.pm/hammer/5.0.0-rc1/Hammer.html#check_rate_inc/4)

EDIT: I'm not totally settled on the check_rate_inc name, any more sensible suggestions welcome.

robsonpeixoto commented 6 years ago

This design is perfect. Thanks a lot.

JuneKelly commented 6 years ago

Cool, I'll cut a release for 5.0.0 soon. Thanks!

JuneKelly commented 6 years ago

This is done, and released in v5.0.0, of both hammer and hammer_backend_redis.

There is a new tutorial section on Custom Increments which explains how to use this new feature.