Please check the build logs for more information.
See Builds for ideas on how to fix a failed build, or Metadata for how to configure docs.rs builds.
If you believe this is docs.rs' fault, open an issue.
Flux Limiter
A high-performance rate limiter based on the Generic Cell Rate Algorithm (GCRA) with nanosecond precision and lock-free concurrent access.
Features
- Mathematically precise: Implements the GCRA algorithm with exact nanosecond timing
- High performance: Lock-free concurrent access using DashMap
- Generic client IDs: Works with any hashable client identifier (
String,IpAddr,u64, etc.) - Rich metadata: Returns detailed decision information for HTTP response construction
- Memory efficient: Automatic cleanup of stale client entries
- Robust error handling: Graceful handling of clock failures and configuration errors
- Testable: Clock abstraction enables deterministic testing
- Thread-safe: Safe to use across multiple threads
- Zero allocations: Efficient hot path with minimal overhead
Installation
Add this to your Cargo.toml:
[]
= "0.4.0"
Quick Start
use ;
// Create a rate limiter: 10 requests per second with burst of 5
let config = new;
let limiter = with_config.unwrap;
// Check if a request should be allowed
match limiter.check_request
Rate Limiting Decisions
The check_request() method returns a Result<FluxLimiterDecision, FluxLimiterError> with rich metadata:
Error Handling
Flux Limiter provides comprehensive error handling for robust production usage:
use FluxLimiterError;
match limiter.check_request
Error Types
FluxLimiterError::InvalidRate: Rate must be positive (configuration error)FluxLimiterError::InvalidBurst: Burst must be non-negative (configuration error)FluxLimiterError::ClockError: System time unavailable or inconsistent
Error Handling Strategies
For clock errors in production:
- Fail-open: Allow requests when rate limiter fails
- Fail-closed: Deny requests when rate limiter fails
- Fallback: Use alternative rate limiting (e.g., in-memory counter)
let fallback_decision = match limiter.check_request ;
Configuration
Builder Pattern
use FluxLimiterConfig;
let config = new
.rate // 100 requests per second
.burst; // Allow bursts of up to 50 requests
Rate and Burst Explained
- Rate: Sustained requests per second (must be > 0)
- Burst: Additional requests allowed in short bursts (must be ≥ 0)
- Total capacity: Approximately
1 + burstrequests can be made immediately
Example: With rate=10.0 and burst=5.0:
- Sustained rate: 10 requests per second (one every 100ms)
- Burst allowance: ~6 requests can be made immediately
- After burst: Limited to 10 req/sec sustained rate
Advanced Usage
Custom Client ID Types
use IpAddr;
// Use IP addresses as client identifiers
let config = new;
let limiter = with_config.unwrap;
let client_ip: IpAddr = "192.168.1.1".parse.unwrap;
match limiter.check_request
Memory Management
// Clean up clients that haven't been seen for 1 hour
let one_hour_nanos = 60 * 60 * 1_000_000_000u64;
if let Err = limiter.cleanup_stale_clients
// Or clean up based on rate interval
let threshold = limiter.rate as u64 * 100 * 1_000_000_000; // 100x rate interval
let _ = limiter.cleanup_stale_clients; // Ignore cleanup errors
Web Framework Integration
Example with Axum
use ;
use ;
use Arc;
async
Standard Rate Limit Headers
Flux Limiter provides all the metadata needed for standard HTTP rate limiting headers:
- X-RateLimit-Remaining: Use
decision.remaining_capacity - Retry-After: Use
decision.retry_after_seconds(when denied) - X-RateLimit-Reset: Convert
decision.reset_time_nanosto timestamp
Algorithm Details
Flux Limiter implements the Generic Cell Rate Algorithm (GCRA), which is mathematically equivalent to the token bucket algorithm but uses a different approach:
- Token Bucket: Tracks available tokens, refills over time
- GCRA: Tracks theoretical arrival time of next request
GCRA advantages:
- No background token refill processes
- Exact timing without floating-point precision loss
- Efficient state representation (one timestamp per client)
Performance Characteristics
- Memory: O(number of active clients)
- Time complexity: O(1) for
check_request()operations - Concurrency: Lock-free reads and writes via DashMap
- Precision: Nanosecond timing accuracy
- Throughput: Millions of operations per second
- Reliability: Graceful degradation on system clock issues
Cleanup Recommendations
Call cleanup_stale_clients() periodically to prevent memory growth:
// In a background task
spawn;
Configuration Validation
use ;
match new.validate
// Or use with_config which validates automatically
match with_config
Production Considerations
Monitoring and Alerting
// Example: Count clock errors for monitoring
use ;
static CLOCK_ERROR_COUNT: AtomicU64 = new;
match limiter.check_request
Graceful Degradation
Consider implementing circuit breaker patterns for persistent clock failures:
// Example: Skip rate limiting after consecutive failures
if consecutive_clock_failures > threshold
License
This project is licensed under the MIT License - see the License.txt file for details.
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.