pub struct RateLimiter { /* private fields */ }Expand description
Fixed-window rate limiter, usable as middleware
Implementations§
Source§impl RateLimiter
impl RateLimiter
Sourcepub fn new(limit: u32, window: Duration) -> Self
pub fn new(limit: u32, window: Duration) -> Self
Allow limit requests per window for each client IP
Sourcepub fn store(self, store: impl RateLimitStore) -> Self
pub fn store(self, store: impl RateLimitStore) -> Self
Count in store instead of process memory, so that all instances of a
service share one budget per client
Sourcepub fn sliding_window(self) -> Self
pub fn sliding_window(self) -> Self
Count over a window that slides with time instead of resetting at fixed
boundaries. A fixed window lets a client send limit requests just before
the reset and limit more just after (twice the limit within a moment);
the sliding window weighs the previous window by how much of it still
overlaps, so the rate stays at limit per window at any moment.
Sourcepub fn key_by<F>(self, f: F) -> Self
pub fn key_by<F>(self, f: F) -> Self
Choose the bucket per request, e.g. an API key header. Returning None
exempts the request from limiting.
Sourcepub fn trust_forwarded_for(self) -> Self
pub fn trust_forwarded_for(self) -> Self
Use the first X-Forwarded-For address, falling back to the peer IP.
Only enable this behind a reverse proxy that sets the header: otherwise
clients choose their own bucket and can evade the limit. Prefer
App::trusted_proxies: the default
key then is the real client address, found by skipping your own proxies
from the right, which clients cannot influence.