Expand description
Clock-agnostic token-bucket rate limiter.
A token bucket holds up to capacity tokens and refills refill_amount
tokens every refill_interval time units. Each request takes one or more
tokens; when the bucket is empty, requests are denied until it refills. The
capacity sets the largest burst you will allow; the refill rate sets the
sustained throughput.
RateLimiter is a small, Copy value. It does not read the clock,
sleep, or allocate — you pass the current time in on each call as a plain
u64 in whatever monotonic unit you choose (milliseconds is typical), and
the intervals use that same unit. That keeps it usable from synchronous
code, any async runtime, and no_std / embedded targets, and makes every
decision deterministic and easy to test. All arithmetic is integer-only and
saturating, so no call ever overflows or panics.
§Example
use reliakit_ratelimit::RateLimiter;
// Allow bursts of up to 10, refilling 1 token every 100ms (~10/sec).
let mut limiter = RateLimiter::new(10, 1, 100);
// The bucket starts full, so a burst of 10 is allowed immediately.
for _ in 0..10 {
assert!(limiter.try_acquire_one(0));
}
// The 11th is denied until the bucket refills.
assert!(!limiter.try_acquire_one(0));
assert_eq!(limiter.retry_after(0, 1), Some(100)); // one token in 100ms
// After 100ms exactly one token is back.
assert!(limiter.try_acquire_one(100));
assert!(!limiter.try_acquire_one(100));Structs§
- Rate
Limiter - A token-bucket rate limiter.