Skip to content

About

Thread-safe TokenBucket, SlidingWindow, and LeakyBucket rate limiters with real concurrency tests. Zero-dependency Rust.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

1 Commit

Folders and files

Repository files navigation

rs-ratelimit

Thread-safe, zero-dependency rate limiters for Rust: TokenBucket, SlidingWindow, and LeakyBucket.

Rate limiting is one of those things every service eventually needs — protecting an API from abuse, smoothing bursty traffic to a downstream dependency, capping how fast a worker pulls jobs off a queue. This crate implements the three most common rate-limiting algorithms directly against the Rust standard library (std::sync::Mutex, std::time::Instant), with no external dependencies at all.

This is a Rust port of the same rate-limiter design the author (kasapdev) has already built and shipped as standalone libraries in PHP, Java, and Go. The algorithms are conceptually identical across all four languages, but this version leans into what Rust does best: instead of relying on a language runtime's cooperative scheduling or external locking conventions, each limiter here is built on Arc<Mutex<_>> and enforces correctness under real OS-thread concurrency, verified by genuine multi-threaded tests (see Testing below) rather than being taken on faith.

Arc<Mutex<_>> was chosen deliberately over lock-free atomics: these algorithms need to update multiple related fields (a token count and a timestamp, a queue of timestamps, a water level and a timestamp) as a single atomic step. A mutex makes that trivially correct; hand-rolled lock-free atomics would be a much larger surface for subtle bugs in exchange for a performance gain rate limiters rarely need. Correctness over micro-optimization.

Usage

Add it to your Cargo.toml:

[dependencies]
rs-ratelimit = "1.0.0"

TokenBucket

Allows bursts up to a fixed capacity, refilling continuously at a configured rate.

use rs_ratelimit::TokenBucket;

// Capacity of 5 tokens, refilling at 2 tokens/sec.
let bucket = TokenBucket::new(5, 2.0).unwrap();

for _ in 0..5 {
    assert!(bucket.try_acquire()); // bucket starts full
}
assert!(!bucket.try_acquire()); // exhausted until it refills

SlidingWindow

Allows at most N requests within any rolling time window.

use rs_ratelimit::SlidingWindow;
use std::time::Duration;

// At most 3 requests per rolling 1-second window.
let limiter = SlidingWindow::new(3, Duration::from_secs(1)).unwrap();

assert!(limiter.try_acquire());
assert!(limiter.try_acquire());
assert!(limiter.try_acquire());
assert!(!limiter.try_acquire()); // 4th request in the same window is denied

LeakyBucket

Smooths bursts by draining ("leaking") at a constant rate; a request is only admitted if there's room after accounting for the leak.

use rs_ratelimit::LeakyBucket;

// Capacity of 5 units, leaking at 2 units/sec.
let bucket = LeakyBucket::new(5, 2.0).unwrap();

for _ in 0..5 {
    assert!(bucket.try_acquire()); // bucket starts empty, has room
}
assert!(!bucket.try_acquire()); // full until it drains

Sharing a limiter across threads

Every limiter is Send + Sync and designed to be wrapped in Arc and shared across threads directly — no external locking needed:

use rs_ratelimit::TokenBucket;
use std::sync::Arc;
use std::thread;

let limiter = Arc::new(TokenBucket::new(10, 5.0).unwrap());

let mut handles = Vec::new();
for worker_id in 0..8 {
    let limiter = Arc::clone(&limiter);
    handles.push(thread::spawn(move || {
        if limiter.try_acquire() {
            println!("worker {worker_id} got a token");
        } else {
            println!("worker {worker_id} was throttled");
        }
    }));
}
for handle in handles {
    handle.join().unwrap();
}

How it works

Token bucket

The bucket starts full with capacity tokens. Every call to try_acquire() first computes elapsed time since the last refill (Instant::now() - last_refill), adds elapsed_secs * refill_rate tokens (capped at capacity), and only then checks whether at least one token is available to consume. This "lazy refill on access" approach means there's no background thread or timer — the bucket's state is always brought up to date exactly when it's checked, using genuine wall-clock arithmetic against std::time::Instant.

Sliding window

Each accepted request's timestamp is pushed onto a VecDeque<Instant>. On every call, timestamps older than window are popped from the front of the queue (they're always in order, since they're pushed in order, so eviction is an O(1)-amortized front-trim rather than a full scan). The request is admitted only if fewer than max_requests timestamps remain after eviction. Because the window "slides" continuously with real time rather than resetting at fixed boundaries, it avoids the classic fixed-window bug where two bursts of max_requests could land back-to-back around a window edge and double the effective rate.

Leaky bucket

The bucket tracks a level (how full it currently is) and last_leak timestamp. On each call, elapsed time since the last check is used to drain the bucket (level -= elapsed_secs * leak_rate, floored at 0), and only then is a new unit added if level + 1 <= capacity. Where a token bucket allows an instant burst up to full capacity, a leaky bucket enforces a steadier outflow, because the bucket must have drained enough room before each new admission once it's full.

Thread safety

All three limiters store their mutable state (token counts, timestamp queues, water levels — always paired with the Instant they were last updated against) inside a single std::sync::Mutex. Every try_acquire() call performs its entire read-refill/evict-check-write sequence while holding that one lock, so the whole operation is atomic with respect to every other thread calling into the same limiter. A limiter instance is meant to be shared as Arc<TheLimiter>; there is no scenario where two threads can each observe "capacity available" for the same unit of capacity and both be admitted — one will always see the other's update first. A poisoned lock (from a panic while another thread held it) does not crash the limiter: the standard .lock().unwrap_or_else(|e| e.into_inner()) pattern recovers the inner state, since none of these limiters' invariants can be left in an unsafe condition by a panic mid-update.

Testing

Beyond ordinary single-threaded correctness tests (denies once exhausted, allows again after enough real time passes for refill/drain/window-roll), each limiter has a genuine concurrency test that is the core proof of thread safety:

  1. A limiter is constructed with a small, precisely known capacity/rate.
  2. It's wrapped in Arc and shared across 16 real std::thread workers.
  3. Each thread calls try_acquire() 200 times as fast as possible — far more than the limiter could ever grant — and counts its own local successes.
  4. After .join()-ing every thread, the successes are summed via a shared AtomicUsize.
  5. The test asserts the total successes across every thread never exceed a mathematically computed upper bound: the limiter's capacity, plus whatever could have refilled/drained during the test's measured wall-clock elapsed time, plus a generous fixed slack to absorb scheduler jitter on slow or loaded CI machines.

This is a real multi-threaded test, not a simulated or sequential one — it exercises actual OS-level thread contention on shared state. If the internal Mutex were removed (or the refill/check/consume sequence were split into separate non-atomic steps), two threads could each observe "capacity available" for the same slot and both be admitted, which this test would catch as an observed total above the computed bound. Bounds are deliberately generous (not "assume zero elapsed time") specifically so the tests are reliable under CI load rather than flaky, while still being tight enough to catch a broken lock.

Run the full suite (including doctests) with:

cargo test

License

MIT — see LICENSE.

About

Thread-safe TokenBucket, SlidingWindow, and LeakyBucket rate limiters with real concurrency tests. Zero-dependency Rust.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages