Expand description
Rate limiting middleware for Salvo.
This middleware protects your server from abuse by limiting the number of requests a client can make within a specified time period. It’s essential for preventing denial-of-service attacks and ensuring fair resource usage.
§Key Components
| Component | Purpose |
|---|---|
RateIssuer | Identifies clients (by IP, user ID, API key, etc.) |
QuotaGetter | Defines rate limits for each client |
RateGuard | Implements the limiting algorithm |
RateStore | Stores rate limit state |
§Built-in Implementations
§Issuers
RemoteIpIssuer: Identifies clients by IP address
§Guards (Algorithms)
FixedGuard: Fixed window algorithm (requiresfixed-guardfeature)SlidingGuard: Sliding window algorithm (requiressliding-guardfeature)
§Stores
MokaStore: In-memory store backed by moka (requiresmoka-storefeature)
§Example
Basic rate limiting by IP address:
ⓘ
use salvo_rate_limiter::{RateLimiter, RemoteIpIssuer, BasicQuota, FixedGuard, MokaStore};
use salvo_core::prelude::*;
let limiter = RateLimiter::new(
FixedGuard::default(),
MokaStore::default(),
RemoteIpIssuer,
BasicQuota::per_minute(100), // 100 requests per minute
);
let router = Router::new()
.hoop(limiter)
.get(my_handler);§Custom Quotas Per User
Different users can have different rate limits:
ⓘ
use salvo_rate_limiter::{QuotaGetter, BasicQuota};
struct TieredQuota;
impl QuotaGetter<String> for TieredQuota {
type Quota = BasicQuota;
type Error = salvo_core::Error;
async fn get<Q>(&self, user_id: &Q) -> Result<Self::Quota, Self::Error>
where
String: std::borrow::Borrow<Q>,
Q: std::hash::Hash + Eq + Sync,
{
// Premium users get higher limits
if is_premium_user(user_id) {
Ok(BasicQuota::per_minute(1000))
} else {
Ok(BasicQuota::per_minute(60))
}
}
}§Response Headers
Enable rate limit headers in responses with .add_headers(true):
X-RateLimit-Limit: Maximum requests allowedX-RateLimit-Remaining: Requests remaining in current windowX-RateLimit-Reset: Unix timestamp when the limit resets
§HTTP Status
When the limit is exceeded, returns 429 Too Many Requests.
Read more: https://salvo.rs
Structs§
- Basic
Quota - A basic quota.
- Celled
Quota - A common used quota has cells field.
- Fixed
Guard fixed-guard - Fixed window implement.
- Moka
Store moka-store - A simple in-memory store for rate limiter.
- Rate
Limiter RateLimiteris the main struct to used limit user request.- Real
IpIssuer - Identify user by their real IP address, supporting proxy headers.
- Remote
IpIssuer - Identify user by the direct connection IP address.
- Sliding
Guard sliding-guard - Sliding window implement.
Traits§
- Quota
Getter - Used to get quota and you can config users’ quota config in database.
- Rate
Guard RateGuardis strategy to verify is the request exceeded quota- Rate
Issuer - Issuer is used to identify every request.
- Rate
Store RateStoreis used to store rate limit data.