Expand description
A comprehensive rate limiting library for Rust applications.
This library provides multiple rate limiting algorithms with a focus on performance, accuracy, and ease of use. All implementations are thread-safe and designed for high-concurrency scenarios.
Time is represented using abstract “ticks” — unit-less integers that typically map to nanoseconds, but can represent any monotonic unit you choose.
§Quick Start
use rate_guard_core::rate_limiters::TokenBucketCore;
// Capacity: 100 tokens
// Refill: 10 tokens every 5 ticks
let limiter = TokenBucketCore::new(100, 5, 10);
// Try to acquire 20 tokens at tick 0
match limiter.try_acquire_at(20, 0) {
Ok(()) => println!("Request allowed"),
Err(e) => println!("Request denied: {}", e),
}§Available Rate Limiting Algorithms
§Leaky Bucket
Tokens leak out at a constant rate, providing smooth traffic shaping:
let limiter = LeakyBucketCore::new(100, 10, 5); // leak 5 tokens every 10 ticks§Token Bucket
Allows bursts up to capacity while maintaining average rate:
let limiter = TokenBucketCore::new(100, 10, 5); // add 5 tokens every 10 ticks§Fixed Window Counter
Simple time-window based counting:
let limiter = FixedWindowCounterCore::new(100, 60); // 100 requests per 60 ticks§Sliding Window Counter
Accurate sliding window using multiple time buckets:
let limiter = SlidingWindowCounterCore::new(100, 10, 6); // 100 requests per 60 ticks§Approximate Sliding Window
Memory-efficient approximation using only two windows:
let limiter = ApproximateSlidingWindowCore::new(100, 60); // ~100 requests per 60 ticks§Core Concepts
§Time Representation
All algorithms use abstract “ticks” to represent time. You can map ticks to any unit
(e.g., milliseconds, nanoseconds). Internally, Tick is an unsigned integer (u64 or u128)
based on crate features.
§Error Handling
All rate limiters return AcquireResult which can indicate:
- Success — Request was allowed
ExceedsCapacity— Rate limit exceededContentionFailure— Lock contentionExpiredTick— Time went backwards or was reused
§Thread Safety
All rate limiters are thread-safe and use non-blocking locks. If a lock cannot
be acquired immediately, ContentionFailure is returned rather than blocking.
§Feature Flags
This crate supports selecting the internal tick precision:
tick_u64(default) —Tick = u64, supports ~584 years of nanosecond tickstick_u128—Tick = u128, supports extremely long durations or ultra-high precision
To use u128, compile with:
cargo build --no-default-features --features tick_u128Re-exports§
pub use types::Uint;
Modules§
- rate_
limiter_ core - Core trait for rate limiter algorithms.
- rate_
limiters - Core rate limiting algorithm implementations.
- types
- Unsigned integer type alias for rate limiter capacities and ticks.
Macros§
- other_
window - Toggles between window indices 0 and 1.
Enums§
- Rate
Limit Error - Error types for rate limiter operations.
Type Aliases§
- Acquire
Result - Result type for acquire operations.