#rate-limiting #rate #limiter #limit

gcra

A basic implementation of GCRA algorithm for rate limiting

12 unstable releases (5 breaking)

0.6.0 Aug 1, 2024
0.5.0 May 28, 2024
0.4.1 May 10, 2024
0.4.0 Mar 10, 2023
0.3.2 Jul 20, 2022

#176 in Algorithms

Download history 8563/week @ 2024-08-18 13424/week @ 2024-08-25 7084/week @ 2024-09-01 9406/week @ 2024-09-08 7162/week @ 2024-09-15 8735/week @ 2024-09-22 16629/week @ 2024-09-29 3137/week @ 2024-10-06 13857/week @ 2024-10-13 7492/week @ 2024-10-20 11516/week @ 2024-10-27 1578/week @ 2024-11-03 26427/week @ 2024-11-10 27411/week @ 2024-11-17 4794/week @ 2024-11-24 20011/week @ 2024-12-01

78,727 downloads per month

MIT license

36KB
779 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 std::sync::Arc;
use gcra::{GcraError, RateLimit, RateLimiter};

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

    rate_limiter.check("key", &rate_limit, 1).await?;
    rate_limiter.check("key", &rate_limit, 1).await?;

    match rate_limiter.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.2–5.5MB
~21K SLoC