Rater ๐
A blazingly fast, lock-free, thread-safe rate limiting library for Rust implementing the token bucket algorithm with optional per-IP rate limiting support.
โจ Features
- ๐ Lock-free Implementation - Uses atomic operations for thread-safe token management without mutex overhead
- โก High Performance - Cache-aligned structures and platform-specific optimizations (PAUSE on x86, YIELD on ARM)
- ๐ Adaptive Refill - Automatically adjusts refill rate under sustained pressure
- ๐ Per-IP Rate Limiting - Built-in IP-based rate limiter management with automatic cleanup
- ๐ Comprehensive Metrics - Real-time performance monitoring and health status tracking
- ๐ฏ Zero Dependencies - Minimal dependencies (only dashmap for IP management)
- ๐ฆ 100% Safe Rust - Unsafe code only for platform-specific CPU instructions
๐ฆ Installation
Add this to your Cargo.toml:
[]
= "0.1.0"
For all features including serialization support:
[]
= { = "0.1.0", = ["full"] }
๐ Quick Start
Basic Rate Limiting
use RateLimiter;
Per-IP Rate Limiting
use IpRateLimiterManager;
use IpAddr;
use Arc;
Using the Builder Pattern
use ;
๐ง Advanced Configuration
Custom Rate Limiting Strategies
use RateLimiterConfig;
// Per-second rate limiting
let config = per_second;
// Per-minute rate limiting
let config = per_minute;
// Custom configuration with burst capacity
let config = new // 500 max tokens, 50 refill rate, 1000ms interval
.with_burst_multiplier // Allow bursts up to 3x the normal rate
.with_ordering; // Strongest memory ordering
Monitoring and Metrics
use RateLimiter;
let limiter = new;
// Perform some operations
for _ in 0..50
// Get comprehensive metrics
let metrics = limiter.metrics;
println!;
println!;
println!;
// Get a detailed summary
println!;
IP Manager with Custom Cleanup Settings
use ;
use Arc;
let config = per_second;
let manager = new;
// Start a stoppable cleanup thread
let = manager.clone.start_stoppable_cleanup_thread;
// ... use the manager ...
// Stop the cleanup thread when done
stop_tx.send.unwrap;
handle.join.unwrap;
๐๏ธ Performance
Rater is designed for extreme performance in high-concurrency scenarios:
- Lock-free algorithm using atomic CAS operations
- Cache-aligned structures to prevent false sharing between CPU cores
- Platform-specific optimizations:
- x86_64: Uses PAUSE instruction for efficient spin-waiting
- ARM64: Uses YIELD instruction
- Bounded CAS retries to prevent infinite spinning under extreme contention
- Adaptive refill automatically reduces refill rate under sustained pressure
Benchmark
TODO
Benchmarks run on AMD Ryzen 9 5900X, 32GB RAM
๐๏ธ Architecture
Core Components
-
RateLimiter: Lock-free token bucket implementation
- Atomic token counter with platform-specific sizing (u64 on 64-bit, u32 on 32-bit)
- Adaptive refill mechanism
- Backpressure detection
-
IpRateLimiterManager: Per-IP rate limiting
- Concurrent hash map for IP tracking
- Automatic cleanup of inactive limiters
- Emergency cleanup under memory pressure
-
Metrics & Monitoring: Real-time performance tracking
- Success/rejection rates
- Pressure detection
- Health status monitoring
Memory Ordering Options
Choose the appropriate memory ordering for your use case:
use MemoryOrdering;
// Best performance, minimal guarantees
Relaxed
// Balanced performance and correctness (default)
AcquireRelease
// Strongest guarantees, lowest performance
Sequential
๐ Use Cases
- Web Services: Rate limit API endpoints per client IP
- Microservices: Implement circuit breakers and backpressure
- Game Servers: Prevent spam and DoS attacks
- IoT Gateways: Control device message rates
- Proxy Servers: Implement fair resource allocation
- Background Jobs: Throttle external API calls
๐ Examples
Check out the examples directory for more detailed usage:
- basic.rs - Simple rate limiting example
- ip_limiting.rs - Per-IP rate limiting with monitoring
๐งช Testing
Run the test suite:
# Run all tests
# Run with all features
# Run benchmarks
๐ Benchmarking
The library includes comprehensive benchmarks:
# Run all benchmarks
# Run specific benchmark
๐ค Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
๐ License
MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT)
๐ Acknowledgments
- Inspired by various rate limiting implementations in the Rust ecosystem
- Thanks to the Rust community for excellent tooling and documentation
Made with โค๏ธ by Khaled