#rate-limiting #rate #limit #send-sync

nightly gcra

A basic implementation of GCRA algorithm for rate limiting

9 unstable releases (3 breaking)

0.4.0 Mar 10, 2023
0.3.5 Jan 28, 2023
0.3.4 Oct 15, 2022
0.3.2 Jul 20, 2022
0.1.0 Jun 12, 2022

#568 in Algorithms

Download history 13666/week @ 2023-12-18 16/week @ 2023-12-25 3439/week @ 2024-01-01 3911/week @ 2024-01-08 3409/week @ 2024-01-15 7541/week @ 2024-01-22 4199/week @ 2024-01-29 5984/week @ 2024-02-05 7383/week @ 2024-02-12 1442/week @ 2024-02-19 8300/week @ 2024-02-26 2462/week @ 2024-03-04 7015/week @ 2024-03-11 5876/week @ 2024-03-18 11134/week @ 2024-03-25 12039/week @ 2024-04-01

36,068 downloads per month

MIT license

33KB
708 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::{GcraState, RateLimit};

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 user_state = GcraState::default();
  assert!(user_state.check_and_modify(&rate_limit, 1).is_ok());
  assert!(
      user_state.check_and_modify(&rate_limit, 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–7MB
~22K SLoC