pub struct RateLimiter { /* private fields */ }Expand description
A shareable fixed-window rate limiter. Cloning shares the same underlying counters and clock, so the middleware layer and its state stay one limiter.
The counters live under a single Mutex. Sharding the lock was tried and
measured (panel finding E5, benchmarks/hot-path): under 64 concurrent
distinct-client requests across the full HTTP stack it showed no gain —
the critical section (one HashMap probe) is too short to contend, and a
per-request shard hash only added cost. A deployment that genuinely needs
cross-replica rate limiting at scale uses the distributed store
(rate_limit_with_store, ADR 0015), not a sharded in-process lock.
Implementations§
Source§impl RateLimiter
impl RateLimiter
Sourcepub fn with_clock(limit: RateLimit, clock: Arc<dyn Clock>) -> Self
pub fn with_clock(limit: RateLimit, clock: Arc<dyn Clock>) -> Self
A limiter over an injected Clock, for deterministic tests.
Sourcepub fn trusting_forwarded_for(self, trust: bool) -> Self
pub fn trusting_forwarded_for(self, trust: bool) -> Self
Keys on the rightmost X-Forwarded-For entry instead of the raw peer IP.
Enable this only when the service sits behind a single trusted reverse
proxy that sets X-Forwarded-For: the rightmost entry is the address that
proxy observed and a client cannot forge it. Left off (the default), the
limiter keys on the TCP peer — correct for a directly exposed service, but
collapsing every client into one bucket behind a proxy.