An Elixir plug that rate limiting with redis.
In Elixir, since ETS is provided by Erlang runtime, it can process rate limit count within memory, but in real world there is no guarantee that it will not restart every time it is deployed and sometimes you want to share values with multiple servers I guess.
So I decided to allow Rate Limit with Redis, even if I restarted the Erlang runtime every deployment, I also made it possible to handle from multiple servers.
- Add
plug_rate_limit_redis
to your list of dependencies inmix.exs
:
def deps do
[{:plug_rate_limit_redis, "~> 0.1.0"}]
end
- Ensure
plug_rate_limit_redis
is started before your application:
def application do
[applications: [:plug_rate_limit_redis]]
end
- Configure your
config.ex
config :plug_rate_limit_redis,
host: "localhost", # Redis host
port: 6379
- Add the RateLimit plug to the controller for which you want rate limit.
plug RateLimit, interval_seconds: 60, max_requests: 30
- If you want to restrict the action, please do as follows
plug RateLimit, [interval_seconds: 60, max_requests: 30] when action in [:index, :show:, :update]
- Or add it to pipeline with router
pipeline :rate_limit do
plug RateLimit, interval_seconds: 60, max_requests: 30
end
scope "/" do
pipe_through :rate_limit
get "/v1/foo/bar, FooController, :bar
end
- Fork it
- 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 new Pull Request