#rate-limiting #tokio #rate #async-context #limiting #async #sliding-window

async-rate-limit

Common traits for rate limiting and implementations in async contexts

2 releases

0.0.4 Mar 8, 2024
0.0.3 Oct 4, 2023

#405 in Asynchronous

Download history 8/week @ 2024-02-18 4/week @ 2024-02-25 96/week @ 2024-03-03 27/week @ 2024-03-10 23/week @ 2024-03-17 2/week @ 2024-03-24 28/week @ 2024-03-31 10/week @ 2024-04-07

65 downloads per month
Used in kraken-async-rs

MIT license

26KB
360 lines

async-rate-limit

A basic Tokio rate-limiting library providing two traits and common implementations.

badge License: MIT

Usage:

use tokio::time::{Instant, Duration};
use async_rate_limit::limiters::VariableCostRateLimiter;
use async_rate_limit::sliding_window::SlidingWindowRateLimiter;

#[tokio::main]
async fn main() -> () {
    let mut limiter = SlidingWindowRateLimiter::new(Duration::from_secs(1), 5);
    
    for _ in 0..3 {
        // these will proceed immediately, spending 3 units
        get_lite(&mut limiter).await;
    }
    // 3/5 units are spent, so this will wait for ~1s to proceed since it costs another 3
    get_heavy(&mut limiter).await;
}

// note the use of the `VariableCostRateLimiter` trait, rather than the direct type
async fn get_lite<T>(limiter: &mut T) where T: VariableCostRateLimiter {
    limiter.wait_with_cost(1).await;
    println!("Lite: {:?}", Instant::now());
}

async fn get_heavy<T>(limiter: &mut T) where T: VariableCostRateLimiter {
    limiter.wait_with_cost(3).await;
    println!("Heavy: {:?}", Instant::now());
}

Dependencies

~2.4–9.5MB
~57K SLoC