request_rate_limiter/
limiter.rs

1//! Rate limiters for controlling request throughput.
2
3use std::{
4    fmt::Debug,
5    sync::{
6        atomic::{AtomicU64, Ordering},
7        Arc,
8    },
9    time::{Duration, Instant},
10};
11
12use async_trait::async_trait;
13use tokio::time::{sleep, timeout};
14
15use crate::algorithms::{RateLimitAlgorithm, RequestSample};
16
17type RequestCount = u64;
18type AtomicRequestCount = AtomicU64;
19
20/// A token representing permission to make a request.
21/// The token tracks when the request was started for timing measurements.
22#[derive(Debug)]
23pub struct Token {
24    start_time: Instant,
25}
26
27/// Controls the rate of requests over time.
28///
29/// Rate limiting is achieved by checking if a request is allowed based on the current
30/// rate limit algorithm. The limiter tracks request patterns and adjusts limits dynamically
31/// based on observed success/failure rates and response times.
32#[async_trait]
33pub trait RateLimiter: Debug + Sync {
34    /// Acquire permission to make a request. Waits until a token is available.
35    async fn acquire(&self) -> Token;
36
37    /// Acquire permission to make a request with a timeout. Returns a token if successful.
38    async fn acquire_timeout(&self, duration: Duration) -> Option<Token>;
39
40    /// Release the token and record the outcome of the request.
41    /// The response time is calculated from when the token was acquired.
42    async fn release(&self, token: Token, outcome: Option<RequestOutcome>);
43}
44
45/// A token bucket based rate limiter.
46///
47/// Cheaply cloneable.
48#[derive(Debug)]
49pub struct DefaultRateLimiter<T> {
50    algorithm: T,
51    tokens: Arc<AtomicRequestCount>,
52    last_refill: Arc<std::sync::Mutex<Instant>>,
53    requests_per_second: Arc<AtomicRequestCount>,
54    bucket_capacity: RequestCount,
55}
56
57/// A snapshot of the state of the rate limiter.
58///
59/// Not guaranteed to be consistent under high concurrency.
60#[derive(Debug, Clone, Copy)]
61pub struct RateLimiterState {
62    /// Current requests per second limit
63    requests_per_second: RequestCount,
64    /// Available tokens in the bucket
65    available_tokens: RequestCount,
66    /// Maximum bucket capacity
67    bucket_capacity: RequestCount,
68}
69
70/// Whether a request succeeded or failed, potentially due to overload.
71///
72/// Errors not considered to be caused by overload should be ignored.
73#[derive(Debug, Clone, Copy, PartialEq, Eq)]
74pub enum RequestOutcome {
75    /// The request succeeded, or failed in a way unrelated to overload.
76    Success,
77    /// The request failed because of overload, e.g. it timed out or received a 429/503 response.
78    Overload,
79    /// The request failed due to client error (4xx) - not related to rate limiting.
80    ClientError,
81}
82
83impl<T> DefaultRateLimiter<T>
84where
85    T: RateLimitAlgorithm,
86{
87    /// Create a rate limiter with a given rate limiting algorithm.
88    pub fn new(algorithm: T) -> Self {
89        let initial_rps = algorithm.requests_per_second();
90        let bucket_capacity = initial_rps; // Use the same value for bucket capacity
91
92        assert!(initial_rps >= 1);
93        Self {
94            algorithm,
95            tokens: Arc::new(AtomicRequestCount::new(bucket_capacity)),
96            last_refill: Arc::new(std::sync::Mutex::new(Instant::now())),
97            requests_per_second: Arc::new(AtomicRequestCount::new(initial_rps)),
98            bucket_capacity,
99        }
100    }
101
102    fn refill_tokens(&self) {
103        let now = Instant::now();
104        if let Ok(mut last_refill) = self.last_refill.try_lock() {
105            let elapsed = now.duration_since(*last_refill);
106            let tokens_to_add = (elapsed.as_secs_f64()
107                * self.requests_per_second.load(Ordering::Acquire) as f64)
108                as u64;
109
110            if tokens_to_add > 0 {
111                let current_tokens = self.tokens.load(Ordering::Acquire);
112                let new_tokens = (current_tokens + tokens_to_add).min(self.bucket_capacity);
113                self.tokens.store(new_tokens, Ordering::SeqCst);
114                *last_refill = now;
115            }
116        }
117    }
118
119    /// The current state of the rate limiter.
120    pub fn state(&self) -> RateLimiterState {
121        self.refill_tokens();
122        RateLimiterState {
123            requests_per_second: self.requests_per_second.load(Ordering::Acquire),
124            available_tokens: self.tokens.load(Ordering::Acquire),
125            bucket_capacity: self.bucket_capacity,
126        }
127    }
128}
129
130#[async_trait]
131impl<T> RateLimiter for DefaultRateLimiter<T>
132where
133    T: RateLimitAlgorithm + Sync + Debug,
134{
135    async fn acquire(&self) -> Token {
136        loop {
137            self.refill_tokens();
138
139            // Try to consume a token atomically
140            let current_tokens = self.tokens.load(Ordering::Acquire);
141            if current_tokens > 0 {
142                match self.tokens.compare_exchange_weak(
143                    current_tokens,
144                    current_tokens - 1,
145                    Ordering::Release,
146                    Ordering::Relaxed,
147                ) {
148                    Ok(_) => {
149                        return Token {
150                            start_time: Instant::now(),
151                        };
152                    }
153                    Err(_) => continue, // Retry on contention
154                }
155            } else {
156                // No tokens available, wait a bit before retrying
157                sleep(Duration::from_millis(1)).await;
158            }
159        }
160    }
161
162    async fn acquire_timeout(&self, duration: Duration) -> Option<Token> {
163        timeout(duration, self.acquire()).await.ok()
164    }
165
166    async fn release(&self, token: Token, outcome: Option<RequestOutcome>) {
167        let response_time = token.start_time.elapsed();
168
169        if let Some(outcome) = outcome {
170            let current_rps = self.requests_per_second.load(Ordering::Acquire);
171            let sample = RequestSample::new(response_time, current_rps, outcome);
172
173            let new_rps = self.algorithm.update(sample).await;
174            self.requests_per_second.store(new_rps, Ordering::Release);
175        }
176    }
177}
178
179impl RateLimiterState {
180    /// The current requests per second limit.
181    pub fn requests_per_second(&self) -> RequestCount {
182        self.requests_per_second
183    }
184    /// The number of available tokens in the bucket.
185    pub fn available_tokens(&self) -> RequestCount {
186        self.available_tokens
187    }
188    /// The maximum bucket capacity.
189    pub fn bucket_capacity(&self) -> RequestCount {
190        self.bucket_capacity
191    }
192}
193
194#[cfg(test)]
195mod tests {
196    use crate::{
197        algorithms::Fixed,
198        limiter::{DefaultRateLimiter, RateLimiter, RequestOutcome},
199    };
200    use std::time::Duration;
201
202    #[tokio::test]
203    async fn rate_limiter_allows_requests_within_limit() {
204        let limiter = DefaultRateLimiter::new(Fixed::new(10));
205
206        // Should allow first request
207        let token = limiter.acquire().await;
208
209        // Release with successful outcome
210        limiter.release(token, Some(RequestOutcome::Success)).await;
211    }
212
213    #[tokio::test]
214    async fn rate_limiter_waits_for_tokens() {
215        use std::sync::Arc;
216
217        let limiter = Arc::new(DefaultRateLimiter::new(Fixed::new(1)));
218
219        // Consume the only token
220        let token1 = limiter.acquire().await;
221
222        // Start acquiring second token (should wait)
223        let limiter_clone = Arc::clone(&limiter);
224        let acquire_task = tokio::spawn(async move { limiter_clone.acquire().await });
225
226        // Give it a moment to start waiting
227        tokio::time::sleep(Duration::from_millis(10)).await;
228
229        // Release the first token - this should allow the second acquire to complete
230        limiter.release(token1, Some(RequestOutcome::Success)).await;
231
232        // The second acquire should now complete
233        let token2 = acquire_task.await.unwrap();
234        limiter.release(token2, Some(RequestOutcome::Success)).await;
235    }
236}