Skip to main content

RedisRateLimiter

Struct RedisRateLimiter 

Source
pub struct RedisRateLimiter { /* private fields */ }
Expand description

A distributed, fixed-window rate limiter backed by a Redis server.

RateLimiter only protects a single process: two rws instances behind a load balancer each track their own in-memory counters, so the effective limit for a client doubles (or worse) as replicas scale out. RedisRateLimiter keys the counter on a shared Redis server instead, so every instance enforces the same budget.

Unlike RateLimiter’s sliding window (a deque of timestamps), this uses a fixed-window counter: key’s count lives under one Redis key with a TTL equal to the window length, incremented atomically via INCR. This is the standard distributed rate-limiting pattern — Redis guarantees INCR is atomic across concurrent callers, so counters stay correct even under heavy concurrent load from multiple rws processes. The tradeoff versus a sliding window: a client can burst up to 2x max_requests across a window boundary (once near the end of one window, once at the start of the next).

Cloning is cheap — all clones share the same underlying TCP connection (one persistent connection per RedisRateLimiter instance).

§Example

use rust_web_server::rate_limit::RedisRateLimiter;

let limiter = RedisRateLimiter::new("127.0.0.1:6379", None, 100, 60); // 100 req / 60s

match limiter.check("192.168.1.1") {
    Ok(true) => { /* process request */ }
    Ok(false) => { /* return 429 Too Many Requests */ }
    Err(e) => { /* Redis unreachable — decide fail-open vs fail-closed */ }
}

Implementations§

Source§

impl RedisRateLimiter

Source

pub fn new( addr: impl Into<String>, password: Option<String>, max_requests: u32, window_secs: u64, ) -> Self

Create a limiter that connects to addr (e.g. "127.0.0.1:6379"), allowing max_requests per window_secs-second window. password is passed to Redis AUTH if Some.

Source

pub fn from_env() -> Self

Build a limiter from environment variables:

  • RWS_REDIS_HOST (default 127.0.0.1)
  • RWS_REDIS_PORT (default 6379)
  • RWS_REDIS_PASSWORD (optional)
  • RWS_CONFIG_RATE_LIMIT_MAX_REQUESTS (default 1000)
  • RWS_CONFIG_RATE_LIMIT_WINDOW_SECS (default 60)
Source

pub fn set_limits(&self, max_requests: u32, window_secs: u64)

Update the limits on a live limiter without restarting.

Source

pub fn check(&self, key: &str) -> Result<bool>

Returns Ok(true) if key (typically a client IP) is within the rate limit, Ok(false) if the limit has been exceeded, or Err if the Redis server could not be reached.

A call always increments the shared counter, whether permitted or not, so callers must decide for themselves whether to fail open (allow the request) or fail closed (deny it) on Err — this limiter does not silently pick one.

Source

pub fn remaining(&self, key: &str) -> Result<u32>

Number of remaining requests key may make within the current window, or Err if the Redis server could not be reached.

Source

pub fn reset(&self, key: &str) -> Result<()>

Remove all tracked state for key. Useful in tests.

Trait Implementations§

Source§

impl Clone for RedisRateLimiter

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more