Skip to content

Rate Limit

rate_limit

In-memory rate limiting implementation.

Provides a simple sliding window rate limiter for protecting authentication endpoints from brute force attacks.

Classes

RateLimitExceeded

Bases: Exception

Raised when rate limit is exceeded.

RateLimiter

RateLimiter(*, max_attempts: int, window_seconds: int)

Sliding window rate limiter for authentication endpoints.

Source code in fastauth/security/rate_limit.py
def __init__(
    self,
    *,
    max_attempts: int,
    window_seconds: int,
):
    self.max_attempts = max_attempts
    self.window_seconds = window_seconds
    self._store: dict[str, deque[float]] = defaultdict(deque)
Functions
hit
hit(key: str) -> None

Register an attempt for a given key. Raises RateLimitExceeded if limit is exceeded.

Source code in fastauth/security/rate_limit.py
def hit(self, key: str) -> None:
    """
    Register an attempt for a given key.
    Raises RateLimitExceeded if limit is exceeded.
    """
    now = time.time()
    window_start = now - self.window_seconds

    attempts = self._store[key]

    while attempts and attempts[0] < window_start:
        attempts.popleft()

    if len(attempts) >= self.max_attempts:
        raise RateLimitExceeded("Too many attempts")

    attempts.append(now)
reset
reset(key: str) -> None

Clear attempts after successful auth.

Source code in fastauth/security/rate_limit.py
def reset(self, key: str) -> None:
    """
    Clear attempts after successful auth.
    """
    self._store.pop(key, None)