Expand description
Β§Rater - High-Performance Rate Limiter for Rust
A blazing-fast, lock-free rate limiting library that helps you control the flow of requests in your application. Think of it as a traffic controller that ensures your system doesnβt get overwhelmed by too many requests at once.
Β§What is Rate Limiting?
Rate limiting is like having a bouncer at a club - it controls how many requests can enter your system within a specific time period. This prevents abuse, ensures fair usage, and protects your services from being overwhelmed.
Β§The Token Bucket Algorithm
This library uses the token bucket algorithm, which works like a vending machine:
Token Bucket Visualization:
Time 0: [πͺπͺπͺπͺπͺ] (5 tokens available)
Request 1: [πͺπͺπͺπͺ] β
(takes 1 token)
Request 2: [πͺπͺπͺ] β
(takes 1 token)
Time +1s: [πͺπͺπͺπͺπͺ] (refilled to max)
Request 3: [πͺπͺπͺπͺ] β
(takes 1 token)- Tokens = Permission to make a request
- Bucket = Container holding a limited number of tokens
- Refill = Tokens are added back at a steady rate
Β§Features
- π Lock-free Implementation - Multiple threads can use it simultaneously without blocking
- β‘ Blazing Fast - Optimized for your CPU architecture (uses PAUSE on Intel, YIELD on ARM)
- π Smart Refilling - Automatically adjusts when under heavy load
- π Per-IP Limiting - Different limits for different users/IPs
- π Real-time Metrics - Monitor performance and detect issues
- π‘οΈ Thread-Safe - Safe to share across threads without extra synchronization
Β§Quick Start
Β§Basic Rate Limiting
use rater::RateLimiter;
// Create a rate limiter:
// - 100 tokens maximum capacity (burst limit)
// - Refills 10 tokens every second
let limiter = RateLimiter::new(100, 10);
// Try to process a request
if limiter.try_acquire() {
println!("β
Request approved - processing...");
// Your request handling code here
} else {
println!("β Rate limited - try again later");
// Return 429 Too Many Requests
}Β§Advanced Usage with Builder Pattern
use rater::{RateLimiterBuilder, MemoryOrdering};
let limiter = RateLimiterBuilder::new()
.max_tokens(1000) // Maximum burst size
.refill_rate(100) // Tokens per interval
.refill_interval_ms(1000) // Refill every second
.memory_ordering(MemoryOrdering::AcquireRelease) // Memory consistency
.build();
// Acquire multiple tokens at once (for expensive operations)
if limiter.try_acquire_n(5) {
println!("Acquired 5 tokens for expensive operation");
}Β§Per-IP Rate Limiting
use rater::{IpRateLimiterManager, RateLimiterConfig};
use std::net::IpAddr;
// Create a manager that handles rate limiting per IP address
let config = RateLimiterConfig::per_second(10); // 10 requests per second per IP
let manager = IpRateLimiterManager::new(config);
// In your request handler:
let client_ip: IpAddr = "192.168.1.100".parse().unwrap();
if manager.try_acquire(client_ip) {
// Process request
} else {
// Rate limit this specific IP
}Β§Architecture Overview
βββββββββββββββββββββββββββ
β Your Application β
ββββββββββββ¬βββββββββββββββ
β
ββββββββββββΌβββββββββββββββ
β Rate Limiter API β
ββββββββββββββββββββββββββββ€
β β’ try_acquire() β
β β’ try_acquire_n() β
β β’ metrics() β
ββββββββββββ¬ββββββββββββββββ
β
ββββββββββββββββ΄ββββββββββββββββ
β β
ββββββββββββΌβββββββββββ βββββββββββββΌβββββββββββ
β Token Bucket β β IP Manager β
βββββββββββββββββββββββ€ ββββββββββββββββββββββββ€
β β’ Atomic tokens β β β’ Per-IP limiters β
β β’ Auto refill β β β’ Auto cleanup β
β β’ Lock-free CAS β β β’ LRU eviction β
βββββββββββββββββββββββ ββββββββββββββββββββββββΒ§Performance Characteristics
| Operation | Time Complexity | Space Complexity |
|---|---|---|
| try_acquire() | O(1)* | O(1) |
| try_acquire_n() | O(1)* | O(1) |
| refill | O(1)* | O(1) |
| metrics | O(1) | O(1) |
*Amortized constant time with bounded retries under contention
Β§Common Use Cases
- API Rate Limiting - Prevent API abuse and ensure fair usage
- Database Protection - Limit queries to prevent overload
- Microservice Communication - Control inter-service request rates
- Background Job Processing - Throttle job execution rates
- Resource Access Control - Limit access to expensive resources
Β§Thread Safety
All types are thread-safe and can be shared across threads:
RateLimiter- Safe to share viaArc<RateLimiter>IpRateLimiterManager- Safe to share viaArc<IpRateLimiterManager>
Β§Memory Ordering
Choose the right memory ordering for your use case:
Relaxed- Fastest, use when exact ordering doesnβt matterAcquireRelease- Balanced (default), ensures proper synchronizationSequential- Strongest guarantees, use when strict ordering is critical
Β§Examples
See the examples/ directory for complete examples:
basic.rs- Simple rate limitingip_limiting.rs- Per-IP rate limiting with cleanup
Β§Safety
This crate uses unsafe code only for:
- Platform-specific CPU pause instructions (for efficient spinning)
- Cache alignment optimizations (to prevent false sharing)
All unsafe code is thoroughly tested and documented.
ModulesΒ§
- prelude
- Prelude module for convenient imports.
StructsΒ§
- IpRate
Limiter Manager - IP-based rate limiting manager for per-client limits Manager for per-IP rate limiting.
- Manager
Stats - IP-based rate limiting manager for per-client limits Statistics for the IP rate limiter manager.
- Rate
Limiter - Core rate limiter implementing the token bucket algorithm Lock-free token bucket rate limiter.
- Rate
Limiter Builder - Builder pattern for creating rate limiters with custom configuration.
- Rate
Limiter Config - Configuration types for customizing rate limiter behavior Configuration for rate limiter instances.
- Rate
Limiter Metrics - Metrics and health monitoring for observability Comprehensive metrics for rate limiter performance analysis.
EnumsΒ§
- Health
Status - Metrics and health monitoring for observability Health status indicator for the rate limiter.
- Memory
Ordering - Configuration types for customizing rate limiter behavior Memory ordering strategy for atomic operations.
ConstantsΒ§
FunctionsΒ§
- cpu_
relax - Utility functions for time and CPU optimizations CPU-specific relaxation hint for spin loops.
- current_
time_ ms - Utility functions for time and CPU optimizations Returns the current time in milliseconds since UNIX epoch.
- current_
time_ ns - Utility functions for time and CPU optimizations Returns the current time in nanoseconds since UNIX epoch.
- current_
time_ us - Utility functions for time and CPU optimizations Returns the current time in microseconds since UNIX epoch.
Type AliasesΒ§
- Shared
IpManager - An IP rate limiter manager wrapped in
Arcfor convenient thread-safe sharing. - Shared
Rate Limiter - A rate limiter wrapped in
Arcfor convenient thread-safe sharing.