Nex.RateLimit (nex_core v0.4.3)

Copy Markdown

ETS-based sliding window rate limiting for Nex applications.

Configuration

# Global defaults
Application.put_env(:nex_core, :rate_limit, max: 100, window: 60)

# As middleware plug
Application.put_env(:nex_core, :plugs, [
  {Nex.RateLimit.Plug, max: 60, window: 60}
])

Standalone Usage

case Nex.RateLimit.check(ip, max: 10, window: 60) do
  :ok -> Nex.json(%{result: "ok"})
  {:error, :rate_limited} -> Nex.status(429, "Too Many Requests")
end

Options

  • :max - Max requests per window (default: 100)
  • :window - Window size in seconds (default: 60)
  • :key_prefix - Prefix for namespacing limits (default: "default")

Summary

Functions

Checks and increments the counter for the given key. Returns :ok if within limit, {:error, :rate_limited} otherwise.

Returns the current request count for a key in the current window.

Resets the counter for a key (useful in tests).

Functions

check(key, opts \\ [])

Checks and increments the counter for the given key. Returns :ok if within limit, {:error, :rate_limited} otherwise.

count(key, opts \\ [])

Returns the current request count for a key in the current window.

reset(key, opts \\ [])

Resets the counter for a key (useful in tests).