Skip to main content

KeyedRateLimiter

Struct KeyedRateLimiter 

Source
pub struct KeyedRateLimiter<C: Clock = SystemClock> { /* private fields */ }
Expand description

Per-key sliding-window rate limiter backed by a DashMap.

Each unique key (IP address, user ID, etc.) gets its own independent counter. The check-and-update sequence for a given key is atomic: no TOCTOU race can allow more requests than max_requests in any single window, even under high concurrency. Distinct keys live on different shards and never block each other on the update path.

The map is capped at DEFAULT_MAX_ENTRIES keys: when an insert would push len() past the cap the entry with the oldest window_start is evicted first. The cap is enforced strictly — the check, eviction, and insert for new keys all run inside a single insert_guard critical section, so len() never exceeds max_entries at any observable instant. Updates to already-present keys take the lock-free fast path and never contend on insert_guard.

§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.

§Type parameter

C: Clock selects the time source. Production code uses the default SystemClock (a zero-sized type) so the clock is inlined and no virtual dispatch or heap allocation occurs. Tests can substitute any closure or custom clock via KeyedRateLimiter::with_clock.

§Constructors

Implementations§

Source§

impl KeyedRateLimiter<SystemClock>

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§

impl<C: Clock> KeyedRateLimiter<C>

Source

pub fn with_clock(config: AuthRateLimitConfig, clock: C) -> Self

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

The clock’s now_unix_secs method 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( config: AuthRateLimitConfig, max_entries: usize, clock: C, ) -> Self

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

The check-and-update step for a given key is atomic: while inspecting and mutating the RequestRecord for key, this function holds the per-shard write reference for that key. No concurrent thread can observe a partial state for the same key, which prevents the classic TOCTOU race where multiple threads simultaneously exceed the rate limit.

§Capacity cap

When max_entries > 0 the map’s length is enforced strictly: new-key inserts run under a serialising insert_guard, so the cap-check, oldest-entry eviction, and insert all occur in a single critical section. records.len() <= max_entries therefore holds at every observable instant, including under sustained concurrent burst. The fast path (updates to keys already present) does not acquire the guard and runs lock-free.

The periodic expiry sweep is best-effort and runs outside the guard; it only ever shrinks records, so it cannot push len() over the cap.

§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.

Source

pub fn active_limiters(&self) -> usize

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

Returns the authoritative entry count maintained under insert_guard, not DashMap’s per-shard sum. Reads are lock-free and reflect the post-mutation count at every observable instant.

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

Trait Implementations§

Source§

impl<C: Clock + Clone> Clone for KeyedRateLimiter<C>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FromRef<T> for T
where T: Clone,

Source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
Source§

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

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: Sized + 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: Sized + 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> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
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