Sigra.Plug.RateLimit (Sigra v0.2.5)

Copy Markdown View Source

IP-based rate limiting plug for auth routes.

Rate limits non-safe HTTP methods (POST, PUT, PATCH, DELETE) by client IP address. GET and HEAD requests pass through without rate checking. When the rate is exceeded, returns 429 with a Retry-After header. Response content is delegated to the configured error handler for content negotiation (JSON for API, flash redirect for browser).

Options

  • :limit - Maximum requests within window. Default: 10.
  • :window - Window size in milliseconds. Default: 60_000 (1 minute).
  • :key_prefix - Prefix for rate limit key. Default: "sigra".
  • :error_handler - Module implementing Sigra.Plug.ErrorHandler. Required.
  • :limiter - Module implementing Sigra.RateLimiter. If nil, resolved at call time: uses Hammer if loaded, otherwise Noop with warning.

Key Format

Rate limit keys are formatted as "{key_prefix}:ip:{ip_address}". For example: "sigra:ip:127.0.0.1".

Proxy Considerations

This plug reads conn.remote_ip as-is. Applications behind a reverse proxy (Nginx, Cloudflare, AWS ALB) must configure remote_ip or plug_cloudflare to set conn.remote_ip to the real client IP.

Example

plug Sigra.Plug.RateLimit,
  limit: 10,
  window: :timer.minutes(1),
  key_prefix: "login",
  error_handler: MyAppWeb.AuthErrorHandler