Skip to main content

RateLimitConfig

Struct RateLimitConfig 

Source
pub struct RateLimitConfig {
    pub max_requests: usize,
    pub window_secs: Duration,
    pub get_id: fn(req: &ServiceRequest) -> String,
    pub on_exceed: fn(id: &String, config: &RateLimitConfig, req: &ServiceRequest) -> HttpResponse,
}
Expand description

Configuration for rate limiting middleware.

This struct contains all the parameters needed to configure rate limiting behavior, including request limits, time windows, and callback functions for client identification and rate limit exceeded handling.

§Examples

use actix_web::HttpResponse;
use actix_web_ratelimit::config::RateLimitConfig;

// Basic configuration
let config = RateLimitConfig::default()
    .max_requests(100)
    .window_secs(3600);

// Advanced configuration with custom handlers
let config = RateLimitConfig::default()
    .max_requests(10)
    .window_secs(60)
    .id(|req| {
        // Custom client identification based on API key
        req.headers()
            .get("X-API-Key")
            .and_then(|h| h.to_str().ok())
            .unwrap_or("anonymous")
            .to_string()
    })
    .exceeded(|id, _config, _req| {
        // Custom rate limit exceeded response
        HttpResponse::TooManyRequests()
            .body(format!("Rate limit exceeded for client: {}", id))
    });

Fields§

§max_requests: usize

Maximum number of requests allowed within the time window

§window_secs: Duration

Duration of the sliding time window

§get_id: fn(req: &ServiceRequest) -> String

Function to extract client identifier from the request. Typically extracts IP address, but can be customized for API keys, user IDs, etc.

§on_exceed: fn(id: &String, config: &RateLimitConfig, req: &ServiceRequest) -> HttpResponse

Function called when rate limit is exceeded. Receives the client ID, configuration, and request, returns the HTTP response.

Implementations§

Source§

impl RateLimitConfig

Source

pub fn max_requests(self, value: usize) -> Self

Sets the maximum number of requests allowed within the time window.

§Arguments
  • value - Maximum number of requests (must be > 0)
§Example
use actix_web_ratelimit::config::RateLimitConfig;

let config = RateLimitConfig::default().max_requests(100);
Source

pub fn window_secs(self, value: u64) -> Self

Sets the time window duration in seconds for the sliding window algorithm.

§Arguments
  • value - Time window duration in seconds
§Example
use actix_web_ratelimit::config::RateLimitConfig;

// Allow 100 requests per hour
let config = RateLimitConfig::default()
    .max_requests(100)
    .window_secs(3600);
Source

pub fn id(self, fn_id: fn(req: &ServiceRequest) -> String) -> Self

Sets a custom function to extract client identifier from requests.

By default, the middleware uses the client’s IP address as identifier. This method allows customization based on headers, authentication, etc.

§Arguments
  • fn_id - Function that takes a ServiceRequest and returns a client identifier string
§Examples
use actix_web_ratelimit::config::RateLimitConfig;

// Rate limit by API key
let config = RateLimitConfig::default()
    .id(|req| {
        req.headers()
            .get("X-API-Key")
            .and_then(|h| h.to_str().ok())
            .unwrap_or("anonymous")
            .to_string()
    });

// Rate limit by custom header
let config = RateLimitConfig::default()
    .id(|req| {
        // Extract user ID from custom header
        req.headers()
            .get("X-User-ID")
            .and_then(|h| h.to_str().ok())
            .unwrap_or("guest")
            .to_string()
    });
Source

pub fn exceeded( self, fn_exceed: fn(id: &String, config: &RateLimitConfig, req: &ServiceRequest) -> HttpResponse, ) -> Self

Sets a custom function to handle rate limit exceeded scenarios.

By default, returns HTTP 429 with “Too many requests” message. This method allows customization of the response format, headers, etc.

§Arguments
  • fn_exceed - Function that takes client ID, config, and request, returns HTTP response
§Examples
use actix_web::HttpResponse;
use actix_web_ratelimit::config::RateLimitConfig;

// Custom error response with details
let config = RateLimitConfig::default()
    .exceeded(|id, config, _req| {
        HttpResponse::TooManyRequests()
            .body(format!(
                "Rate limit exceeded for client: {}. Limit: {} requests per {} seconds.",
                id,
                config.max_requests,
                config.window_secs.as_secs()
            ))
    });

// Custom headers and retry-after
let config = RateLimitConfig::default()
    .exceeded(|_id, config, _req| {
        HttpResponse::TooManyRequests()
            .append_header(("Retry-After", config.window_secs.as_secs()))
            .append_header(("X-RateLimit-Limit", config.max_requests))
            .body("Rate limit exceeded. Please try again later.")
    });

Trait Implementations§

Source§

impl Clone for RateLimitConfig

Source§

fn clone(&self) -> RateLimitConfig

Returns a duplicate of the value. Read more
1.0.0 · Source§

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

Performs copy-assignment from source. Read more
Source§

impl Default for RateLimitConfig

Source§

fn default() -> Self

Creates a default rate limiting configuration.

§Default Values
  • max_requests: 10 requests
  • window_secs: 100 seconds
  • get_id: Extracts real IP address from connection info
  • on_exceed: Returns HTTP 429 “Too Many Requests” with plain text body
§Example
use actix_web_ratelimit::config::RateLimitConfig;

let config = RateLimitConfig::default();
assert_eq!(config.max_requests, 10);

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<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> Same for T

Source§

type Output = T

Should always be Self
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
Source§

impl<T> ErasedDestructor for T
where T: 'static,