r8limit
A dead simple Rust library for rate limiting.
Usage
In your Cargo.toml
:
[dependencies]
r8limit = "0.2"
In your code:
use std::time::Duration;
fn main() {
let mut limiter = r8limit::RateLimiter::new(3, Duration::from_secs(5));
println!("{}", limiter.attempt()); println!("{}", limiter.attempt()); println!("{}", limiter.attempt()); println!("{}", limiter.attempt()); }
Refill policies
The refill policy is what determines how the number of executions in an interval are refilled.
Full
By default, the refill policy is set to Full
. This means that every time the difference between now and the
start of the current window has reached or exceeded the specified interval, the number of executions is reset to
the maximum number of executions allowed during the interval.
use std::time::Duration;
use std::thread::sleep;
use crate::RateLimiter;
fn main() {
let mut limiter = RateLimiter::new(3, Duration::from_secs(1));
limiter.attempt(); limiter.attempt(); limiter.attempt(); limiter.attempt(); sleep(Duration::from_millis(500)); assert_eq!(limiter.attempt(), false); sleep(Duration::from_millis(500)); limiter.attempt(); limiter.attempt(); limiter.attempt(); limiter.attempt(); }
Gradual
Unlike the Full
refill policy, the Gradual
refill policy does not wait until the interval has completely elapsed
to refill the number of executions remaining.
use std::time::Duration;
use std::thread::sleep;
use crate::{RateLimiter, RefillPolicy};
fn main() {
let mut limiter = RateLimiter::new(2, Duration::from_millis(500)).with_refill_policy(RefillPolicy::Gradual);
limiter.attempt(); limiter.attempt(); limiter.attempt(); sleep(Duration::from_millis(250)); limiter.attempt(); limiter.attempt(); sleep(Duration::from_millis(500)); limiter.attempt(); limiter.attempt(); limiter.attempt(); }