Expand description
A throttling service that limits the number of attempts (hits) from an IP address within a specified time period.
§Example: Basic Rate Limiting
use std::time::Duration;
use cache_ro::Cache;
use throttle_ro::ThrottlesService;
// Create a cache instance (in-memory for this example)
let cache = Cache::new(cache_ro::CacheConfig {
persistent: false,
..Default::default()
}).unwrap();
// Create a throttling service for IP "127.0.0.1"
// allowing maximum 5 attempts per minute
let ip = "127.0.0.1".to_string();
let mut service = ThrottlesService::new(
ip,
5, // max attempts
Duration::from_secs(60), // time window
"api_rate_limit_" // cache key prefix
);
// Check if the IP is allowed to proceed
if service.can_go(&cache) {
// Record the attempt
service.hit(&cache);
println!("Request allowed");
// Process the request...
} else {
println!("Rate limit exceeded - please try again later");
// Return error or wait...
}
// You can also manually clear the throttle if needed
// service.remove(&cache);Structs§
- Throttles
Service - A service for throttling attempts from an IP address.