Skip to content

rate_limit

Sliding-window rate limiting middleware backed by ETS.

Types

gleam
pub type RateLimitOptions {
  RateLimitOptions(
    limit: Int,
    window_ms: Int,
    key_fn: fn(Conn(Connection)) -> String,
  )
}

Functions

options

gleam
pub fn options(limit limit: Int, window_ms window_ms: Int) -> RateLimitOptions

Create options with the default key function (client IP from X-Forwarded-For, X-Real-IP, or host).


with_key

gleam
pub fn with_key(opts: RateLimitOptions, key_fn: fn(Conn(Connection)) -> String) -> RateLimitOptions

Override the key function. Use to rate-limit by user ID, API token, or any other dimension.


middleware

gleam
pub fn middleware(opts: RateLimitOptions) -> Middleware(Connection)

Returns a middleware function. Allows up to opts.limit requests per opts.window_ms milliseconds per key. Exceeding the limit returns 429 with a Retry-After header. Passing requests receive X-RateLimit-Limit and X-RateLimit-Remaining headers.

Released under the Apache 2.0 License.