Token-Bucket Rate Limiter (Rust)
Topics: concurrency, rate limiting
Problem
Implement a token-bucket limiter:
impl Limiter {
pub fn new(rps: u32, burst: u32) -> Self;
pub fn allow(&self) -> bool;
pub fn wait_timeout(&self, timeout: Duration) -> bool;
}
new(rps, burst) — the bucket holds up to burst tokens and refills at rps tokens/second. It
starts pre-filled to burst.
allow consumes a token and returns true if one is available right now, else false.
wait_timeout blocks until it consumes a token (returns true) or timeout elapses (false).
new(1, 5): allow() ×5 → true, then false // burst pre-filled
new(200, 1): allow() drains; wait_timeout(1s) → true (refills in ~5ms)
The Go version's Wait(ctx) is replaced here by wait_timeout(Duration) — same idea, with a
deadline instead of a context.
Hint: track tokens: f64 + a last: Instant behind a Mutex; lazily add elapsed * rps (capped at
burst) on each call.
Grading
Your solution.rs is compiled together with a trusted tests.rs (which include!s it) using
rustc --test. Only solution.rs is yours to edit.
Sign in to submit your solution.