Rate Limit Plug

ElixirPlug giving requests per second rate limiting capability.

A resource can be protected by a pro-rata rate limit. For example a limit of 4 requests a second will allow a request every 250ms - you cannot use up all requests in the first few milliseconds of a period.

The response code when the limit is exceeded is 429 Too Many Requests. This plug uses the Token Bucket Algorithm.

Master: Build Status

Example

There is an example app in example/demo.exs. To run:

mix run --no-halt example/demo.exs

Then call enough times to exceed the 4 req/sec limit:

seq 5 | xargs -Iz curl -w " %{http_code}\n" http://localhost:4000/
ok 200
ok 200
ok 200
ok 200
Too Many Requests 429

Dev

Start REPL:

iex -S mix

Load plug:

c "lib/plug/ratelimit.ex"
{:ok, _} = Plug.Adapters.Cowboy.http Plug.Ratelimit, []

Exercise:

curl http://localhost:4000/
ab -n 4 http://127.0.0.1:4000/

or run curl multiple times:

seq 5 | xargs -Iz curl http://localhost:4000/

Credits