pub struct KeyedRateLimiter<B: RateLimitBackend> { /* private fields */ }in-memory only.Expand description
Per-key rate limiter that tracks separate rate limits for each key.
Keys either use the default quota or a per-key override set via
with_quota_for_key.
Overrides live in a DashMap consulted by borrowed key on every
check; the check decision itself is delegated straight to the
shared backend, so the warm path performs no allocation.
§Example
use throttle_kit::{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> KeyedRateLimiter<B>
impl<B: RateLimitBackend> KeyedRateLimiter<B>
Sourcepub fn new(default_quota: Quota, backend: B) -> Self
pub fn new(default_quota: Quota, backend: B) -> Self
Create a new keyed rate limiter with the given default quota and backend.
Sourcepub fn with_quota_for_key(&self, key: &str, quota: Quota)
pub fn with_quota_for_key(&self, key: &str, quota: Quota)
Override the rate limit quota for a specific key.
This replaces any existing override for the key. The next call
to check uses this quota.
Sourcepub async fn check(&self, key: &str) -> RateLimitResult
pub async fn check(&self, key: &str) -> RateLimitResult
Check whether the caller identified by key is allowed to proceed.
The warm path (any repeated check) is allocation-free: the
override map is read by borrowed key, and the decision comes
straight from the shared backend — no per-key limiter is
materialized or cloned. The map guard is never held across
the backend await.
Sourcepub fn check_sync(&self, key: &str) -> RateLimitResult
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).