route-ratelimit
Route-based rate limiting middleware for reqwest.
Features
- Endpoint matching: Match requests by host, HTTP method, and path prefix
- Multiple rate limits: Stack burst and sustained limits on the same endpoint
- Configurable behavior: Choose to delay requests or return errors per endpoint
- Lock-free performance: Uses GCRA algorithm with atomic operations
- Shared state: Rate limits are tracked across all client clones
Installation
Add to your Cargo.toml:
[]
= "0.1"
= "0.12"
= "0.4"
Quick Start
use RateLimitMiddleware;
use ClientBuilder;
use Duration;
async
Usage
Host-Scoped Routes
Organize rate limits by host for cleaner configuration:
use RateLimitMiddleware;
use Duration;
use Method;
let middleware = builder
.host
.build;
Multiple Limits (Burst + Sustained)
Apply both burst and sustained limits to the same endpoint:
use RateLimitMiddleware;
use Duration;
let middleware = builder
.route
.build;
Error Behavior
By default, requests are delayed until they can proceed. Use ThrottleBehavior::Error to fail fast:
use ;
use Duration;
let middleware = builder
.route
.build;
Route Matching
All Matching Routes Apply
Routes are checked in order, and all matching routes' limits are applied. This allows layering general limits with specific ones:
use RateLimitMiddleware;
use Duration;
let middleware = builder
.host
.build;
Host Matching
Host matching uses only the hostname, excluding the port:
// Matches: https://api.example.com/path
// Matches: https://api.example.com:8443/path
// Does NOT match: https://other.example.com/path
.host
Path Matching
Path matching uses segment boundaries, not simple prefix matching:
| Pattern | Matches | Does NOT Match |
|---|---|---|
/order |
/order, /order/, /order/123 |
/orders, /order-test |
/api/v1 |
/api/v1/users, /api/v1/ |
/api/v2, /api/v10 |
Optional Features
Tracing Support
Enable the tracing feature for diagnostic logging:
[]
= { = "0.1", = ["tracing"] }
This enables warnings for potentially problematic configurations (e.g., catch-all routes preceding specific routes).
Memory Management
For long-running applications, periodically clean up stale rate limit state:
use RateLimitMiddleware;
use Duration;
let middleware = builder
.route
.build;
// Call periodically (e.g., every hour)
middleware.cleanup;
// Monitor state size
println!;
Examples
See the examples directory for complete usage examples:
- Polymarket API - Complete rate limit configuration for a real-world API
Minimum Supported Rust Version
This crate requires Rust 1.88.0 or later.
License
Licensed under the MIT License. See LICENSE for details.