Last active
November 15, 2022 08:14
-
-
Save nazmulidris/ebeeef70ef149a1286c5eed13e83cbad to your computer and use it in GitHub Desktop.
Snippet for impl rate limiter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// Playground link: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=7f2ff17ff7ae239924d11698d12a69f9 | |
mod rate_limiter { | |
#[test] | |
fn test() { | |
const MAX_REQ_ALLOWED_IN_WINDOW: usize = 2; | |
const WINDOW_SIZE_MS: usize = 1000; | |
#[derive(Debug, /* deep copy support */ Clone, /* deep equality support */ PartialEq)] | |
enum RateLimitCheck { | |
Approve, | |
Reject, | |
} | |
fn is_ts_in_window(ts: usize, new_req_time_ms: usize) -> bool { new_req_time_ms - ts < WINDOW_SIZE_MS } | |
fn check_rate_limit(new_req_ts: usize, vec_success_ts: &mut Vec<usize>) -> RateLimitCheck { | |
// How many transactions have already been allowed in the last WINDOWS_SIZE_MS? | |
let num_previously_allowed_in_window: usize = { | |
let mut count = 0; | |
for ts in vec_success_ts.iter().rev() { | |
if is_ts_in_window(*ts, new_req_ts) { | |
count += 1; | |
} | |
} | |
count | |
}; | |
// Reject or Approve? | |
if num_previously_allowed_in_window < MAX_REQ_ALLOWED_IN_WINDOW { | |
vec_success_ts.push(new_req_ts); | |
RateLimitCheck::Approve | |
} else { | |
RateLimitCheck::Reject | |
} | |
} | |
fn main() { | |
let mut vec_success_ts: Vec<usize> = vec![1000, 1500, 2000]; | |
assert_eq!(check_rate_limit(2_100, &mut vec_success_ts), RateLimitCheck::Reject); | |
assert_eq!(check_rate_limit(2_500, &mut vec_success_ts), RateLimitCheck::Approve); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment