brazier/rate_limit

Types

Opaque handle to the limiter’s ETS table and owner.

pub type Handle

Why an operation on a limiter’s table or owner failed.

pub type LimiterError {
  LimiterNotRunning
  LimiterTimeout(timeout_ms: Int)
  LimiterCallFailed(reason: String)
}

Constructors

  • LimiterNotRunning

    The limiter’s owner exited, and its table with it.

  • LimiterTimeout(timeout_ms: Int)

    The owner did not answer within timeout_ms (it is alive but busy or suspended).

  • LimiterCallFailed(reason: String)

    The owner exited while handling the call; reason is its exit reason.

Rate limit configuration.

pub type RateLimitConfig {
  RateLimitConfig(max_requests: Int, window_seconds: Int)
}

Constructors

  • RateLimitConfig(max_requests: Int, window_seconds: Int)

    Arguments

    max_requests

    Maximum requests allowed per window. Must be at least 1.

    window_seconds

    Window duration in seconds. Must be at least 1.

Result of a rate limit check.

pub type RateLimitResult {
  Allowed(remaining: Int)
  RateLimited
}

Constructors

  • Allowed(remaining: Int)

    Request is allowed.

  • RateLimited

    Request is rate limited (over the limit, or refused because the limiter is at its key cap or no longer running).

A running rate limiter. Create one with new or new_with_max_keys, which validate the settings; read them with config and max_keys.

pub opaque type RateLimiter

Values

pub fn check(
  limiter: RateLimiter,
  key: String,
) -> RateLimitResult

Count a request from key and decide whether it is allowed.

pub fn config(limiter: RateLimiter) -> RateLimitConfig

The limiter’s settings.

pub const default_max_keys: Int

Default hard cap on live counters per limiter.

pub fn describe_error(error: LimiterError) -> String

A readable description of a LimiterError, for logs.

pub fn key_count(
  limiter: RateLimiter,
) -> Result(Int, LimiterError)

Number of live counters (one per key per active window).

pub fn max_keys(limiter: RateLimiter) -> Int

The limiter’s cap on live counters.

pub fn new(
  name: String,
  config: RateLimitConfig,
) -> Result(RateLimiter, String)

Create a rate limiter with the default key cap. Errors on invalid settings, an invalid name, or a name already in use.

pub fn new_with_max_keys(
  name: String,
  config: RateLimitConfig,
  max_keys: Int,
) -> Result(RateLimiter, String)

Create a rate limiter with an explicit cap on live counters.

pub fn reset(
  limiter: RateLimiter,
  key: String,
) -> Result(Nil, LimiterError)

Delete every counter for a key.

pub fn sweep(limiter: RateLimiter) -> Result(Int, LimiterError)

Delete expired counters now instead of waiting for the next periodic sweep. Returns how many counters were deleted.

✨ Search Document