15 releases (4 breaking)

0.5.2 Feb 17, 2022
0.5.1 Dec 26, 2021
0.4.0 Dec 26, 2021
0.3.2 Sep 23, 2021
0.1.4 Jan 20, 2021

#698 in Network programming

Download history 549/week @ 2023-12-14 410/week @ 2023-12-21 332/week @ 2023-12-28 441/week @ 2024-01-04 659/week @ 2024-01-11 576/week @ 2024-01-18 500/week @ 2024-01-25 457/week @ 2024-02-01 517/week @ 2024-02-08 498/week @ 2024-02-15 436/week @ 2024-02-22 483/week @ 2024-02-29 466/week @ 2024-03-07 441/week @ 2024-03-14 339/week @ 2024-03-21 240/week @ 2024-03-28

1,560 downloads per month
Used in 3 crates (via rosu-v2)

MIT/Apache

31KB
485 lines

leaky-bucket-lite

docs badge crates badge actions badge

A token-based rate limiter based on the leaky bucket algorithm, mainly a lazy reimplementation of udoprog's leaky-bucket with less dependencies and overhead.

If the tokens are already available, the acquisition will be instant through a fast path, and the acquired number of tokens will be added to the bucket.

If they aren't, the task that tried to acquire the tokens will be suspended until the required number of tokens has been added.

Usage

Add the following to your Cargo.toml:

leaky-bucket-lite = "0.4"

Features

leaky-bucket-lite provides 3 implementations:

For potential performance increase with sync-threadsafe or tokio using parking_lot's locking objects, enable the parking_lot feature.

Example

use leaky_bucket_lite::LeakyBucket;
use std::time::Duration;

#[tokio::main]
async fn main() {
    let rate_limiter = LeakyBucket::builder()
        .max(5)
        .tokens(0)
        .refill_interval(Duration::from_secs(1))
        .refill_amount(1)
        .build();

    println!("Waiting for permit...");
    // should take about 5 seconds to acquire.
    rate_limiter.acquire(5).await;
    println!("I made it!");
}

Dependencies

~2–9MB
~49K SLoC