Skip to main content

Crate salvo_rate_limiter

Crate salvo_rate_limiter 

Source
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

ComponentPurpose
RateIssuerIdentifies clients (by IP, user ID, API key, etc.)
QuotaGetterDefines rate limits for each client
RateGuardImplements the limiting algorithm
RateStoreStores rate limit state

§Built-in Implementations

§Issuers

§Guards (Algorithms)

  • FixedGuard: Fixed window algorithm (requires fixed-guard feature)
  • SlidingGuard: Sliding window algorithm (requires sliding-guard feature)

§Stores

  • MokaStore: In-memory store backed by moka (requires moka-store feature)

§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 allowed
  • X-RateLimit-Remaining: Requests remaining in current window
  • X-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§

BasicQuota
A basic quota.
CelledQuota
A common used quota has cells field.
FixedGuardfixed-guard
Fixed window implement.
MokaStoremoka-store
A simple in-memory store for rate limiter.
RateLimiter
RateLimiter is the main struct to used limit user request.
RealIpIssuer
Identify user by their real IP address, supporting proxy headers.
RemoteIpIssuer
Identify user by the direct connection IP address.
SlidingGuardsliding-guard
Sliding window implement.

Traits§

QuotaGetter
Used to get quota and you can config users’ quota config in database.
RateGuard
RateGuard is strategy to verify is the request exceeded quota
RateIssuer
Issuer is used to identify every request.
RateStore
RateStore is used to store rate limit data.