Skip to main content

Module rate_limit

Module rate_limit 

Source
Expand description

Pluggable rate-limit primitive (Sprint 7 §6.1, ADR-057).

The library exposes a transport-agnostic RateLimiter trait plus a reference in-process [LruRateLimiter] implementation. Consumer binders (actix-web, axum, tower) adapt the trait to their middleware surface — this crate never mounts routes itself (F7 boundary).

§Algorithm

Sliding-window counter keyed by (route, subject). Each bucket stores the monotonic Instant of every hit inside the current window. On each RateLimiter::check:

  1. Prune entries older than window.
  2. If the remaining count >= max, deny with retry_after_secs = ceil(window - (now - oldest_hit)).
  3. Otherwise, record now and allow.

§Storage

An LRU cache bounds memory under pathological key churn. The cache capacity defaults to DEFAULT_LRU_CAPACITY (4096). Entries that are evicted lose their history — a deliberate trade-off: the bound is hard, and real-world adversaries cannot force forgiveness of their own recent hits without also flushing their own bucket.

§Subject identity

RateLimitSubject distinguishes per-IP (anonymous requests) from per-WebID (authenticated requests). Consumers SHOULD prefer WebID keying for authenticated endpoints: it is stable across NAT churn.

§Concurrency

The limiter uses parking_lot::Mutex (already in the dep graph via reqwest). Contention is O(1) per check; the critical section is the prune-and-push on a single bucket.

Structs§

RateLimitKey
Composite key for a limiter bucket. Bundles the logical route name with the subject; buckets never cross routes.

Enums§

RateLimitDecision
Outcome of a single RateLimiter::check.
RateLimitSubject
Rate-limit subject — the entity whose quota is being counted.

Traits§

RateLimiter
Transport-agnostic rate-limit contract.