Skip to main content

KeyedRateLimiter

Struct KeyedRateLimiter 

Source
pub struct KeyedRateLimiter<B: RateLimitBackend + Clone> { /* private fields */ }
Expand description

Per-key rate limiter that tracks separate rate limits for each key.

Each key gets its own RateLimiter instance with either a custom quota (set via with_quota_for_key) or the default quota.

§Example

use ratelimit::{KeyedRateLimiter, Quota, InMemoryBackend};

#[tokio::main]
async fn main() {
    let backend = InMemoryBackend::new();
    let limiter = KeyedRateLimiter::new(Quota::per_second(100), backend);

    // Tighter limit for login endpoint
    limiter.with_quota_for_key("login", Quota::per_second(10));

    let result = limiter.check("192.168.1.1").await;
    assert!(result.allowed);
}

Implementations§

Source§

impl<B: RateLimitBackend + Clone> KeyedRateLimiter<B>

Source

pub fn new(default_quota: Quota, backend: B) -> Self

Create a new keyed rate limiter with the given default quota and backend.

Source

pub fn with_quota_for_key(&self, key: &str, quota: Quota)

Override the rate limit quota for a specific key.

This replaces any existing limiter for the key. If the key has not been seen yet, the next call to check will use this quota instead of the default.

Source

pub async fn check(&self, key: &str) -> RateLimitResult

Check whether the caller identified by key is allowed to proceed.

Source

pub fn check_sync(&self, key: &str) -> RateLimitResult

Synchronous version of check.

Blocks the current thread until the check completes. Useful for synchronous frameworks (e.g. Actix, Rocket).

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, 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, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

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

fn try_from(value: U) -> Result<T, !>

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.