ExHammer / hammer-backend-redis

A Redis backend for for the Hammer rate-limiter
https://hexdocs.pm/ExHammer/hammer-backend-redis
MIT License
48 stars 32 forks source link
elixir elixir-lang phoenix phoenix-framework rate-limiter rate-limiting redis

HammerBackendRedis

Build Status Hex.pm Documentation Total Download License

A Redis backend for the Hammer rate-limiter.

Installation

Hammer-backend-redis is available in Hex, the package can be installed by adding hammer_backend_redis to your list of dependencies in mix.exs:

def deps do
  [{:hammer_backend_redis, "~> 6.1"},
   {:hammer, "~> 6.0"}]
end

Usage

Configure the :hammer application to use the Redis backend:

config :hammer,
  backend: {Hammer.Backend.Redis, [delete_buckets_timeout: 10_0000,
                                   key_prefix: "my_application:rate_limiter",
                                   expiry_ms: 60_000 * 60 * 2,
                                   redix_config: [host: "localhost",
                                                  port: 6379]]}

(the redix_config arg is a keyword-list which is passed to Redix, it's also aliased to redis_config, with an s)

Another option to configure Redis is to use the Redis Url format (see https://hexdocs.pm/redix/Redix.html#start_link/1-using-a-redis-uri) to configure Redis. If both options are specified the redis_url will be used first.

config :hammer,
  backend: {Hammer.Backend.Redis, [delete_buckets_timeout: 10_0000,
                                   key_prefix: "my_application:rate_limiter",
                                   expiry_ms: 60_000 * 60 * 2,
                                   redis_url: "redis://HOST:PORT"]}

And that's it, calls to Hammer.check_rate/3 and so on will use Redis to store the rate-limit counters.

See the Hammer Tutorial for more.

Documentation

On hexdocs: https://hexdocs.pm/hammer_backend_redis/

Run tests locally

You need a running Redis instance. One can be started locally using docker-compose up -d. See the docker-compose.yml for more details on.

Getting Help

If you're having trouble, open an issue on this repo.