# Rate Limit Plug

[Elixir]( [Plug]( 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](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, []


    curl http://localhost:4000/

    ab -n 4

or run `curl` multiple times:

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

## Credits

* This library uses a Stern-Brocot tree to find a good ratio of the number of tokens to add to the bucket at a given interval - this ratio is a variation of the algorithm described in [John D. Cook's Best rational approximation](