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.
§Features
- Token Bucket Algorithm: Efficiently manages request rates.
- IP-based Rate Limiting: Identifies clients by IP address, with support for
X-Forwarded-ForandX-Real-IPheaders. - Configurable: Allows customization of capacity, time window, and cleanup intervals.
- Asynchronous Cleanup: Periodically removes stale rate limit entries to save memory.
- Response Headers: Adds
X-RateLimit-Remaining,X-RateLimit-Limit, andX-RateLimit-Resetheaders to responses. - Customizable Error Response: Returns a
429 Too Many RequestsJSON response when limits are exceeded. - Runtime Agnostic: Supports both
tokio(default) andasync-stdruntimes via feature flags.
§Installation
Add this to your Cargo.toml:
[dependencies]
ntex-ratelimiter = "^0.1.0"§Feature Flags
tokio(default): Enables Tokio runtime support.async-std: Enables async-std runtime support.json(default): Enables JSON serialization for error responses usingserde.
Example with async-std and json:
[dependencies]
ntex-ratelimiter = { version = "^0.1.0", default-features = false, features = ["async-std", "json"] }§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(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
}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 theRateLimiterstruct,RateLimiterConfig,TokenBucketimplementation, and theRateLimitntex middleware.
Re-exports§
pub use tokio;
Structs§
- Rate
Limit - Rate limiting middleware
- Rate
Limit Result - Result of a rate limit check
- Rate
Limiter - High-performance rate limiter using token bucket algorithm
- Rate
Limiter Config - Configuration for the rate limiter
- Rate
Limiter Stats - Statistics about the rate limiter