Skip to main content

Module rate

Module rate 

Source
Expand description

Fixed-window rate limiting keyed by caller and route.

The RateLimiter trait answers whether a key is still within limit requests for the current minute. InMemoryRateLimiter keeps per-minute buckets in process memory, RedisBackedRateLimiter shares buckets in Redis via INCR plus a 60s expiry (falling back to memory on Redis errors), and create_from_env picks the Redis variant when REDIS_URL or REDIS_URI is set, else the in-memory one. Routers build keys as <user id or x-forwarded-for>:<route path>.

if !limiter.is_allowed("user-1:/v1/users/list", 100).await { return Err(too_many()); }

Structs§

InMemoryRateLimiter
In-process per-minute limiter: buckets are keyed by "{key}:{minute}" with a 60-second window and expired buckets are pruned by periodic cleanup.
RedisBackedRateLimiter
Redis-shared per-minute limiter: increments rate_limit:{key}:{minute} with a 60s expiry on first use. Uses the in-memory limiter whenever Redis is unconfigured or fails.

Enums§

LimiterKind
Selects which limiter backend create builds.

Traits§

RateLimiter
Per-minute request gate: returns true when key is still within limit requests for the current minute, false when the caller must be rejected.

Functions§

create
Builds the backend selected by kind as a shared trait object.
create_from_env
Builds a shared limiter from the environment: Redis-backed when REDIS_URL or REDIS_URI is set, otherwise in-memory.