ntex-ratelimiter
A high-performance rate limiting middleware for the ntex web framework.
Installation
Add this to your Cargo.toml:
[]
= "0.1.1"
Feature Flags
tokio(default): Enable Tokio runtime supportasync-std: Enable async-std runtime supportjson(default): Enable JSON serialization for error responses
[]
# Default features (tokio + json)
= "0.1.1"
# With async-std instead of tokio
= { = "0.1.1", = false, = ["async-std", "json"] }
# Minimal build without JSON support
= { = "0.1.1", = false, = ["tokio"] }
Quick Start
use ;
use ;
async
Advanced Configuration
For more control over the rate limiter behavior:
use ;
use Duration;
let config = RateLimiterConfig ;
let limiter = with_config;
// Get statistics
let stats = limiter.stats;
println!;
How It Works
This middleware uses the token bucket algorithm for rate limiting:
- Each client IP gets a token bucket with a configured capacity
- Tokens are consumed on each request
- Tokens are refilled at a constant rate based on the time window
- When the bucket is empty, requests are rate limited
Client IP Detection
The middleware intelligently extracts client IPs from:
X-Forwarded-Forheader (first IP in comma-separated list)X-Real-IPheader- Connection remote address (fallback)
This ensures accurate rate limiting even behind proxies and load balancers.
Response Headers
The middleware adds these headers to all responses:
| Header | Description |
|---|---|
x-ratelimit-remaining |
Number of requests remaining in current window |
x-ratelimit-limit |
Total request limit for the window |
x-ratelimit-reset |
Unix timestamp when the rate limit resets |
Error Response
When rate limits are exceeded, a 429 Too Many Requests response is returned:
Configuration Options
RateLimiterConfig
| Field | Type | Default | Description |
|---|---|---|---|
capacity |
usize |
100 | Maximum requests allowed in the time window |
window |
u64 |
60 | Time window in seconds |
cleanup_interval |
Duration |
5 minutes | How often to clean up stale entries |
stale_threshold |
u64 |
1 hour | How long before entries are considered stale |
Examples
Basic Web API
use ;
use ;
async
async
Multiple Rate Limits
use ;
use ;
async
Testing
Run the test suite:
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
This project is licensed under the MIT License - see the LICENSE file for details.