Raxol.RateLimit (Raxol v2.6.0)

View Source

Rate limiting utilities for Raxol.

Provides token bucket rate limiting for API endpoints and actions.

Example

case Raxol.RateLimit.check(:login, user_ip) do
  :ok -> process_login()
  {:error, :rate_limited} -> {:error, "Too many attempts"}
end

Summary

Functions

Check if an action is allowed under rate limits.

Returns a specification to start this module under a supervisor.

Configure custom limits for an action.

Get remaining requests in the current window.

Reset rate limit for an identifier.

Get time until rate limit resets.

Start the rate limiter agent.

Functions

check(action, identifier, opts \\ [])

@spec check(atom(), String.t(), keyword()) :: :ok | {:error, :rate_limited}

Check if an action is allowed under rate limits.

Example

case Raxol.RateLimit.check(:login, user_ip) do
  :ok -> process_login()
  {:error, :rate_limited} -> reject_request()
end

child_spec(arg)

Returns a specification to start this module under a supervisor.

See Supervisor.

configure(action, opts)

@spec configure(
  atom(),
  keyword()
) :: :ok

Configure custom limits for an action.

Example

Raxol.RateLimit.configure(:custom_action, limit: 50, window: 30_000)

remaining(action, identifier, opts \\ [])

@spec remaining(atom(), String.t(), keyword()) :: non_neg_integer()

Get remaining requests in the current window.

Example

remaining = Raxol.RateLimit.remaining(:api, user_id)
# => 95

reset(action, identifier)

@spec reset(atom(), String.t()) :: :ok

Reset rate limit for an identifier.

Example

:ok = Raxol.RateLimit.reset(:login, user_ip)

reset_in(action, identifier, opts \\ [])

@spec reset_in(atom(), String.t(), keyword()) :: non_neg_integer()

Get time until rate limit resets.

Example

ms = Raxol.RateLimit.reset_in(:login, user_ip)
# => 45000 (milliseconds)

start_link(opts \\ [])

Start the rate limiter agent.

Usually started automatically by the application supervisor.