View Source Hammer behaviour (hammer v7.0.0-rc.3)

Hammer is a rate-limiting library for Elixir.

It provides a simple way for creating rate limiters, and comes with a built-in ETS backend.

defmodule MyApp.RateLimit do
  use Hammer, backend: :ets
end

# Start the rate limiter, in case of ETS it will create the ETS table and schedule cleanups
MyApp.RateLimit.start_link(clean_period: :timer.minutes(10))

# Check the rate limit allowing 10 requests per second
MyApp.RateLimit.hit("some-key", _scale = :timer.seconds(1), _limit = 10)

Summary

Callbacks

Optional callback for getting the counter value for a key.

Checks if a key is allowed to perform an action, and increment the counter.

Optional callback to check if a key is allowed to perform an action, and increment the counter.

Same as inc/3 with increment set to 1.

Optional callback for incrementing a counter value for a kit without performing limit check.

Optional callback for setting the counter value for a key.

Functions

Use the Hammer library in a module to create a rate limiter.

Types

Callbacks

Link to this callback

get(key, scale)

View Source (optional)
@callback get(key(), scale()) :: count()

Optional callback for getting the counter value for a key.

Returns the current counter value.

@callback hit(key(), scale(), limit()) :: {:allow, count()} | {:deny, timeout()}

Checks if a key is allowed to perform an action, and increment the counter.

Same as hit/4 with increment set to 1.

Link to this callback

hit(key, scale, limit, increment)

View Source (optional)
@callback hit(key(), scale(), limit(), increment()) ::
  {:allow, count()} | {:deny, timeout()}

Optional callback to check if a key is allowed to perform an action, and increment the counter.

Returns {:allow, count} if the action is allowed, or {:deny, timeout} if the action is denied.

This is the only required callback.

Link to this callback

inc(key, scale)

View Source (optional)
@callback inc(key(), scale()) :: count()

Same as inc/3 with increment set to 1.

Link to this callback

inc(key, scale, increment)

View Source (optional)
@callback inc(key(), scale(), increment()) :: count()

Optional callback for incrementing a counter value for a kit without performing limit check.

Returns the new counter value.

Link to this callback

set(key, scale, count)

View Source (optional)
@callback set(key(), scale(), count()) :: count()

Optional callback for setting the counter value for a key.

Returns the new counter value.

Functions

Link to this macro

__using__(opts)

View Source (macro)

Use the Hammer library in a module to create a rate limiter.

defmodule MyApp.RateLimit do
  use Hammer, backend: :ets
end