Skip to main content

KeyedRateLimiter

Struct KeyedRateLimiter 

Source
pub struct KeyedRateLimiter { /* private fields */ }
Expand description

Per-key sliding-window rate limiter backed by a Mutex<HashMap>.

Each unique key (IP address, user ID, etc.) gets its own independent counter. The check-and-update sequence is atomic: no TOCTOU race can allow more requests than max_requests in any single window, even under high concurrency.

The map is capped at DEFAULT_MAX_ENTRIES keys. When a new key arrives at capacity the entry with the oldest window_start is evicted to make room, bounding memory growth while still tracking new sources.

§Deployment note

This rate limiter is per-process. In a multi-replica deployment, each replica enforces the limit independently — the effective limit across N replicas is N × limit. For true distributed enforcement, configure a Redis-backed rate limiter via the redis-rate-limiting Cargo feature (see the fraiseql-observers queue feature for the integration pattern). Call warn_if_single_node_rate_limiting during server startup to emit a reminder when no distributed backend is detected.

§Constructors

Implementations§

Source§

impl KeyedRateLimiter

Source

pub fn new(config: AuthRateLimitConfig) -> Self

Create a new keyed rate limiter using wall-clock time.

Source

pub fn with_max_entries(config: AuthRateLimitConfig, max_entries: usize) -> Self

Create a rate limiter with a custom entry cap.

Use this when the deployment context calls for a tighter or looser bound than DEFAULT_MAX_ENTRIES. Setting max_entries = 0 disables the cap (unbounded — not recommended in production).

Source

pub fn with_clock<F>(config: AuthRateLimitConfig, clock: F) -> Self
where F: Fn() -> u64 + Send + Sync + 'static,

Create a rate limiter with an injectable clock (for testing).

The clock function is called on every check() to obtain the current Unix timestamp. Pass || u64::MAX to simulate a broken system clock and verify fail-open behavior.

Source

pub fn with_clock_and_max_entries<F>( config: AuthRateLimitConfig, max_entries: usize, clock: F, ) -> Self
where F: Fn() -> u64 + Send + Sync + 'static,

Create a rate limiter with both a custom clock and a custom entry cap (for testing).

Combines the benefits of KeyedRateLimiter::with_clock and KeyedRateLimiter::with_max_entries for deterministic eviction tests.

Source

pub fn check(&self, key: &str) -> Result<()>

Check if a request should be allowed for the given key

§Atomicity

This operation is atomic - the entire check-and-update sequence happens atomically:

  1. Acquires exclusive lock on rate limit records
  2. Gets current timestamp
  3. Loads or creates request record for this key
  4. Decides: allow, reset window, or deny
  5. Updates counter/window only if request is allowed
  6. Releases lock

No concurrent thread can observe a partial state. This prevents classic time-of-check-time-of-use (TOCTOU) race conditions where multiple threads simultaneously exceed the rate limit.

§Returns

Ok(()) if the request is allowed and the counter has been incremented.

§Errors

Returns AuthError::RateLimited if the key has exceeded the configured rate limit within the sliding window.

§Panics

Panics if the Mutex is poisoned (another thread panicked while holding the lock). This is acceptable because a poisoned lock indicates a thread panic, suggesting the system is already in an inconsistent state and should be restarted.

Source

pub fn active_limiters(&self) -> usize

Get the number of active rate limiters (for monitoring).

Source

pub fn clear(&self)

Clear all rate limiters (for testing or reset).

Source

pub fn clone_config(&self) -> AuthRateLimitConfig

Create a copy for independent testing

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<A, B, T> HttpServerConnExec<A, B> for T
where B: Body,