Rate limiter for session creation using sliding window algorithm.
This GenServer maintains an ETS table to track session creation timestamps and enforces the configured rate limit (sessions per minute).
Configuration
config :phoenix_session_process,
rate_limit: 100 # Maximum 100 sessions per minuteAlgorithm
Uses a sliding window approach:
- Stores timestamp for each session creation attempt
- Counts entries in the last 60 seconds
- Rejects new sessions if count >= rate_limit
- Automatically cleans up old entries every 10 seconds
Performance
- O(1) insertion with ETS
- O(n) counting but optimized with select_count
- Minimal memory overhead (only timestamps)
- Thread-safe with ETS public table
Telemetry
Emits the following events:
[:phoenix, :session_process, :rate_limit_exceeded]- When limit is hit[:phoenix, :session_process, :rate_limit_check]- On each check
Summary
Functions
Checks if a new session can be created under the current rate limit.
Returns a specification to start this module under a supervisor.
Gets the current request count in the sliding window. Useful for monitoring and debugging.
Resets the rate limiter by clearing all tracked requests. Useful for testing.
Starts the rate limiter GenServer.
Functions
@spec check_rate_limit() :: :ok | {:error, :rate_limit_exceeded}
Checks if a new session can be created under the current rate limit.
Returns :ok if the session can be created, or {:error, :rate_limit_exceeded}
if the rate limit would be exceeded.
Examples
iex> RateLimiter.check_rate_limit()
:ok
# After 100 requests in 1 minute
iex> RateLimiter.check_rate_limit()
{:error, :rate_limit_exceeded}
Returns a specification to start this module under a supervisor.
See Supervisor.
@spec current_count() :: non_neg_integer()
Gets the current request count in the sliding window. Useful for monitoring and debugging.
Examples
iex> RateLimiter.current_count()
42
@spec reset() :: :ok
Resets the rate limiter by clearing all tracked requests. Useful for testing.
Starts the rate limiter GenServer.