k3d3 / leaky-bucket

A tokio-based leaky bucket rate limiter

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

A leaky-bucket rate limiter

Documentation Crates Actions Status

A token-based rate limiter based on the leaky bucket algorithm.

Usage

This library requires the user to add the following dependencies to use:

leaky-bucket = "0.7.1"

Example

use leaky_bucket::LeakyBucket;
use std::{error::Error, time::Duration};

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let rate_limiter = LeakyBucket::builder()
        .max(100)
        .refill_interval(Duration::from_secs(10))
        .refill_amount(100)
        .build()?;

    println!("Waiting for permit...");
    // should take about ten seconds to get a permit.
    rate_limiter.acquire_one().await?;
    println!("I made it!");

    Ok(())
}

Example with custom coordinator

Leaky buckets require coordination. By default, this will happen through a static coordinator spawned through tokio::spawn at first use. If you want to spawn the coordinator yourself, you can do the following with LeakyBuckets:

use leaky_bucket::LeakyBuckets;
use std::{error::Error, time::Duration};

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let mut buckets = LeakyBuckets::new();
    let coordinator = buckets.coordinate()?;
    // spawn the coordinate thread to refill the rate limiter.
    tokio::spawn(async move { coordinator.await.expect("coordinate thread errored") });

    let rate_limiter = buckets
        .rate_limiter()
        .max(100)
        .refill_interval(Duration::from_secs(10))
        .refill_amount(100)
        .build()?;

    println!("Waiting for permit...");
    // should take about ten seconds to get a permit.
    rate_limiter.acquire_one().await?;
    println!("I made it!");

    Ok(())
}

About

A tokio-based leaky bucket rate limiter

License:Apache License 2.0


Languages

Language:Rust 100.0%