ratelimit
A lock-free token bucket ratelimiter for rate limiting and admission control.
Getting Started
std is enabled by default. For no_std targets, disable default features:
= { = "1", = false }
Usage
Ratelimiter::new, Ratelimiter::builder, and StdClock are available with
the default std feature.
use Ratelimiter;
// 10,000 requests/s
let ratelimiter = new;
loop
For more control over burst capacity and initial tokens:
use Ratelimiter;
let ratelimiter = builder
.max_tokens // allow up to 5 seconds of burst
.initial_available // start with some tokens available
.build
.unwrap;
The rate can be changed dynamically at runtime:
use Ratelimiter;
let ratelimiter = new;
// later...
ratelimiter.set_rate;
A rate of 0 means unlimited -- try_wait() will always succeed.
no_std
Disable default features and provide your own monotonic clock:
use Duration;
use ;
;
let ratelimiter = with_clock;
assert!;
Design
This crate implements a lock-free token bucket algorithm. Tokens accumulate continuously based on elapsed time using scaled integer arithmetic for sub-token precision. All synchronization is done with atomic CAS operations, making it safe to share across threads with no mutex contention.
Key parameters:
- rate -- tokens per second. The single knob for controlling throughput.
- max tokens -- bucket capacity, bounding burst size. Defaults to
rate(1 second of burst). - initial available -- tokens available at construction. Defaults to 0.
Migration from 0.10.x
Before :
use Ratelimiter;
use Duration;
// 8 requests/s
let ratelimiter = builder
.build
.unwrap;
After:
use Ratelimiter;
// 8 requests/s
let ratelimiter = builder
.build
.unwrap;
Links
License
Licensed under either of Apache License, Version 2.0 or MIT license at your option.