ratelimit
A lock-free token bucket ratelimiter for rate limiting and admission control.
Getting Started
Usage
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.
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.
Links
License
Licensed under either of Apache License, Version 2.0 or MIT license at your option.