Skip to main content

Crate ntex_ratelimiter

Crate ntex_ratelimiter 

Source
Expand description

§ntex-ratelimiter

ntex-ratelimiter is a rate limiting middleware for the ntex web framework. It uses the token bucket algorithm to limit the number of requests from clients based on their IP address, or on any custom key (e.g. an API token id).

§Features

  • Token Bucket Algorithm: Efficiently manages request rates.
  • IP-based Rate Limiting: Identifies clients by IP address.
  • Custom Keys: RateLimiter<K> works with any Hash + Eq + Clone key, either in a handler or via RateLimit::with_key.
  • Spoofing-Resistant: Defaults to the unspoofable peer socket address; X-Forwarded-For is only read from trusted_proxies, taking the rightmost untrusted hop.
  • Bounded Memory: A max_entries cap routes excess unseen keys to a shared overflow bucket, so rotating-IP attacks cannot exhaust memory.
  • Configurable: Capacity, time window, cleanup interval, proxy-header trust, and max entries.
  • Inline Cleanup: Periodically removes buckets that have refilled to capacity (lossless) to save memory, without a background task.
  • Response Headers: Adds X-RateLimit-Remaining, X-RateLimit-Limit, and X-RateLimit-Reset headers to responses, plus Retry-After on 429.
  • Customizable Error Response: Returns a 429 Too Many Requests JSON response when limits are exceeded.
  • Runtime Agnostic: Spawns no tasks, so it works on every ntex runtime (tokio, compio, neon) with no feature flags.

§Installation

Add this to your Cargo.toml:

[dependencies]
ntex-ratelimiter = "^0.4.0"

§Quick Start

use ntex::web;
use ntex_ratelimiter::{RateLimit, RateLimiter};

#[ntex::main]
async fn main() -> std::io::Result<()> {
    // Create a rate limiter: 100 requests per 60 seconds
    let limiter = RateLimiter::new(100, 60);
     
    web::HttpServer::new(async move || {
        web::App::new()
            // Apply rate limiting middleware
            .wrap(RateLimit::new(limiter.clone()))
            .service(web::resource("/").to(|| async { "Hello world!" }))
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}

§Custom Keys

To limit by something other than the client IP (e.g. an API token), use a RateLimiter<K> and check it in the handler after authentication:

use ntex::web::{self, HttpRequest, HttpResponse};
use ntex_ratelimiter::RateLimiter;
use std::sync::Arc;

fn authenticate(req: &HttpRequest) -> Option<String> {
    // Validate the credential and return a stable token id.
}

async fn mcp(
    req: HttpRequest,
    limiter: web::types::State<Arc<RateLimiter<String>>>,
) -> HttpResponse {
    let Some(token_id) = authenticate(&req) else {
        return HttpResponse::Unauthorized().finish();
    };
    let result = limiter.check_rate_limit(&token_id);
    if !result.allowed {
        return HttpResponse::TooManyRequests()
            .header("retry-after", result.retry_after.to_string())
            .finish();
    }
    HttpResponse::Ok().body("ok")
}

#[ntex::main]
async fn main() -> std::io::Result<()> {
    // 60 requests per minute per token
    let limiter = RateLimiter::<String>::new(60, 60);

    web::HttpServer::new(async move || {
        web::App::new()
            .state(limiter.clone())
            .service(web::resource("/mcp").route(web::post().to(mcp)))
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}

RateLimit::with_key does the same as middleware; see its docs for the caveat about keying on unverified credentials.

For more advanced usage and configuration, please refer to the documentation of RateLimiter and RateLimiterConfig.

§Module Structure

  • limiter: Contains the core rate limiting logic, including the RateLimiter struct, RateLimiterConfig, TokenBucket implementation, and the RateLimit ntex middleware.

Structs§

PeerIp
Keys requests by client IP (see RateLimiterConfig::trusted_proxies).
RateLimit
Rate limiting middleware
RateLimitResult
Result of a rate limit check
RateLimiter
High-performance rate limiter using token bucket algorithm.
RateLimiterConfig
Configuration for the rate limiter
RateLimiterStats
Statistics about the rate limiter

Enums§

IpNet
An IP network address, either IPv4 or IPv6.

Traits§

KeyExtractor
Decides how RateLimit rate-limits a request.