#rate-limiting #rate #limit

nightly gcra

A basic implementation of GCRA algorithm for rate limiting

10 releases

new 0.4.1 May 10, 2024
0.4.0 Mar 10, 2023
0.3.5 Jan 28, 2023
0.3.4 Oct 15, 2022
0.1.0 Jun 12, 2022

#170 in Algorithms

Download history 7538/week @ 2024-01-21 4192/week @ 2024-01-28 5985/week @ 2024-02-04 7390/week @ 2024-02-11 1401/week @ 2024-02-18 8328/week @ 2024-02-25 2473/week @ 2024-03-03 7012/week @ 2024-03-10 5873/week @ 2024-03-17 11140/week @ 2024-03-24 11888/week @ 2024-03-31 2586/week @ 2024-04-07 4120/week @ 2024-04-14 4255/week @ 2024-04-21 4762/week @ 2024-04-28 2183/week @ 2024-05-05

15,653 downloads per month

MIT license

35KB
774 lines

Build Status License Documentation crates.io

GCRA: A basic implementation

Library which implements the core GCRA functionality in rust.

Features

  • rate-limiter a LRU + expiring rate limiter. Implements Send + Sync so can be used asynchronously.

Usage

use gcra::{RateLimit, RatelimitGuard};

fn check_rate_limit() {
    const LIMIT: u32 = 1;
    // Create a rate limit that allows `1/1s`
    let rate_limit = RateLimit::per_sec(LIMIT);
    let mut rate_limit_guard = RateLimitGuard::new_state(rate_limit);

    assert!(rate_limit_guard.check_and_modify(1).is_ok());
    assert!(
        rate_limit_guard.check_and_modify(1).is_err(),
        "We should be over the limit now"
    );
}

With rate-limiter

use gcra::{GcraError, RateLimit, RateLimiter};

#[tokio::main]
async fn main() -> Result<(), GcraError> {
    let rate_limit = RateLimit::per_sec(2);
    let mut rl = RateLimiter::new(4);

    rl.check("key", rate_limit.clone(), 1).await?;
    rl.check("key", rate_limit.clone(), 1).await?;

    match rl.check("key", rate_limit.clone(), 1).await {
        Err(GcraError::DeniedUntil { next_allowed_at }) => {
            print!("Denied: Request next at {:?}", next_allowed_at);
            Ok(())
        }
        unexpected => panic!("Opps something went wrong! {:?}", unexpected),
    }
}

Dependencies

~0.3–6MB
~21K SLoC