ratekeeper v0.2.4 Ratekeeper View Source

Ratekeeper

Ratekeeper is a library for scheduling rate-limited actions. It supports complex rate limits and estimates time left to resetting limits.

Installation

Add ratekeeper as dependency in mix.exs

def deps do
    [{:ratekeeper, "~> 0.2"}]
end

Usage

Limits can be set in config:

config :ratekeeper, :limits, %{"myapi.org" => [{1000, 5}, {60_000, 100}]}

or at runtime:

Ratekeeper.add_limit "myapi.org", 1000, 5
Ratekeeper.add_limit "myapi.org", 60_000, 100

This sets limits to 5 requests per 1 second and 100 requests per minute.

Appoint a request to rate limited api:

case Ratekeeper.register("myapi.org", 10_000) do
  nil ->
    raise "Rate limits exceeded, request not allowed in next 10 seconds"
  delay ->
    :timer.sleep(delay)
    MyApi.do_request()
end

Full documentation can be found at https://hexdocs.pm/ratekeeper.

Link to this section Summary

Functions

Returns a specification to start this module under a supervisor

Deletes limit rule

Returns all limits

Returns limits for id

Registers next request to the rate limited api in specified time

Resets all hits registered for current intervals

Starts Ratekeeper server

Returns time in milliseconds to wait for the next allowed request

Link to this section Functions

Link to this function add_limit(id, interval, limit) View Source

Adds limit rule.

Returns a specification to start this module under a supervisor.

See Supervisor.

Link to this function delete_limit(id, interval) View Source

Deletes limit rule.

Returns all limits

Returns limits for id

Link to this function register(id, max_delay \\ 0) View Source

Registers next request to the rate limited api in specified time.

Returns delay to wait before the next allowed request or nil if no request allowed in max_delay

Resets all hits registered for current intervals.

Starts Ratekeeper server.

args[:limits] can be provided to set limits in format %{bucket_name: [{interval, limit}]}

Returns time in milliseconds to wait for the next allowed request.

This function does not appoint actual api call! Use it only to estimate time (probably no practical use at all). If you are going to make a request, use Ratekeeper.register/2 instead.