An adaptive rate limiting library for Rust using AIMD (Additive Increase Multiplicative Decrease) algorithm. This library dynamically adjusts rate limits based on system health metrics like latency, error rates, and queue utilization.
- Adaptive Rate Limiting: Automatically adjusts limits based on system health
- AIMD Algorithm: Proven congestion control algorithm (used in TCP)
- Health Metrics: Tracks latency percentiles, error rates, and queue depth
- Async/Await: Built on Tokio for efficient async operations
- Configurable: Flexible configuration for different use cases
- Zero-cost Abstractions: Minimal overhead when not under load
- HTTP Clients: Rate limit API calls to external services
- Database Connection Pools: Adapt to database load
- Message Queues: Control message processing rate
- WebSocket Connections: Manage connection and message rates
- Microservices: Implement backpressure between services
- Load Testing: Gradually increase load while monitoring health
Add this to your Cargo.toml:
[dependencies]
arli = "0.1"use arli::{AdaptiveRateLimiter, AimdConfig};
use std::time::Duration;
#[tokio::main]
async fn main() {
// Create an adaptive rate limiter with AIMD configuration
let limiter = AdaptiveRateLimiter::new(AimdConfig {
initial_rate: 100.0, // Start at 100 req/sec
min_rate: 10.0, // Never go below 10 req/sec
max_rate: 1000.0, // Cap at 1000 req/sec
increase_step: 10.0, // Add 10 req/sec on success
decrease_factor: 0.5, // Halve rate on congestion
adjustment_interval: Duration::from_secs(5),
..Default::default()
});
// Acquire a permit before making a request
limiter.acquire_one().await;
// Make your request...
let start = std::time::Instant::now();
let result = make_request().await;
let latency = start.elapsed();
// Record the result for adaptive adjustment
if result.is_ok() {
limiter.record_success(latency).await;
} else {
limiter.record_failure(arli::ErrorType::Error).await;
}
}
async fn make_request() -> Result<(), Box<dyn std::error::Error>> {
// Your request logic here
Ok(())
}use arli::AimdConfig;
use std::time::Duration;
let config = AimdConfig {
// Rate limits
initial_rate: 100.0, // Starting rate (requests/second)
min_rate: 10.0, // Minimum rate limit
max_rate: 1000.0, // Maximum rate limit
// Adjustment parameters
increase_step: 10.0, // Additive increase per interval
decrease_factor: 0.5, // Multiplicative decrease factor (0.0-1.0)
adjustment_interval: Duration::from_secs(5), // How often to adjust
backoff_period: Duration::from_secs(10), // Wait period after decrease
initialization_period: Duration::from_secs(30), // Warmup period
// Health thresholds for triggering decrease
max_error_rate: 0.05, // 5% error rate threshold
max_timeout_rate: 0.02, // 2% timeout rate threshold
latency_threshold_multiplier: 2.0, // Max latency vs baseline
max_queue_utilization: 0.9, // 90% queue utilization threshold
// Target thresholds for allowing increase
target_error_rate: 0.01, // 1% error rate target
target_latency_multiplier: 1.2, // Target latency vs baseline
target_queue_utilization: 0.7, // 70% queue utilization target
};The library implements the AIMD (Additive Increase Multiplicative Decrease) algorithm:
- Additive Increase: When the system is healthy, gradually increase the rate limit
- Multiplicative Decrease: When congestion is detected, aggressively decrease the rate limit
This approach is proven in TCP congestion control and provides stable, efficient rate limiting.
Initial State: rate = initial_rate
Every adjustment_interval:
if system_healthy:
rate = min(rate + increase_step, max_rate) // Additive increase
else:
rate = max(rate * decrease_factor, min_rate) // Multiplicative decrease
System is considered unhealthy if:
- Error rate > max_error_rate
- Timeout rate > max_timeout_rate
- P99 latency > baseline * latency_threshold_multiplier
- Queue utilization > max_queue_utilization
The rate limiter operates through these states:
Initializing → Stable: After initialization_period
Stable → BackingOff: When congestion detected (error/latency/queue threshold exceeded)
BackingOff → Recovering: After backoff_period
Recovering → Stable: On successful increase
The limiter tracks several health metrics:
- Latency Percentiles (P50, P95, P99): Monitor request latency distribution
- Error Rate: Track the percentage of failed requests
- Timeout Rate: Track requests that exceed timeout thresholds
- Queue Depth: Monitor backlog of pending requests
- Connection Failures: Track connection-level failures
The limiter adjusts rates based on:
if error_rate > threshold || latency > max_latency || queue_full {
// Decrease rate multiplicatively
new_rate = current_rate * decrease_factor
} else if all_metrics_healthy {
// Increase rate additively
new_rate = current_rate + increase_step
}use arli::{AdaptiveRateLimiter, AimdConfig};
let limiter = AdaptiveRateLimiter::new(AimdConfig::default());
loop {
// Wait for permission
limiter.acquire_one().await;
// Make request
match make_api_call().await {
Ok(response) => {
limiter.record_success(response.latency).await;
}
Err(e) => {
limiter.record_failure(ErrorType::Error).await;
}
}
}use arli::{AdaptiveRateLimiter, AimdConfig};
let limiter = AdaptiveRateLimiter::new(AimdConfig::default());
// Spawn a task to periodically check metrics
tokio::spawn({
let limiter = limiter.clone();
async move {
loop {
tokio::time::sleep(Duration::from_secs(10)).await;
let metrics = limiter.current_metrics().await;
println!("Current rate: {:.2} req/sec", limiter.current_rate().await);
println!("P95 latency: {:.2}ms", metrics.p95_latency_ms);
println!("Error rate: {:.2}%", metrics.error_rate * 100.0);
}
}
});let config = AimdConfig {
backoff_period: Duration::from_secs(10), // Wait 10s after decrease
decrease_factor: 0.5, // Halve rate on congestion
max_error_rate: 0.05, // Trigger on 5% errors
..Default::default()
};
let limiter = AdaptiveRateLimiter::new(config);
// The limiter will automatically decrease rate when thresholds exceeded
// and wait for backoff_period before allowing increases againYou can implement custom logic to evaluate system health:
let limiter = AdaptiveRateLimiter::new(config);
// Get current metrics
let metrics = limiter.current_metrics().await;
// Implement custom health evaluation
let is_healthy = metrics.p99_latency_ms < 200.0
&& metrics.error_rate < 0.01
&& metrics.queue_utilization < 0.5;
if !is_healthy {
// Take custom action
limiter.record_failure(ErrorType::Error).await;
}Use different limiters for different resources:
// Fast operations
let fast_limiter = AdaptiveRateLimiter::new(AimdConfig {
initial_rate: 1000.0,
target_latency_ms: 50.0,
..Default::default()
});
// Slow operations
let slow_limiter = AdaptiveRateLimiter::new(AimdConfig {
initial_rate: 10.0,
target_latency_ms: 1000.0,
..Default::default()
});The adaptive rate limiter is designed for high performance:
- Lock-free metrics: Uses atomic operations for counters
- Minimal allocations: Reuses buffers for latency tracking
- Async-first: Built on Tokio for efficient async operations
- Low overhead: < 1μs overhead per request when healthy
Run the test suite:
cargo testRun examples:
cargo run --example basic
cargo run --example adaptiveContributions are welcome! Please feel free to submit a Pull Request.
This project is MIT-0 licensed for code and CC0-1.0 licensed for non-code content - See LICENSE file for details.
"arli" stands for Adaptive Rate Limiter.